forked from joa/haxe-sublime2-bundle
-
Notifications
You must be signed in to change notification settings - Fork 85
/
HaxeComplete.py
2419 lines (1867 loc) · 80.9 KB
/
HaxeComplete.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
# -*- coding: utf-8 -*-
import sys
#sys.path.append("/usr/lib/python2.6/")
#sys.path.append("/usr/lib/python2.6/lib-dynload")
import sublime, sublime_plugin
import subprocess, time
import tempfile
import os, signal
import stat
#import xml.parsers.expat
import re
import codecs
import glob
import hashlib
import shutil
import functools
# Information about where the plugin is running from
plugin_file = __file__
plugin_filepath = os.path.realpath(plugin_file)
plugin_path = os.path.dirname(plugin_filepath)
# Reload modules
reloader = 'features.haxe_reload_modules'
if sys.version_info >= (3,):
reloader = 'Haxe.' + reloader
if reloader in sys.modules:
sys.modules[reloader].reload_modules()
try: # Python 3
# Import the features module, including the haxelib and key commands etc
from .features import *
from .features.haxelib import *
# Import the helper functions and regex helpers
from .features.haxe_helper import runcmd, show_quick_panel, cache, parse_sig, get_env
from .features.haxe_helper import spaceChars, wordChars, importLine, packageLine
from .features.haxe_helper import compactFunc, compactProp, libLine, classpathLine, typeDecl
from .features.haxe_helper import libFlag, skippable, inAnonymous, extractTag
from .features.haxe_helper import variables, functions, functionParams, paramDefault
from .features.haxe_helper import isType, comments, haxeVersion, haxeFileRegex, controlStruct
from .features.haxe_errors import highlight_errors, extract_errors
except (ValueError): # Python 2
# Import the features module, including the haxelib and key commands etc
from features import *
from features.haxelib import *
# Import the helper functions and regex helpers
from features.haxe_helper import runcmd, show_quick_panel, cache, parse_sig, get_env
from features.haxe_helper import spaceChars, wordChars, importLine, packageLine
from features.haxe_helper import compactFunc, compactProp, libLine, classpathLine, typeDecl
from features.haxe_helper import libFlag, skippable, inAnonymous, extractTag
from features.haxe_helper import variables, functions, functionParams, paramDefault
from features.haxe_helper import isType, comments, haxeVersion, haxeFileRegex, controlStruct
from features.haxe_errors import highlight_errors, extract_errors
# For running background tasks
from subprocess import Popen, PIPE
try:
STARTUP_INFO = subprocess.STARTUPINFO()
STARTUP_INFO.dwFlags |= subprocess.STARTF_USESHOWWINDOW
STARTUP_INFO.wShowWindow = subprocess.SW_HIDE
except (AttributeError):
STARTUP_INFO = None
# For parsing xml
from xml.etree import ElementTree
from xml.etree.ElementTree import TreeBuilder as XMLTreeBuilder
try :
from elementtree import SimpleXMLTreeBuilder # part of your codebase
ElementTree.XMLTreeBuilder = SimpleXMLTreeBuilder.TreeBuilder
except ImportError as e:
pass # ST3
try :
stexec = __import__("exec")
ExecCommand = stexec.ExecCommand
AsyncProcess = stexec.AsyncProcess
except ImportError as e :
import Default
stexec = getattr( Default , "exec" )
ExecCommand = stexec.ExecCommand
AsyncProcess = stexec.AsyncProcess
unicode = str #dirty...
class HaxeLib :
available = {}
basePath = None
def __init__( self , name , dev , version ):
self.name = name
self.dev = dev
self.version = version
self.classes = None
self.packages = None
if self.dev :
self.path = self.version
self.version = "dev"
else :
self.path = os.path.join( HaxeLib.basePath , self.name , ",".join(self.version.split(".")) )
#print(self.name + " => " + self.path)
def extract_types( self ):
if self.dev is True or ( self.classes is None and self.packages is None ):
self.classes, self.packages = HaxeComplete.inst.extract_types(
self.path ,
cache_name = '%s_%s.cache' % (self.name, self.version) )
return self.classes, self.packages
@staticmethod
def get( name ) :
if( name in HaxeLib.available.keys()):
return HaxeLib.available[name]
else :
sublime.status_message( "Haxelib : "+ name +" project not installed" )
return None
@staticmethod
def get_completions() :
comps = []
for l in HaxeLib.available :
lib = HaxeLib.available[l]
comps.append( ( lib.name + " [" + lib.version + "]" , lib.name ) )
return comps
@staticmethod
def scan( view ) :
settings = view.settings()
haxelib_path = settings.get("haxelib_path" , "haxelib")
hlout, hlerr = runcmd( [haxelib_path , "config" ] )
HaxeLib.basePath = hlout.strip()
HaxeLib.available = {}
hlout, hlerr = runcmd( [haxelib_path , "list" ] )
for l in hlout.split("\n") :
found = libLine.match( l )
if found is not None :
name, dev, version = found.groups()
lib = HaxeLib( name , dev is not None , version )
HaxeLib.available[ name ] = lib
inst = None
documentationStore = {}
class BuildCache:
def __init__(self, path, raw, build, target):
self.path = path
self.raw = raw
self.build = build
self.target = target
class HaxeBuild :
#auto = None
targets = ["js","cpp","swf","neko","php","java","cs","x","python"]
nme_targets = [
("Flash - test","flash -debug","test"),
("Flash - build only","flash -debug","build"),
("Flash - release","flash","build"),
("HTML5 - test","html5 -debug","test"),
("HTML5 - build only","html5 -debug","build"),
("HTML5 - release","html5","build"),
("C++ - test","cpp -debug","test"),
("C++ - build only","cpp -debug","build"),
("C++ - release","cpp","build"),
("Linux - test","linux -debug","test"),
("Linux - build only","linux -debug","build"),
("Linux - release","linux","build"),
("Linux 64 - test","linux -64 -debug","test"),
("Linux 64 - build only","linux -64 -debug","build"),
("Linux 64 - release","linux -64","build"),
("iOS - test in iPhone simulator","ios -simulator -debug","test"),
("iOS - test in iPad simulator","ios -simulator -ipad -debug","test"),
("iOS - update XCode project","ios -debug","update"),
("iOS - release","ios","build"),
("Android - test","android -debug","test"),
("Android - build only","android -debug","build"),
("Android - release","android","build"),
("WebOS - test", "webos -debug","test"),
("WebOS - build only", "webos -debug","build"),
("WebOS - release", "webos","build"),
("Neko - test","neko -debug","test"),
("Neko - build only","neko -debug","build"),
("Neko - release","neko","build"),
("Neko 64 - test","neko -64 -debug","test"),
("Neko 64 - build only","neko -64 -debug","build"),
("Neko 64 - release","neko -64","build"),
("BlackBerry - test","blackberry -debug","test"),
("BlackBerry - build only","blackberry -debug","build"),
("BlackBerry - release","blackberry","build"),
("Emscripten - test", "emscripten -debug","test"),
("Emscripten - build only", "emscripten -debug","build"),
("Emscripten - release", "emscripten","build"),
]
nme_target = ("Flash - test","flash -debug","test")
flambe_targets = [
("Flash - test", "run flash --debug" ),
("Flash - build only", "build flash --debug" ),
("HTML5 - test", "run html --debug" ),
("HTML5 - build only" , "build html --debug"),
("Android - test" , "run android --debug"),
("Android - build only" , "build android --debug"),
("iOS - test" , "run ios --debug"),
("iOS - build only" , "build ios --debug"),
("Firefox App - test" , "run firefox --debug"),
("Firefox App - build only" , "build firefox --debug"),
]
flambe_target = ("Flash - run", "run flash --debug")
def __init__(self) :
self.args = []
self.main = None
self.target = None
self.output = None
self.hxml = None
self.nmml = None
self.yaml = None
self.classpaths = []
self.libs = []
self.classes = None
self.packages = None
self.libClasses = None
self.libPacks = None
self.openfl = False
self.lime = False
self.cwd = None
def __eq__(self,other) :
return self.__dict__ == other.__dict__
def __cmp__(self,other) :
return self.__dict__ == other.__dict__
def is_valid(self) :
if self.hxml is not None and self.target is None and self.yaml is None and self.nmml is None :
return False
if self.main is None and self.output is None :
return False;
return True;
def to_string(self) :
if not self.is_valid() :
return "Invalid Build"
out = self.main
if self.output is not None :
out = os.path.basename(self.output)
main = self.main
if main is None :
main = "[no main]"
if self.openfl :
return "{out} (openfl / {target})".format(self=self, out=out, target=HaxeBuild.nme_target[0]);
elif self.lime :
return "{out} (lime / {target})".format(self=self, out=out, target=HaxeBuild.nme_target[0]);
elif self.nmml is not None:
return "{out} (NME / {target})".format(self=self, out=out, target=HaxeBuild.nme_target[0]);
elif self.yaml is not None:
return "{out} (Flambe / {target})".format(self=self, out=out, target=HaxeBuild.flambe_target[0]);
else:
if self.target == "--interp" :
return "{main} (interp)".format(main=main);
if self.target == "--run" :
return "{main} (run)".format(main=main);
return "{main} ({target}:{out})".format(self=self, out=out, main=main, target=self.target);
#return "{self.main} {self.target}:{out}".format(self=self, out=out);
def make_hxml( self ) :
outp = "# Autogenerated "+self.hxml+"\n\n"
outp += "# "+self.to_string() + "\n"
outp += "-main "+ self.main + "\n"
for a in self.args :
outp += " ".join( list(a) ) + "\n"
d = os.path.dirname( self.hxml ) + "/"
# relative paths
outp = outp.replace( d , "")
outp = outp.replace( "-cp "+os.path.dirname( self.hxml )+"\n", "")
outp = outp.replace("--no-output" , "")
outp = outp.replace("-v" , "")
#outp = outp.replace("dummy" , self.main.lower() )
#print( outp )
return outp.strip()
def is_temp( self ) :
return not os.path.exists( self.hxml )
def get_types( self ) :
cwd = self.cwd
if cwd is None :
cwd = os.path.dirname( self.hxml )
if self.libClasses is None or self.libPacks is None :
classes = []
packs = []
cp = []
for lib in self.libs :
if lib is None :
continue
c, p = HaxeComplete.inst.extract_types(
os.path.join( cwd , lib.path ),
cache_name = '%s_%s.cache' % (lib.name, lib.version) )
classes.extend( c )
packs.extend( p )
self.libClasses = classes;
self.libPacks = packs;
classes = []
packs = []
cp = self.classpaths
for path in cp :
c, p = HaxeComplete.inst.extract_types( os.path.join( cwd , path ) )
classes.extend( c )
packs.extend( p )
classes.extend(self.libClasses)
packs.extend(self.libPacks)
classes.sort()
packs.sort()
self.classes = classes;
self.packs = packs;
return self.classes, self.packs
def get_classpath(self, view):
filepath = view.file_name()
buildpath = self.hxml
if buildpath is None:
buildpath = self.nmml
if buildpath is None:
buildpath = self.yaml
builddir = os.path.dirname(buildpath)
abscps = []
for cp in self.classpaths:
if os.path.isabs(cp):
abscps.append(cp)
else:
abscps.append(
os.path.normpath(os.path.join(builddir, cp)))
for cp in abscps:
if cp in filepath:
return cp
return None
class HaxeDisplayCompletion( sublime_plugin.TextCommand ):
def show_auto_complete(self):
view = self.view
HaxeComplete.inst.force_display_completion = True
HaxeComplete.inst.type_completion_only = self.type_completion
view.run_command('auto_complete', {
'api_completions_only': True,
'disable_auto_insert': True,
'next_completion_if_showing': False
})
HaxeComplete.inst.force_display_completion = False
HaxeComplete.inst.type_completion_only = False
def run(self, edit, type_completion=False, hide=False):
view = self.view
self.type_completion = type_completion
if hide:
view.run_command('hide_auto_complete')
sublime.set_timeout(self.show_auto_complete, 100)
else:
self.show_auto_complete()
class HaxeInsertCompletion( sublime_plugin.TextCommand ):
def run( self , edit ) :
#print("insert completion")
view = self.view
view.run_command( "insert_best_completion" , {
"default" : ".",
"exact" : True
} )
class HaxeSaveAllAndBuild( sublime_plugin.TextCommand ):
def run( self , edit ) :
complete = HaxeComplete.inst
view = self.view
view.window().run_command("save_all")
complete.run_build( view )
class HaxeRunBuild( sublime_plugin.TextCommand ):
def run( self , edit ) :
complete = HaxeComplete.inst
view = self.view
complete.run_build( view )
class HaxeSelectBuild( sublime_plugin.TextCommand ):
def run( self , edit , all_views = False ) :
complete = HaxeComplete.inst
view = self.view
complete.select_build( view , all_views )
class HaxeComplete( sublime_plugin.EventListener ):
#folder = ""
#buildArgs = []
currentBuild = None
selectingBuild = False
builds = []
haxe_settings_file = 'Preferences.sublime-settings'
currentCompletion = {
"inp" : None,
"outp" : None
}
classpathExclude = ['.git','_std']
classpathDepth = 2
stdPaths = []
stdPackages = []
#stdClasses = ["Void","Float","Int","UInt","Null","Bool","Dynamic","Iterator","Iterable","ArrayAccess"]
stdClasses = []
stdCompletes = []
visibleCompletionList = [] # This will contain the list of visible completions, if there is one.
panel = None
serverMode = False
serverProc = None
serverPort = 6000
compilerVersion = 2
inited = False
def __init__(self):
#print("init haxecomplete")
HaxeComplete.inst = self
self.build_cache = {}
self.force_display_completion = False
self.type_completion_only = False
self.selected_build_id_map = {}
def __del__(self) :
self.stop_server()
def extract_types( self , path , depth = 0 , cache_name = None ) :
classes = []
packs = []
hasClasses = False
if cache_name is not None:
view = sublime.active_window().active_view()
if view.settings().get('haxe_use_cache', True):
cache_str = cache(cache_name)
if cache_str is not None:
spl = cache_str.split(';')
classes = spl[0].split(',')
packs = spl[1].split(',')
return classes, packs
#print(path)
if not os.path.exists( path ) :
print('Warning: path %s doesn´t exists.'%path);
return classes, packs
for fullpath in glob.glob( os.path.join(path,"*.hx") ) :
f = os.path.basename(fullpath)
cl, ext = os.path.splitext( f )
if cl not in HaxeComplete.stdClasses:
s = codecs.open( os.path.join( path , f ) , "r" , "utf-8" , "ignore" )
src = comments.sub( "" , s.read() )
clPack = "";
for ps in packageLine.findall( src ) :
clPack = ps
if clPack == "" :
packDepth = 0
else:
packDepth = len(clPack.split("."))
for decl in typeDecl.findall( src ):
t = decl[1]
params = decl[2]
if( packDepth == depth ) : # and t == cl or cl == "StdTypes"
if t == cl or cl == "StdTypes":
classes.append( t + params )
else:
classes.append( cl + "." + t + params )
hasClasses = True
if hasClasses or depth <= self.classpathDepth :
for f in os.listdir( path ) :
cl, ext = os.path.splitext( f )
if os.path.isdir( os.path.join( path , f ) ) and f not in self.classpathExclude :
packs.append( f )
subclasses,subpacks = self.extract_types( os.path.join( path , f ) , depth + 1 )
for cl in subclasses :
classes.append( f + "." + cl )
classes.sort()
packs.sort()
if cache_name is not None:
view = sublime.active_window().active_view()
if view.settings().get('haxe_use_cache', True):
cache_str = ';'.join((','.join(classes), ','.join(packs)))
cache(cache_name, cache_str)
return classes, packs
def on_post_save( self , view ) :
if view.score_selector(0,'source.hxml') > 0:
self.clear_build(view)
def on_activated( self , view ) :
return self.on_open_file( view )
def on_load( self, view ) :
return self.on_open_file( view )
def on_open_file( self , view ) :
if view.is_loading() :
return;
if view.window() is None:
return
if view.score_selector(0,'source.haxe.2') > 0 :
HaxeCreateType.on_activated( view )
elif view.score_selector(0,'source.hxml,source.erazor,source.nmml') == 0:
return
self.init_plugin( view )
# HaxeProjects.determine_type()
self.extract_build_args( view )
self.get_build( view )
self.generate_build( view )
highlight_errors( view )
def on_pre_save( self , view ) :
if view.score_selector(0,'source.haxe.2') == 0 :
return []
fn = view.file_name()
if fn is not None :
path = os.path.dirname( fn )
if not os.path.isdir( path ) :
os.makedirs( path )
def __on_modified( self , view ):
win = sublime.active_window()
if win is None :
return None
isOk = ( win.active_view().buffer_id() == view.buffer_id() )
if not isOk :
return None
sel = view.sel()
caret = 0
for s in sel :
caret = s.a
if caret == 0 :
return None
if view.score_selector(caret,"source.haxe") == 0 or view.score_selector(caret,"string,comment,keyword.control.directive.conditional.haxe.2") > 0 :
return None
src = view.substr(sublime.Region(0, view.size()))
ch = src[caret-1]
#print(ch)
if ch not in ".(:, " :
view.run_command("haxe_display_completion")
#else :
# view.run_command("haxe_insert_completion")
def generate_build(self, view) :
fn = view.file_name()
if fn is not None and self.currentBuild is not None and fn == self.currentBuild.hxml and view.size() == 0 :
view.run_command("insert_snippet",{
"contents" : self.currentBuild.make_hxml()
})
def select_build( self , view , all_views = False ) :
scopes = view.scope_name(view.sel()[0].end()).split()
if 'source.hxml' in scopes:
view.run_command("save")
self.extract_build_args( view , True , all_views )
def find_nmml( self, folder ) :
nmmls = glob.glob( os.path.join( folder , "*.nmml" ) )
nmmls += glob.glob( os.path.join( folder , "*.xml" ) )
nmmls += glob.glob( os.path.join( folder , "*.hxp" ) )
nmmls += glob.glob( os.path.join( folder , "*.lime" ) )
for build in nmmls:
# yeah...
if not os.path.exists( build ) :
continue
f = codecs.open( build , "r+", "utf-8" , "ignore" )
raw = f.read()
if build in self.build_cache and \
self.build_cache[build].raw == raw:
currentBuild = self.build_cache[build].build
if currentBuild.main is not None :
self.add_build( currentBuild )
continue
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.nmml = build
currentBuild.openfl = build.endswith("xml")
currentBuild.lime = build.endswith("lime")
buildPath = os.path.dirname(build)
self.build_cache[build] = BuildCache(build, raw, currentBuild, None)
outp = "NME"
is_hxp = build.endswith("hxp")
if is_hxp:
currentBuild.main = 'hxp'
outp = 'Lime/OpenFl'
currentBuild.lime = True
lines = raw.splitlines()
for l in lines:
if len(l) > 200:
continue
if is_hxp:
continue
m = extractTag.search(l)
if not m is None:
#print(m.groups())
tag = m.group(1)
name = m.group(3)
if (tag == "app"):
currentBuild.main = name
currentBuild.args.append( ("-main" , name) )
mFile = re.search("\\b(file|title)=\"([a-z0-9_-]+)\"", l, re.I)
if not mFile is None:
outp = mFile.group(2)
elif (tag == "haxelib"):
currentBuild.libs.append( HaxeLib.get( name ) )
currentBuild.args.append( ("-lib" , name) )
elif (tag == "haxedef"):
currentBuild.args.append( ("-D", name) )
elif (tag == "classpath" or tag == "source"):
currentBuild.classpaths.append( os.path.join( buildPath , name ) )
currentBuild.args.append( ("-cp" , os.path.join( buildPath , name ) ) )
else: # NME 3.2
mPath = re.search("\\bpath=\"([a-z0-9_-]+)\"", l, re.I)
if not mPath is None:
#print(mPath.groups())
path = mPath.group(1)
currentBuild.classpaths.append( os.path.join( buildPath , path ) )
currentBuild.args.append( ("-cp" , os.path.join( buildPath , path ) ) )
outp = os.path.join( folder , outp )
if currentBuild.openfl or currentBuild.lime :
if self.compilerVersion >= 3 :
currentBuild.target = "swf"
else :
currentBuild.target = "swf9"
else :
currentBuild.target = "cpp"
currentBuild.args.append( ("--remap", "flash:nme") )
#currentBuild.args.append( ("-cpp", outp) )
currentBuild.output = outp
currentBuild.args.append( ("-"+currentBuild.target, outp) )
if currentBuild.main is not None :
self.add_build( currentBuild )
def find_yaml( self, folder ) :
yamls = glob.glob( os.path.join( folder , "flambe.yaml") )
for build in yamls :
# yeah...
if not os.path.exists( build ) :
continue
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.yaml = build
currentBuild.cwd = os.path.dirname( build )
currentBuild.output = "Flambe"
res, err = runcmd(
["flambe","--config" , build, "haxe-flags"] )
lines = res.split('\n')
i, n = 0, len(lines)
while i < n:
if lines[i] == '-lib':
i += 1
lib = HaxeLib.get(lines[i])
if lib is not None:
currentBuild.libs.append(lib)
i += 1
self.add_build( currentBuild )
def read_hxml( self, build ) :
#print("Reading build " + build );
def _read_hxml( build, builds ) :
buildPath = os.path.dirname(build);
spl = build.split("@")
if( len(spl) == 2 ) :
buildPath = spl[0]
build = os.path.join( spl[0] , spl[1] )
if not os.path.exists( build ) :
return builds
if builds:
currentBuild = builds[-1]
else:
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.cwd = buildPath
builds.append(currentBuild)
#print( currentBuild )
with codecs.open( build , "r+" , "utf-8" , "ignore" ) as f:
lines = f.readlines()
while lines:
l = lines.pop(0)
l = l.strip()
if l.startswith("#") : # a comment
pass
elif l.startswith("--next") :
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.cwd = buildPath
builds.append(currentBuild)
elif l.startswith("-main") :
spl = l.split(" ", 1)
if len( spl ) == 2 :
currentBuild.main = spl[1]
currentBuild.args.append( ( spl[0] , spl[1] ) )
else :
sublime.status_message( "Invalid build.hxml : no Main class" )
elif l.startswith("-lib") :
spl = l.split(" ", 1)
if len( spl ) == 2 :
lib = HaxeLib.get( spl[1] )
currentBuild.libs.append( lib )
currentBuild.args.append( spl )
else :
sublime.status_message( "Invalid build.hxml : lib not found" )
elif [l for flag in [ "cmd" , "-macro" ] if l.startswith( "-" + flag )] :
spl = l.split(" ", 1)
currentBuild.args.append( ( spl[0] , spl[1] ) )
#elif l.startswith("--connect") and HaxeComplete.inst.serverMode :
# currentBuild.args.append( ( "--connect" , str(self.serverPort) ))
elif [l for flag in [
"D" ,
"swf-version" ,
"swf-header",
"debug" ,
"-no-traces" ,
"-flash-use-stage" ,
"-gen-hx-classes" ,
"-remap" ,
"-no-inline" ,
"-no-opt" ,
"-php-prefix" ,
"-js-namespace" ,
"-dead-code-elimination" ,
"-remap" ,
"-php-front" ,
"-php-lib",
"dce" ,
"-js-modern" ,
"swf-lib"
] if l.startswith( "-"+flag )]:
currentBuild.args.append( l.split(" ", 1) )
elif [l for flag in [ "resource" , "xml" , "java-lib" , "net-lib" ] if l.startswith( "-"+flag )] :
spl = l.split(" ", 1)
outp = os.path.join( buildPath , spl[1] )
currentBuild.args.append( (spl[0] , outp) )
#print(HaxeBuild.targets)
elif [l for flag in HaxeBuild.targets if l.startswith( "-" + flag + " " )] :
spl = l.split(" ", 1)
#outp = os.path.join( folder , spl[1] )
outp = spl[1]
#currentBuild.args.append( ("-"+spl[0], outp) )
currentBuild.target = spl[0][1:]
currentBuild.output = outp
currentBuild.args.append( ( spl[0] , outp ) )
elif l.startswith( "--interp" ) :
currentBuild.target = "--interp"
currentBuild.output = ""
currentBuild.args.append( ( "--interp", ) )
elif l.startswith( "--run" ) :
spl = l.split(" ", 1)
#outp = os.path.join( folder , spl[1] )
outp = spl[1]
currentBuild.target = "--run"
currentBuild.output = outp
currentBuild.main = outp
currentBuild.args.append( ( "--run" , outp ) )
while lines:
l = lines.pop(0).strip()
if (not l) or l.startswith("#") : # an empty line or a comment
continue
currentBuild.args.append( (l,) )
elif l.startswith("-cp "):
cp = l.split(" ", 1)
#view.set_status( "haxe-status" , "Building..." )
classpath = cp[1]
absClasspath = classpath#os.path.join( buildPath , classpath )
currentBuild.classpaths.append( absClasspath )
currentBuild.args.append( ("-cp" , absClasspath ) )
elif l.endswith(".hxml"):
_read_hxml(os.path.join(currentBuild.cwd, l), builds)
elif re.match(r'[A-Za-z0-9_\.]+', l): # a haxe class
currentBuild.args.append( (l,) )
elif l:
sublime.status_message("unknown compiler argument: " + l)
# maybe there is a new compiler argument that we don't know,
# so let's add the argument anyway
currentBuild.args.append( (l,) )
return builds
builds = _read_hxml(build, [])
for build in builds:
if len(build.classpaths) == 0:
build.classpaths.append( build.cwd )
build.args.append( ("-cp" , build.cwd ) )
return [build for build in builds if build.is_valid()]
def add_build( self , build ) :
if build in self.builds :
self.builds.remove( build )
self.builds.insert( 0, build )
def find_hxml( self, folder ) :
hxmls = glob.glob( os.path.join( folder , "*.hxml" ) )
for build in hxmls:
for b in self.read_hxml( build ):
self.add_build( b )
def find_build_file( self , folder ) :
self.find_hxml(folder)
self.find_nmml(folder)
self.find_yaml(folder)
def extract_build_args( self , view ,
forcePanel = False , all_views = False ) :
#print("extract build args")
self.builds = []
fn = view.file_name()
settings = view.settings()
win = view.window()
folder = None
file_folder = None
# folder containing the file, opened in window
project_folder = None
win_folders = []
folders = []
if fn is not None :
file_folder = folder = os.path.dirname(fn)
# find window folder containing the file
if win is not None :
win_folders = win.folders()
for f in win_folders:
if f + os.sep in fn :
project_folder = folder = f
# extract build files from project
build_files = view.settings().get('haxe_builds')
if build_files is not None :
for build in build_files :
if( int(sublime.version()) > 3000 ) and win is not None :
# files are relative to project file name
proj = win.project_file_name()
if( proj is not None ) :
proj_path = os.path.dirname( proj )
build = os.path.join( proj_path , build )
for b in self.read_hxml( build ) :
self.add_build( b )
else :
crawl_folders = []
# go up all folders from file to project or root
if file_folder is not None :
f = os.path.normpath(file_folder)
prev = None
while prev != f and ( project_folder is None or project_folder in f ):
crawl_folders.append( f )
prev = f
f = os.path.abspath(os.path.join(f, os.pardir))