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
|
#!/usr/bin/env python
import sys, string, re, os, random, cPickle, codecs
import config, tokenizer, treegenerator, filetool, stringoptimizer
internalModTime = 0
def validateFiles():
global internalModTime
base = os.path.dirname(os.path.abspath(sys.argv[0]))
if base.endswith("modules"):
path = base
else:
path = os.path.join(base, "modules")
maxFileModTime = os.stat(os.path.join(path, ".." + os.path.sep + "generator.py")).st_mtime
for root, dirs, files in os.walk(path):
# Filter ignored directories
for ignoredDir in config.DIRIGNORE:
if ignoredDir in dirs:
dirs.remove(ignoredDir)
# Searching for files
for fileName in files:
if os.path.splitext(fileName)[1] != config.PYEXT:
continue
filePath = os.path.join(root, fileName)
fileModTime = os.stat(filePath).st_mtime
if fileModTime > maxFileModTime:
maxFileModTime = fileModTime
internalModTime = maxFileModTime
def getInternalModTime(options):
global internalModTime
if internalModTime == 0 and not options.disableInternalCheck:
validateFiles()
return internalModTime
def extractFileContentId(data):
for item in config.QXHEAD["id"].findall(data):
return item
for item in config.QXHEAD["classDefine"].findall(data):
return item
# TODO: Obsolete with 0.7
for item in config.QXHEAD["defineClass"].findall(data):
return item[0]
return None
def extractSuperClass(data):
for item in config.QXHEAD["superClass"].findall(data):
return item
# TODO: Obsolete with 0.7
for item in config.QXHEAD["defineClass"].findall(data):
return item[2]
return None
def extractLoadtimeDeps(data, fileId=""):
deps = []
# qooxdoo specific:
# store inheritance deps
superClass = extractSuperClass(data)
if superClass != None and superClass != "" and not superClass in config.JSBUILTIN:
deps.append("qx.OO")
deps.append(superClass)
elif "qx.OO.defineClass(" in data:
deps.append("qx.OO")
# Adding explicit requirements
for item in config.QXHEAD["require"].findall(data):
if item == fileId:
print " - Self-referring load dependency: %s" % item
elif item in deps:
print " - Double definition of load dependency: %s" % item
else:
deps.append(item)
return deps
def extractAfterDeps(data, fileId=""):
deps = []
# Adding explicit after requirements
for item in config.QXHEAD["after"].findall(data):
if item == fileId:
print " - Self-referring load dependency: %s" % item
elif item in deps:
print " - Double definition of load dependency: %s" % item
else:
deps.append(item)
return deps
def extractRuntimeDeps(data, fileId=""):
deps = []
# Adding explicit runtime requirements
for item in config.QXHEAD["use"].findall(data):
if item == fileId:
print " - Self-referring runtime dependency: %s" % item
elif item in deps:
print " - Double definition of runtime dependency: %s" % item
else:
deps.append(item)
return deps
def extractLoadDeps(data, fileId=""):
deps = []
# Adding before requirements
for item in config.QXHEAD["load"].findall(data):
if item == fileId:
print " - Self-referring runtime dependency: %s" % item
elif item in deps:
print " - Double definition of runtime dependency: %s" % item
else:
deps.append(item)
return deps
def extractOptional(data):
deps = []
# Adding explicit requirements
for item in config.QXHEAD["optional"].findall(data):
if not item in deps:
deps.append(item)
return deps
def extractModules(data):
mods = []
for item in config.QXHEAD["module"].findall(data):
if not item in mods:
mods.append(item)
return mods
def extractResources(data):
res = []
for item in config.QXHEAD["resource"].findall(data):
res.append(item)
return res
def getTokens(fileDb, fileId, options):
if not fileDb[fileId].has_key("tokens"):
if options.verbose:
print " - Generating tokens for %s..." % fileId
useCache = False
loadCache = False
fileEntry = fileDb[fileId]
filePath = fileEntry["path"]
fileEncoding = fileEntry["encoding"]
if options.cacheDirectory != None:
cachePath = os.path.join(filetool.normalize(options.cacheDirectory), fileId + "-tokens.pcl")
useCache = True
if not filetool.checkCache(filePath, cachePath, getInternalModTime(options)):
loadCache = True
if loadCache:
tokens = filetool.readCache(cachePath)
else:
fileContent = filetool.read(filePath, fileEncoding)
tokens = tokenizer.parseStream(fileContent, fileId)
if useCache:
if options.verbose:
print " - Caching tokens for %s..." % fileId
filetool.storeCache(cachePath, tokens)
fileDb[fileId]["tokens"] = tokens
return fileDb[fileId]["tokens"]
def getTree(fileDb, fileId, options):
if not fileDb[fileId].has_key("tree"):
if options.verbose:
print " - Generating tree for %s..." % fileId
useCache = False
loadCache = False
fileEntry = fileDb[fileId]
filePath = fileEntry["path"]
if options.cacheDirectory != None:
cachePath = os.path.join(filetool.normalize(options.cacheDirectory), fileId + "-tree.pcl")
useCache = True
if not filetool.checkCache(filePath, cachePath, getInternalModTime(options)):
loadCache = True
if loadCache:
tree = filetool.readCache(cachePath)
else:
tree = treegenerator.createSyntaxTree(getTokens(fileDb, fileId, options))
if useCache:
if options.verbose:
print " - Caching tree for %s..." % fileId
filetool.storeCache(cachePath, tree)
fileDb[fileId]["tree"] = tree
return fileDb[fileId]["tree"]
def getStrings(fileDb, fileId, options):
if not fileDb[fileId].has_key("strings"):
if options.verbose:
print " - Searching for strings in %s..." % fileId
useCache = False
loadCache = False
fileEntry = fileDb[fileId]
filePath = fileEntry["path"]
if options.cacheDirectory != None:
cachePath = os.path.join(filetool.normalize(options.cacheDirectory), fileId + "-strings.pcl")
useCache = True
if not filetool.checkCache(filePath, cachePath, getInternalModTime(options)):
loadCache = True
if loadCache:
strings = filetool.readCache(cachePath)
else:
strings = stringoptimizer.search(getTree(fileDb, fileId, options), options.verbose)
if useCache:
if options.verbose:
print " - Caching strings for %s..." % fileId
filetool.storeCache(cachePath, strings)
fileDb[fileId]["strings"] = strings
return fileDb[fileId]["strings"]
def resolveAutoDeps(fileDb, options):
######################################################################
# DETECTION OF AUTO DEPENDENCIES
######################################################################
if options.verbose:
print " * Resolving dependencies..."
else:
print " * Resolving dependencies: ",
knownIds = []
depCounter = 0
hasMessage = False
for fileId in fileDb:
knownIds.append(fileId)
for fileId in fileDb:
fileEntry = fileDb[fileId]
if fileEntry["autoDeps"] == True:
continue
if not options.verbose:
sys.stdout.write(".")
sys.stdout.flush()
hasMessage = False
fileTokens = getTokens(fileDb, fileId, options)
fileDeps = []
assembledName = ""
for token in fileTokens:
if token["type"] == "name" or token["type"] == "builtin":
if assembledName == "":
assembledName = token["source"]
else:
assembledName += ".%s" % token["source"]
if assembledName in knownIds:
if assembledName != fileId and not assembledName in fileDeps:
fileDeps.append(assembledName)
assembledName = ""
elif not (token["type"] == "token" and token["source"] == "."):
if assembledName != "":
assembledName = ""
if token["type"] == "string" and token["source"] in knownIds and token["source"] != fileId and not token["source"] in fileDeps:
fileDeps.append(token["source"])
if options.verbose:
print " - Analysing %s..." % fileId
# Updating lists...
optionalDeps = fileEntry["optionalDeps"]
loadtimeDeps = fileEntry["loadtimeDeps"]
runtimeDeps = fileEntry["runtimeDeps"]
# Removing optional deps from list
for dep in optionalDeps:
if dep in fileDeps:
fileDeps.remove(dep)
if options.verbose:
# Checking loadtime dependencies
for dep in loadtimeDeps:
if not dep in fileDeps:
print " - Could not confirm #require(%s) in %s!" % (dep, fileId)
# Checking runtime dependencies
for dep in runtimeDeps:
if not dep in fileDeps:
print " - Could not confirm #use(%s) in %s!" % (dep, fileId)
# Adding new content to runtime dependencies
for dep in fileDeps:
if not dep in runtimeDeps and not dep in loadtimeDeps:
if options.verbose:
print " - Adding dependency: %s" % dep
runtimeDeps.append(dep)
depCounter += 1
# store flag to omit it the next run
fileEntry["autoDeps"] = True
if not hasMessage and not options.verbose:
print
print " * Added %s dependencies" % depCounter
def storeEntryCache(fileDb, options):
print " * Storing file entries..."
cacheCounter = 0
ignoreDbEntries = [ "tokens", "tree", "path", "pathId", "encoding", "resourceInput", "resourceOutput", "sourceScriptPath", "listIndex", "scriptInput" ]
for fileId in fileDb:
fileEntry = fileDb[fileId]
if fileEntry["cached"] == True:
continue
# Store flag
fileEntry["cached"] = True
# Copy entries
fileEntryCopy = {}
for key in fileEntry:
if not key in ignoreDbEntries:
fileEntryCopy[key] = fileEntry[key]
filetool.storeCache(fileEntry["cachePath"], fileEntryCopy)
cacheCounter += 1
print " * Updated %s files" % cacheCounter
def indexFile(filePath, filePathId, scriptInput, listIndex, scriptEncoding, sourceScriptPath, resourceInput, resourceOutput, options, fileDb={}, moduleDb={}):
########################################
# Checking cache
########################################
useCache = False
loadCache = False
cachePath = None
if options.cacheDirectory != None:
cachePath = os.path.join(filetool.normalize(options.cacheDirectory), filePathId + "-entry.pcl")
useCache = True
if not filetool.checkCache(filePath, cachePath, getInternalModTime(options)):
loadCache = True
########################################
# Loading file content / cache
########################################
if loadCache:
fileEntry = filetool.readCache(cachePath)
fileId = filePathId
else:
fileContent = filetool.read(filePath, scriptEncoding)
# Extract ID
fileContentId = extractFileContentId(fileContent)
# Search for valid ID
if fileContentId == None:
print " - Could not extract ID from file: %s. Using fileName!" % filePath
fileId = filePathId
else:
fileId = fileContentId
if fileId != filePathId:
print " - ID mismatch: CONTENT=%s != PATH=%s" % (fileContentId, filePathId)
sys.exit(1)
fileEntry = {
"autoDeps" : False,
"cached" : False,
"cachePath" : cachePath,
"optionalDeps" : extractOptional(fileContent),
"loadtimeDeps" : extractLoadtimeDeps(fileContent, fileId),
"runtimeDeps" : extractRuntimeDeps(fileContent, fileId),
"afterDeps" : extractAfterDeps(fileContent, fileId),
"loadDeps" : extractLoadDeps(fileContent, fileId),
"resources" : extractResources(fileContent),
"modules" : extractModules(fileContent)
}
########################################
# Additional data
########################################
# We don't want to cache these items
fileEntry["path"] = filePath
fileEntry["pathId"] = filePathId
fileEntry["encoding"] = scriptEncoding
fileEntry["resourceInput"] = resourceInput
fileEntry["resourceOutput"] = resourceOutput
fileEntry["sourceScriptPath"] = sourceScriptPath
fileEntry["listIndex"] = listIndex
fileEntry["scriptInput"] = scriptInput
########################################
# Registering file
########################################
# Register to file database
fileDb[fileId] = fileEntry
# Register to module database
for moduleId in fileEntry["modules"]:
if moduleDb.has_key(moduleId):
moduleDb[moduleId].append(fileId)
else:
moduleDb[moduleId] = [ fileId ]
def indexSingleScriptInput(scriptInput, listIndex, options, fileDb={}, moduleDb={}):
scriptInput = filetool.normalize(scriptInput)
# Search for other indexed lists
if len(options.scriptEncoding) > listIndex:
scriptEncoding = options.scriptEncoding[listIndex]
else:
scriptEncoding = "utf-8"
if len(options.sourceScriptPath) > listIndex:
sourceScriptPath = options.sourceScriptPath[listIndex]
else:
sourceScriptPath = None
if len(options.resourceInput) > listIndex:
resourceInput = options.resourceInput[listIndex]
else:
resourceInput = None
if len(options.resourceOutput) > listIndex:
resourceOutput = options.resourceOutput[listIndex]
else:
resourceOutput = None
for root, dirs, files in os.walk(scriptInput):
# Filter ignored directories
for ignoredDir in config.DIRIGNORE:
if ignoredDir in dirs:
dirs.remove(ignoredDir)
# Searching for files
for fileName in files:
if os.path.splitext(fileName)[1] == config.JSEXT:
filePath = os.path.join(root, fileName)
filePathId = filePath.replace(scriptInput + os.sep, "").replace(config.JSEXT, "").replace(os.sep, ".")
indexFile(filePath, filePathId, scriptInput, listIndex, scriptEncoding, sourceScriptPath, resourceInput, resourceOutput, options, fileDb, moduleDb)
def indexScriptInput(options):
if options.cacheDirectory != None:
filetool.directory(options.cacheDirectory)
print " * Indexing files... "
fileDb = {}
moduleDb = {}
listIndex = 0
for scriptInput in options.scriptInput:
indexSingleScriptInput(scriptInput, listIndex, options, fileDb, moduleDb)
listIndex += 1
print " * %s files were found" % len(fileDb)
if options.enableAutoDependencies:
resolveAutoDeps(fileDb, options)
if options.cacheDirectory != None:
storeEntryCache(fileDb, options)
return fileDb, moduleDb
"""
Simple resolver, just try to add items and put missing stuff around
the new one.
"""
def addIdWithDepsToSortedList(sortedList, fileDb, fileId):
if not fileDb.has_key(fileId):
print " * Error: Couldn't find required file: %s" % fileId
return False
# Test if already in
if not fileId in sortedList:
# Including loadtime dependencies
for loadtimeDepId in fileDb[fileId]["loadtimeDeps"]:
if loadtimeDepId == fileId: break;
addIdWithDepsToSortedList(sortedList, fileDb, loadtimeDepId)
# Including after dependencies
for afterDepId in fileDb[fileId]["afterDeps"]:
if afterDepId == fileId: break;
addIdWithDepsToSortedList(sortedList, fileDb, afterDepId)
# Add myself
if not fileId in sortedList:
sortedList.append(fileId)
# Include runtime dependencies
for runtimeDepId in fileDb[fileId]["runtimeDeps"]:
addIdWithDepsToSortedList(sortedList, fileDb, runtimeDepId)
# Include load dependencies
for loadDepId in fileDb[fileId]["loadDeps"]:
addIdWithDepsToSortedList(sortedList, fileDb, loadDepId)
"""
Search for dependencies, but don't add them. Just use them to put
the new class after the stuff which is required (if it's included, too)
"""
def addIdWithoutDepsToSortedList(sortedList, fileDb, fileId):
if not fileDb.has_key(fileId):
print " * Error: Couldn't find required file: %s" % fileId
return False
# Test if already in
if not fileId in sortedList:
# Search sortedList for files which needs this one and are already included
lowestIndex = None
currentIndex = 0
for lowId in sortedList:
for lowDepId in getResursiveLoadDeps([], fileDb, lowId, lowId):
if lowDepId == fileId and (lowestIndex == None or currentIndex < lowestIndex):
lowestIndex = currentIndex
currentIndex += 1
# Insert at defined index or just append new entry
if lowestIndex != None:
sortedList.insert(lowestIndex, fileId)
else:
sortedList.append(fileId)
def getResursiveLoadDeps(deps, fileDb, fileId, ignoreId=None):
if fileId in deps:
return
if fileId != ignoreId:
deps.append(fileId)
# Including loadtime dependencies
for loadtimeDepId in fileDb[fileId]["loadtimeDeps"]:
getResursiveLoadDeps(deps, fileDb, loadtimeDepId)
# Including after dependencies
for afterDepId in fileDb[fileId]["afterDeps"]:
getResursiveLoadDeps(deps, fileDb, afterDepId)
return deps
def getSortedList(options, fileDb, moduleDb):
includeWithDeps = []
excludeWithDeps = []
includeWithoutDeps = []
excludeWithoutDeps = []
sortedIncludeList = []
sortedExcludeList = []
# INCLUDE
# Add Modules and Files (with deps)
if options.includeWithDeps:
for include in options.includeWithDeps:
if include in moduleDb:
includeWithDeps.extend(moduleDb[include])
elif "*" in include or "?" in include:
regstr = "^(" + include.replace('.', '\\.').replace('*', '.*').replace('?', '.?') + ")$"
regexp = re.compile(regstr)
for fileId in fileDb:
if regexp.search(fileId):
if not fileId in includeWithDeps:
includeWithDeps.append(fileId)
else:
if not include in includeWithDeps:
includeWithDeps.append(include)
# Add Modules and Files (without deps)
if options.includeWithoutDeps:
for include in options.includeWithoutDeps:
if include in moduleDb:
includeWithoutDeps.extend(moduleDb[include])
elif "*" in include or "?" in include:
regstr = "^(" + include.replace('.', '\\.').replace('*', '.*').replace('?', '.?') + ")$"
regexp = re.compile(regstr)
for fileId in fileDb:
if regexp.search(fileId):
if not fileId in includeWithoutDeps:
includeWithoutDeps.append(fileId)
else:
if not include in includeWithoutDeps:
includeWithoutDeps.append(include)
# Add all if both lists are empty
if len(includeWithDeps) == 0 and len(includeWithoutDeps) == 0:
for fileId in fileDb:
includeWithDeps.append(fileId)
# Sorting include (with deps)
for fileId in includeWithDeps:
addIdWithDepsToSortedList(sortedIncludeList, fileDb, fileId)
# Sorting include (without deps)
for fileId in includeWithoutDeps:
addIdWithoutDepsToSortedList(sortedIncludeList, fileDb, fileId)
# EXCLUDE
# Add Modules and Files (with deps)
if options.excludeWithDeps:
for exclude in options.excludeWithDeps:
if exclude in moduleDb:
excludeWithDeps.extend(moduleDb[exclude])
elif "*" in exclude or "?" in exclude:
regstr = "^(" + exclude.replace('.', '\\.').replace('*', '.*').replace('?', '.?') + ")$"
regexp = re.compile(regstr)
for fileId in fileDb:
if regexp.search(fileId):
if not fileId in excludeWithDeps:
excludeWithDeps.append(fileId)
else:
if not exclude in excludeWithDeps:
excludeWithDeps.append(exclude)
# Add Modules and Files (without deps)
if options.excludeWithoutDeps:
for exclude in options.excludeWithoutDeps:
if exclude in moduleDb:
excludeWithoutDeps.extend(moduleDb[exclude])
elif "*" in exclude or "?" in exclude:
regstr = "^(" + exclude.replace('.', '\\.').replace('*', '.*').replace('?', '.?') + ")$"
regexp = re.compile(regstr)
for fileId in fileDb:
if regexp.search(fileId):
if not fileId in excludeWithDeps:
excludeWithoutDeps.append(fileId)
else:
if not exclude in excludeWithDeps:
excludeWithoutDeps.append(exclude)
# Sorting exclude (with deps)
for fileId in excludeWithDeps:
addIdWithDepsToSortedList(sortedExcludeList, fileDb, fileId)
# Sorting exclude (without deps)
for fileId in excludeWithoutDeps:
addIdWithoutDepsToSortedList(sortedExcludeList, fileDb, fileId)
# MERGE
# Remove excluded files from included files list
for fileId in sortedExcludeList:
if fileId in sortedIncludeList:
sortedIncludeList.remove(fileId)
# RETURN
return sortedIncludeList
|