forked from smhanov/jzbuild
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjzbuild.py
executable file
·2487 lines (2191 loc) · 130 KB
/
jzbuild.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/python
"""
JZBUILD Javascript build system
By Steve Hanov ([email protected])
This is free software. It is released to the public domain.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
The JZBUILD software may include jslint software, which is covered under the
following license.
/*
Copyright (c) 2002 Douglas Crockford (www.JSLint.com)
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
The Software shall be used for Good, not Evil.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
Coffeescript is covered under the following license.
Copyright (c) 2011 Jeremy Ashkenas
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
------------------------------------------------------------------------------
------------------------------------------------------------------------------
------------------------------------------------------------------------------
JCoffeeScript is covered under the following license:
/*
* Copyright 2010 David Yeung
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
"""
import re
import os
import platform
import subprocess
import sys
import urllib2
import cStringIO
import zipfile
import glob
import base64
import zlib
import tempfile
import atexit
MAKEFILE_NAME = "makefile.jz"
NEVER_CHECK_THESE_FILES = """
jquery.min.js
jquery.js
prototype.js
""".split("\n")
COMPILERS = {
# Name of the compiler, as specified in the makefile and the --compiler
# option.
"closure": {
# URL at which to download a zipfile of the compiler
"download":
"http://closure-compiler.googlecode.com/files/compiler-latest.zip",
# full path in the zip file of the compiler.
"filename":
"compiler.jar",
# These options are always specified.
"requiredOptions": [],
# Command line option that must precede each input filename
"inputOption":
"--js",
# Command line option to specify the output file
"outputOption":
"--js_output_file",
# Default options to use if none are specified
"defaultOptions": [
"--compilation_level", "SIMPLE_OPTIMIZATIONS",
"--warning_level", "VERBOSE" ],
# Options to use if none are specified and user is doing a --release
# build.
"releaseOptions": [
"--compilation_level", "ADVANCED_OPTIMIZATIONS",
"--warning_level", "VERBOSE" ],
# Set this to True if the tool can't take the input on the command
# line, and instead requires input to be concatenated together and
# piped to its standard input.
"requiresStdin": False,
},
"yui": {
"download":
"http://yui.zenfs.com/releases/yuicompressor/yuicompressor-2.4.2.zip",
"filename":
"yuicompressor-2.4.2/build/yuicompressor-2.4.2.jar",
"requiredOptions": ["--type", "js"],
"inputOption": "",
"outputOption": "-o",
"defaultOptions": [],
"requiresStdin": True,
},
}
EXTERNS = {
"jquery-1.5.js":
"http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/jquery-1.5.js",
"json.js":
"http://closure-compiler.googlecode.com/svn/trunk/contrib/externs/json.js",
"jquery-mobile.js":
"http://github.com/smhanov/jzbuild/raw/master/externs/jquery-mobile.js",
}
JCOFFEESCRIPT_URL = \
"http://github.com/downloads/smhanov/jcoffeescript/jcoffeescript-1.1.jar"
COFFEESCRIPT_URL = \
"http://github.com/downloads/smhanov/coffee-script/coffee-script.js"
def GetStorageFolder():
"""Returns the path to a location where we can store downloads"""
# Seems to work on windows 7 too
path = os.path.join(os.path.expanduser("~"), ".jzbuild")
if not os.path.isdir(path):
print "Creating %s" % path
os.mkdir(path)
return path
JCOFFEESCRIPT_PATH = \
os.path.join(GetStorageFolder(), os.path.basename( JCOFFEESCRIPT_URL ) )
COFFEESCRIPT_PATH = \
os.path.join(GetStorageFolder(), os.path.basename( COFFEESCRIPT_URL ) )
VALID_COMPILERS = COMPILERS.keys();
VALID_COMPILERS.append("cat")
MAN_PAGE = """
NAME
jzbuild - The easy Javascript build system
SYNOPSIS
jzbuild [files or projects]
DESCRIPTION
Runs jslint and joins together javascript input files, optionally using the
Google closure compiler or YUI compressor to reduce file size and find more
errors.
Jzbuild looks for a file named "makefile.jz" in the current folder. If
found, it reads the list of projects and options from that file. Otherwise,
it uses the options given from the command line, or defaults.
Jzbuild will download and use the Coffeescript compiler to seemlessly
handle files ending in ".coffee".
[files]
If no filenames are given and no makefile is present, Jzbuild will
run jslint on all files matching the pattern "*.js" in the current
folder.
[projects]
If a makefile is present, the names given on the command line refer to
projects in the makefile.
--out <output>
Specifies output file name. If an output file is given, the makefile is
ignored. This option is called "output" in the makefile.
--prepend <filename>
Specifies a file for prepending. The include path will be searched for
the file, and it will be prepended to the output. This option may be
specified multiple times. This option is ignored if a makefile is
resent.
-I<path>
Specifies a folder to be searched for included files. This option may
be specified multiple times. The current folder is always in the
include path. This option is ignored if a makefile is present.
--compiler
Specifies the compiler to use. This option is ignored if a makefile is
present. Valid options are VALID_COMPILERS. If you do not have the
given compiler, it will be downloaded.
--release
Specifies that we should use a advanced compilation options, such
as minification, if available.
clean
If the word "clean" is given as an option, the output file is erased
instead of created, and JSLINT is not run.
MAKEFILE FORMAT
When jzbuild starts, it runs in one of two modes --
1. If the '--out' option is not specified, it searches the current
folder for a file named "MAKEFILE_JZ". If it is found, the settings
are processed as described below.
2. If the "--out" option is given, or MAKEFILE_JZ is not found, then it
builds a list of input files from '*.js', excluding any common
javascript libraries such as jquery.
The makefile is formatted in Lazy JSON. This is exactly like JSON, except
that quotes and commas are optional. The Makefile consists of a single
object whos keys are project names. For example:
{
release: {
input: [ foo.js bar.js ]
include: [ ../shared ]
output: foo-compressed.js
compiler: closure
}
yui {
base: release
output: foo-yui-compressed.js
compiler: yui
}
}
The above defines two projects named "release", and "yui". The release
project consists of foo.js and bar.js, as well as any files that they
include. The include path searched is the current folder as well as
"../shared".
The yui project specifies "base: release". That means that it inherits any
unset properties from the project named "release".
Here is a list of valid options for a project:
input
A string or array of files that will be compiled together, along
with any files they include.
output
The output filename. If none is given, the compiler will not run.
Only JSLINT checking will be performed.
include
A single string, or array of strings that specify the paths to
search when looking for input files, or the files that they
include. The current folder is always part of the include path.
compiler
The name of the compiler to use. Valid compilers are
VALID_COMPILERS. The default is "cat"
compilerOptions
Compiler options to use. Jzbuild contains suitable defaults for
each compiler. But they can be overridden.
base
Specifies another project from which to inherit the above settings.
prepend
A single string, or array of strings specifying the names of files
which are prepended to the output. No error checking is performed
on these files, and they are not compiled.
""".replace("VALID_COMPILERS",
",".join(VALID_COMPILERS)).replace("MAKEFILE_JZ", MAKEFILE_NAME)
# Make these variables global, and set them later.
JSLINT_RHINO = ""
JSLINT_WSH = ""
CLOSURE_EXTERNS = ""
# Keep temporary files here so they are not deleted until program exit.
# There are problems with using NamedTemporaryFile delete=True on windows, so
# do it manually.
TemporaryFiles = []
def cleanupBeforeExit():
for temp in TemporaryFiles:
if os.path.exists( temp.name ):
temp.close()
os.unlink( temp.name )
atexit.register( cleanupBeforeExit )
class LazyJsonParser:
"""This class parses Lazy JSON. Currently it does not take advantage of
python language features such as generators or regular expressions. It
is designed to be a reference decoder that is easily portable to other
languages such as Javascript and C.
"""
class Token:
def __init__(self, type, start, length):
self.type = type
self.start = start
self.length = length
def getText( self, text ):
return text[self.start:self.start + self.length]
def __init__(self, text):
self.text = text
self.pos = -1
# Possible token types
self.TOKEN_EOF = -2
self.TOKEN_ERROR = -1
self.TOKEN_LEFT_BRACE = 0
self.TOKEN_RIGHT_BRACE = 1
self.TOKEN_LEFT_BRACKET = 2
self.TOKEN_RIGHT_BRACKET = 3
self.TOKEN_STRING = 4
self.TOKEN_COLON = 5
# Possible values of STATE
self.STATE_START = 0
self.STATE_WHITESPACE = 1
self.STATE_SLASH = 2
self.STATE_SLASH_SLASH = 3
self.STATE_SLASH_STAR = 4
self.STATE_SLASH_STAR_STAR = 5
self.STATE_STRING = 6
self.STATE_SQUOTED_STRING = 7
self.STATE_SQUOTED_STRING2 = 8
self.STATE_SESCAPE = 9
self.STATE_DQUOTED_STRING = 10
self.STATE_DQUOTED_STRING2 = 11
self.STATE_DESCAPE = 12
self.ACTION_SINGLE_CHAR = 1
self.ACTION_SUBTRACT_1 = 2
self.ACTION_SUBTRACT_2 = 4
self.ACTION_STORE_POS = 8
self.ACTION_TOKEN = 16
self.ACTION_ERROR = 17
# Represents any character in the state machine transition table.
self.ANY = ''
# Represents whitespace in the state machine transition table.
WS = "\n\r\t ,"
# There are better ways of writing a tokenizer in python. However, I
# wanted a parser for Lazy JSON that is easily portable to other languages such as C.
self.fsm = [
# in state, when we get this char, switch to state, perform these actions, action data
[ self.STATE_START, '{', self.STATE_START, self.ACTION_SINGLE_CHAR, self.TOKEN_LEFT_BRACE ],
[ self.STATE_START, '}', self.STATE_START, self.ACTION_SINGLE_CHAR, self.TOKEN_RIGHT_BRACE ],
[ self.STATE_START, '[', self.STATE_START, self.ACTION_SINGLE_CHAR, self.TOKEN_LEFT_BRACKET ],
[ self.STATE_START, ']', self.STATE_START, self.ACTION_SINGLE_CHAR, self.TOKEN_RIGHT_BRACKET ],
[ self.STATE_START, ':', self.STATE_START, self.ACTION_SINGLE_CHAR, self.TOKEN_COLON ],
[ self.STATE_START, WS, self.STATE_WHITESPACE, 0 ],
[ self.STATE_START, '/', self.STATE_SLASH, 0 ],
[ self.STATE_START, '"', self.STATE_DQUOTED_STRING, 0 ],
[ self.STATE_START, "'", self.STATE_SQUOTED_STRING, 0 ],
[ self.STATE_START, self.ANY, self.STATE_STRING, self.ACTION_STORE_POS | self.ACTION_SUBTRACT_1 ],
[ self.STATE_WHITESPACE, WS, self.STATE_WHITESPACE, 0 ],
[ self.STATE_WHITESPACE, self.ANY, self.STATE_START, self.ACTION_SUBTRACT_1 ],
[ self.STATE_SLASH, '/', self.STATE_SLASH_SLASH, 0 ],
[ self.STATE_SLASH, '*', self.STATE_SLASH_STAR, 0 ],
[ self.STATE_SLASH, self.ANY, self.STATE_STRING, self.ACTION_SUBTRACT_2 | self.ACTION_STORE_POS ],
[ self.STATE_SLASH_SLASH, '\n', self.STATE_START, 0 ],
[ self.STATE_SLASH_SLASH, self.ANY, self.STATE_SLASH_SLASH, 0 ],
[ self.STATE_SLASH_STAR, '*', self.STATE_SLASH_STAR_STAR, 0 ],
[ self.STATE_SLASH_STAR, self.ANY, self.STATE_SLASH_STAR, 0 ],
[ self.STATE_SLASH_STAR_STAR, '/', self.STATE_START, 0 ],
[ self.STATE_SLASH_STAR_STAR, self.ANY, self.STATE_SLASH_STAR, 0 ],
[ self.STATE_STRING, "[]{}:"+WS, self.STATE_START, self.ACTION_TOKEN | self.ACTION_SUBTRACT_1, self.TOKEN_STRING ],
[ self.STATE_STRING, self.ANY, self.STATE_STRING, 0 ],
[ self.STATE_DQUOTED_STRING, self.ANY, self.STATE_DQUOTED_STRING2, self.ACTION_STORE_POS | self.ACTION_SUBTRACT_1 ],
[ self.STATE_DQUOTED_STRING2, '\n', self.STATE_DQUOTED_STRING2, self.ACTION_ERROR, "Newline in string"],
[ self.STATE_DQUOTED_STRING2, '\\', self.STATE_DESCAPE, 0 ],
[ self.STATE_DQUOTED_STRING2, '"', self.STATE_START, self.ACTION_TOKEN, self.TOKEN_STRING ],
[ self.STATE_DQUOTED_STRING2, self.ANY, self.STATE_DQUOTED_STRING2, 0 ],
[ self.STATE_DESCAPE, self.ANY, self.STATE_DQUOTED_STRING2, 0 ],
[ self.STATE_SQUOTED_STRING, self.ANY, self.STATE_SQUOTED_STRING2, self.ACTION_STORE_POS | self.ACTION_SUBTRACT_1 ],
[ self.STATE_SQUOTED_STRING2, '\n', self.STATE_SQUOTED_STRING2, self.ACTION_ERROR, "Newline in string"],
[ self.STATE_SQUOTED_STRING2, '\\', self.STATE_SESCAPE, 0 ],
[ self.STATE_SQUOTED_STRING2, "'", self.STATE_START, self.ACTION_TOKEN, self.TOKEN_STRING ],
[ self.STATE_SQUOTED_STRING2, self.ANY, self.STATE_SQUOTED_STRING2, 0 ],
[ self.STATE_SESCAPE, self.ANY, self.STATE_SQUOTED_STRING2, 0 ],
]
# One previous token is allowed to be unshifted back. Store that token here.
self.unshifted = None
def unshift(self, token):
self.unshifted = token
def next(self):
"""Get the next token. Returns an object with the type, start, and
length of the token in the text."""
# Return the unshifted token if there is one.
if self.unshifted != None:
token = self.unshifted
self.unshifted = None
return token
state = self.STATE_START
storedPos = 0
while 1:
self.pos = self.pos + 1
#print "%c: %d" % (self.text[self.pos], state)
if self.pos >= len(self.text):
if state == self.STATE_START:
return LazyJsonParser.Token(self.TOKEN_EOF, self.pos, 0)
else:
return LazyJsonParser.Token(self.TOKEN_ERROR, self.pos, 0)
for transition in self.fsm:
if transition[0] == state and (transition[1] == self.ANY
or self.text[self.pos] in transition[1]):
originalPos = self.pos
if transition[3] & self.ACTION_STORE_POS:
storedPos = self.pos
if transition[3] & self.ACTION_SUBTRACT_1:
self.pos -= 1
if transition[3] & self.ACTION_SUBTRACT_2:
self.pos -= 2
if transition[3] & self.ACTION_SINGLE_CHAR:
return LazyJsonParser.Token( transition[4], originalPos, 1 )
if transition[3] & self.ACTION_TOKEN:
pos = self.pos
return LazyJsonParser.Token( transition[4], storedPos, originalPos -
storedPos )
if transition[3] & self.ACTION_ERROR:
self.error( LazyJsonParser.Token( self.TOKEN_ERROR,
originalPos, transition[4] ) )
state = transition[2]
break
else:
return LazyJsonParser.Token( self.TOKEN_ERROR, self.pos, 1 )
def unescape( self, str ):
"""Unescape JSON string"""
ret = ""
i = 0
while i < len( str ):
if i < len( str ) - 1 and str[i] == '\\':
i += 1
if str[i] == 'b':
ret += '\b'
elif str[i] == 'f':
ret += '\f'
elif str[i] == 'n':
ret += '\n'
elif str[i] == 'r':
ret += '\r'
elif str[i] == 't':
ret += '\t'
else:
ret += str[i]
else:
ret += str[i]
i += 1
return ret
def parse( self ):
""" Parse a single item, which may contain other items """
token = self.next()
if token.type == self.TOKEN_EOF:
return None
if token.type == self.TOKEN_LEFT_BRACE:
# Parse a list of string : item, followed by brace
value = {}
while 1:
token = self.next()
if token.type == self.TOKEN_RIGHT_BRACE:
break
elif token.type == self.TOKEN_STRING:
key = self.unescape(token.getText(self.text))
else:
self.error( token, "Expected a string" )
token = self.next()
if token.type != self.TOKEN_COLON:
self.error( token, "Expected ':'" )
value[key] = self.parse()
elif token.type == self.TOKEN_LEFT_BRACKET:
# Parse list of strings followed by bracket
value = []
while 1:
token = self.next()
if token.type == self.TOKEN_RIGHT_BRACKET:
break
elif token.type < 0:
self.error( token, "Expected ']'" )
self.unshift( token )
item = self.parse()
value.append( item )
elif token.type == self.TOKEN_STRING:
# Just a string.
value = self.unescape(token.getText(self.text))
else:
self.error( token, "Expected: '{', '[', or string" )
return value
def error( self, token, message ):
line = 1
pos = 1
for i in range( token.start ):
if self.text[i] == '\n':
line += 1
pos = 1
else:
pos += 1
raise Exception( "Error on line %d:%d: %s" % (line, pos, message) )
def ParseLazyJson( text ):
"""Wrapper for LazyJsonParser class that transforms Lazy JSON or JSON text
into a python object."""
return LazyJsonParser(text).parse();
# Global variable to say whether we are on windows.
IsWindows = platform.system() == "Windows"
def ReplaceSlashes(list):
"""Transform unix style slashes into the path separator of the system that
we are running on"""
if os.path.sep == '/': return list
newList = []
for item in list:
newList.append( item.replace( "/", os.path.sep ) )
return newList
class DependencyGraph:
""" Represents a dependency graph. A dependency graph contains items that
depend on other items. After adding all of the nodes, you can call the
walk() method to get a list of the items in topological order.
"""
def __init__(self):
self.nodes = {}
def addDependency(self, child, parent):
"""Add a dependency to the graph. The child and parent nodes are added to
the graph if not already present. Then, the child depends on the
parent. It is not necessary to call the addNode() method to add the nodes
first.
"""
child = self.__getNodeFor( child )
parent = self.__getNodeFor( parent )
if not self.__find( child, parent ):
parent.children.append( child )
child.parents.append( parent )
return True
else:
return False
def __find( self, parent, node ):
"""Searches the parent for the given node, and if found, returns True
"""
if parent == node: return True
for child in parent.children:
if self.__find( child, node ):
return True
return False
def addNode( self, data ):
"""Adds a single node to the graph with no dependencies. Dependencies may
be added afterward using the addDepenency() method. If no dependencies are
added, then the node will appear early in the topological sort.
"""
self.__getNodeFor( data )
def walk( self ):
"""Returns the topological sort of the nodes.
"""
L = []
S = [n for n in self.nodes.values() if len(n.parents) == 0]
while len(S) > 0:
n = S.pop()
L.append( n )
for m in n.children[:]:
del n.children[n.children.index(m)]
del m.parents[m.parents.index(n)]
if len( m.parents ) == 0:
S.append( m )
return [s.data for s in L]
def __getNodeFor( self, data ):
if data in self.nodes:
return self.nodes[data]
self.nodes[data] = self.__DependencyNode( data )
return self.nodes[data]
class __DependencyNode:
""" Represents a node in the dependency graph. This class is used
internally in the dependency graph. """
def __init__(self, data):
self.data = data
self.parents = []
self.children = []
class Analysis:
"""
Analyses the javascript files and stores the result. The analysis includes
a topological sort of included files as well as a list of exports.
fileListIn specifies a list of files
vpath is a list of folders in which to search for the files in the file list
as well as any included files.
"""
def __init__(self, fileListIn, vpath):
graph = DependencyGraph()
# Set of fully qualified paths that we have already processed.
filesProcessed = {}
# List of files awaiting processing
filesToProcess = []
self.exports = []
includeRe_js = re.compile(r"""\/\/#include\s+[<"]([^>"]+)[>"]""")
exportRe_js = re.compile(r"""\/\/\@export ([A-Za-z_\$][A-Za-z_0-9\.\$]*)""")
includeRe_coffee = re.compile(r"""#include\s+[<"]([^>"]+)[>"]""")
exportRe_coffee = re.compile(r"""#@export ([A-Za-z_\$][A-Za-z_0-9\.\$]*)""")
self.vpath = vpath
# contains named temporary files. They will be automatically deleted by
# python when the Analysis goes out of scope.
self.tempFiles = []
def processFile( path ):
"""Given the full path to a file, open it and look for includes. For
each include found, add it to the file list and update the dependency
graph with the dependency.
"""
contents = open( path, "r" ).readlines()
graph.addNode( path )
filesProcessed[path] = 1;
if path.endswith(".coffee"):
includeRe = includeRe_coffee
exportRe = exportRe_coffee
else:
includeRe = includeRe_js
exportRe = exportRe_js
for line in contents:
m = exportRe.search( line )
if m:
self.exports.append( m.group(1) )
m = includeRe.match( line )
if not m: continue
includedPath = self.__findFile( m.group(1) )
if includedPath:
if includedPath not in filesProcessed:
filesToProcess.append( includedPath )
graph.addDependency( path, includedPath )
else:
print 'Error: Could not find file "%s" included from "%s"' % \
(m.group(1), path )
# Augment each file passed in with full path information.
for name in fileListIn:
path = self.__findFile( name )
if path:
filesToProcess.append( path )
else:
print "File not found: " + name
# while the file list is not empty, remove and process a file.
while len( filesToProcess ):
processFile( filesToProcess.pop() )
# spit out dependencies...
self.fileList = graph.walk()
def addFileToStart( self, filename ):
"""
Add a file to the start. This is used to place the coffee script
utilities at the top of the compiled output. It is different from
prepended files because the contents are passed to the compiler,
whereas prepended files are not.
"""
self.fileList = [filename] + self.fileList
def addContentToStart( self, contents ):
temp = tempfile.NamedTemporaryFile( mode="wb", delete=False )
temp.write(contents)
self.tempFiles.append( temp.name )
self.addFileToStart( temp.name )
def prependFiles( self, fileNames ):
"""Search for each file in the vpath and prepend its path to the
filelist returned by getFileList()
"""
files = []
for name in fileNames:
path = self.__findFile( name )
if path != none:
files.append( path )
else:
print "File not found: %s" % name
files.extend( self.fileList )
self.fileList = files
def __findFile( self, file ):
# for each vpath entry,
for path in self.vpath:
# join it with the filename
fullname = os.path.join(path, file)
(base, ext) = os.path.splitext(fullname)
# if it exists, return it.
if os.path.exists( base + ".coffee" ):
return base + ".coffee"
elif os.path.exists( fullname ):
return fullname
else:
return None
def getFileList(self):
return self.fileList
def replaceFile(self, source, destination):
for i in range(len(self.fileList)):
if self.fileList[i] == source:
self.fileList[i] = destination
return
def getExports(self):
# keep track of exports already written.
written = {}
str = ""
# for each export,
for export in self.exports:
if export in written: continue
written[export] = 1
# split into . components.
names = export.split(".")
if len(names) == 1:
# one component. use window["name"] = name;
str += 'window["%s"] = %s;\n' % (names[0], export )
else:
# more that one component. Only the last is exported.
str += (".".join(names[:-1]) +
'["%s"] = %s;\n' % (names[-1], export ) )
return str
def getInputFilesEndingWith( self, extension ):
return filter( lambda f: f.endswith( extension), self.fileList )
def RunJsLint(files, targetTime, options):
"""Run Jslint on each file in the list that has a modification time greater
than the targetTime. Returns the number of files processed.
If jslint is not available in the storage folder, then create it.
"""
storagePath = GetStorageFolder()
numProcessed = 0
if IsWindows:
# check if jslint-wsh exists in the same location as this script. if
# not, create one.
jslint = os.path.join( storagePath, "jslint-wsh.js" );
if not os.path.exists( jslint ):
print "%s not found. Creating." % jslint
f = file(jslint, "wb")
f.write(zlib.decompress(base64.b64decode(JSLINT_WSH)))
f.close()
for f in files:
if os.path.getmtime(f) > targetTime and not f.endswith(".coffee"):
print f + "..."
os.system("cscript /Nologo \"" + jslint + "\" <\"%s\"" % f)
numProcessed += 1
else:
# Create the jslint-rhino file if it does not exist.
jslint = os.path.join( storagePath, "jslint-rhino.js" );
if not os.path.exists( jslint ):
print "%s not found. Creating." % jslint
f = file(jslint, "wb")
f.write(zlib.decompress(base64.b64decode(JSLINT_RHINO)))
f.close()
# run the JSlint-rhino file on any files which are newer than the
# target.
cmd = []
cmd.extend(options.rhinoCmd)
cmd.append( jslint )
for f in files:
if f.endswith(".coffee"): continue
if os.path.getmtime(f) > targetTime:
cmd.append(f);
numProcessed += 1
if numProcessed > 0:
subprocess.call(cmd)
return numProcessed
def CompileCoffeeScript( analysis, options, compiler, joined ):
"""
For files that end in .coffee, compile them to .coffee.js if they are
newer than the existing .js file.
compiler is the name of the compiler that will be used.
noJoin is specified when there is no output file. In that case, all the
coffeescript files will be translated, but they will not be joined
together later. That affects the options that we use.
"""
anyCoffee = False
closureMode = compiler == 'closure' or joined
for filename in analysis.getFileList():
(path, ext) = os.path.splitext(filename)
if ext == ".coffee":
destination = path + ".coffee.js"
anyCoffee = True
if not os.path.exists(destination) or \
os.path.getmtime(destination) < os.path.getmtime(filename):
RunCoffeeScript( filename, destination, closureMode )
analysis.replaceFile( filename, destination )
if anyCoffee:
analysis.addContentToStart( COFFEESCRIPT_UTILITIES )
def DownloadProgram(url, fileInZip, outputPath):
"""Given a url to a zip file, a path to a file within that zip file, and an
output file, it downloads the zip and extracts it to the given path.
If the target file already exists it does nothing."""
if not os.path.exists( outputPath ):
print "%s not found! Downloading from %s" % (outputPath, url)
url = urllib2.urlopen( url )
dataFile = ""
while 1:
data = url.read( 1024 )
if data == "": break
dataFile += data
print "Read %d bytes\r" % len(dataFile),
zip = zipfile.ZipFile( cStringIO.StringIO( dataFile ), "r" )
file(outputPath, "wb").write(zip.read(fileInZip))
return True
HaveCoffeeScript = os.path.exists( JCOFFEESCRIPT_PATH )
def DownloadCoffeeScript():
global HaveCoffeeScript
if not HaveCoffeeScript:
print "Downloading JCoffeescript..."
open(JCOFFEESCRIPT_PATH, "wb").write( urllib2.urlopen(JCOFFEESCRIPT_URL).read() )
print COFFEESCRIPT_URL
open(COFFEESCRIPT_PATH, "wb").write( urllib2.urlopen(COFFEESCRIPT_URL).read() )
HaveCoffeeScript = True
def RunCoffeeScript( source, destination, closureMode ):
DownloadCoffeeScript()
commands = [ "java", "-jar", JCOFFEESCRIPT_PATH,
"--coffeescriptjs", COFFEESCRIPT_PATH ]
if closureMode:
# Add closure annotations
commands.extend( ["--bare", "--noutil", "--closure"] )
print "Compiling %s -> %s" % (source, destination)
output = open(destination, "wb")
process = \
subprocess.Popen(commands, stdout=output, stdin=subprocess.PIPE)
process.stdin.write( open( source, "rb" ).read() )
process.stdin.close()
process.wait()
def DownloadExterns():
"""Downloads Closure compiler externs files, if necessary."""
for (extern,url) in EXTERNS.iteritems():
path = os.path.join( GetStorageFolder(), extern )
if not os.path.exists( path ):
print "Fetching %s" % url
file(path,"wb").write(urllib2.urlopen(url).read())
def RunCompiler(type, files, output, compilerOptions, prepend, exports):
"""Downloads and runs the compiler of the given type.