-
Notifications
You must be signed in to change notification settings - Fork 89
/
HaxeComplete.py
2160 lines (1631 loc) · 70.6 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 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)
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 .HaxeHelper import runcmd, show_quick_panel
from .HaxeHelper import spaceChars, wordChars, importLine, packageLine, compilerOutput
from .HaxeHelper import compactFunc, compactProp, libLine, classpathLine, typeDecl
from .HaxeHelper import libFlag, skippable, inAnonymous, extractTag
from .HaxeHelper import variables, functions, functionParams, paramDefault
from .HaxeHelper import isType, comments, haxeVersion, haxeFileRegex, controlStruct
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 HaxeHelper import runcmd, show_quick_panel
from HaxeHelper import spaceChars, wordChars, importLine, packageLine, compilerOutput
from HaxeHelper import compactFunc, compactProp, libLine, classpathLine, typeDecl
from HaxeHelper import libFlag, skippable, inAnonymous, extractTag
from HaxeHelper import variables, functions, functionParams, paramDefault
from HaxeHelper import isType, comments, haxeVersion, haxeFileRegex, controlStruct
# 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 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 )
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 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"),
("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 64 - test","neko -64 -debug","test"),
("Neko 64 - build only","neko -64 -debug","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 = "js"
self.output = None
self.hxml = None
self.nmml = None
self.yaml = None
self.classpaths = []
self.libs = []
self.classes = None
self.packages = 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"
outp += "-" + self.target + " " + self.output + "\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 ) :
if self.classes is None or self.packs is None :
classes = []
packs = []
cp = []
cp.extend( self.classpaths )
for lib in self.libs :
if lib is not None :
cp.append( lib.path )
#print("extract types :")
#print(cp)
cwd = self.cwd
if cwd is None :
cwd = os.path.dirname( self.hxml )
for path in cp :
c, p = HaxeComplete.inst.extract_types( os.path.join( cwd , path ) )
classes.extend( c )
packs.extend( p )
classes.sort()
packs.sort()
self.classes = classes;
self.packs = packs;
return self.classes, self.packs
class HaxeDisplayCompletion( sublime_plugin.TextCommand ):
def run( self , edit ) :
#print("completing")
view = self.view
view.run_command( "auto_complete" , {
"api_completions_only" : True,
"disable_auto_insert" : True,
"next_completion_if_showing" : False
} )
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 ) :
complete = HaxeComplete.inst
view = self.view
complete.select_build( view )
class HaxeHint( sublime_plugin.TextCommand ):
def run( self , edit , input = "" ) :
complete = HaxeComplete.inst
view = self.view
if input == "(":
sel = view.sel()
emptySel = True
for r in sel :
if not r.empty() :
emptySel = False
break
autoMatch = view.settings().get("auto_match_enabled",False)
if autoMatch :
if emptySel :
view.run_command( "insert_snippet" , {
"contents" : "($0)"
})
else :
view.run_command( "insert_snippet" , {
"contents" : "(${0:$SELECTION})"
})
else :
view.run_command("insert" , {
"characters" : "("
})
else :
view.run_command("insert" , {
"characters" : input
})
autocomplete = view.settings().get("auto_complete",True)
if not autocomplete :
return
for r in view.sel() :
comps, hints = complete.get_haxe_completions( self.view , r.end() )
fn_name = complete.get_current_fn_name(self.view, r.end())
if view.settings().get("haxe_smart_snippets",False) :
snippet = ""
i = 1
for h in hints :
var = str(i)+": " + h + " ";
var = var.replace("{","\{")
var = var.replace("}","\}")
if snippet == "":
snippet = var
else:
snippet = snippet + ",${" + var + "}"
i = i+1
#print( hints )
view.run_command( "insert_snippet" , {
"contents" : "${"+snippet+"}"
})
#view.set_status("haxe-status", status)
#sublime.status_message(status)
#if( len(comps) > 0 ) :
# view.run_command('auto_complete', {'disable_auto_insert': True})
class HaxeComplete( sublime_plugin.EventListener ):
#folder = ""
#buildArgs = []
currentBuild = None
selectingBuild = False
builds = []
errors = []
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
def __del__(self) :
self.stop_server()
def extract_types( self , path , depth = 0 ) :
classes = []
packs = []
hasClasses = False
#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()
return classes, packs
def highlight_errors( self , view ) :
fn = view.file_name()
line_regions = []
char_regions = []
if fn is None :
return
for e in self.errors :
if os.path.samefile(e["file"], fn) :
metric = e["metric"]
l = e["line"]
left = e["from"]
right = e["to"]
if metric.startswith("character") :
# retrieve character positions from utf-8 bytes offset reported by compiler
line = view.substr(view.line(view.text_point(l, 0))).encode("utf-8")
left = len(line[:left].decode("utf-8"))
right = len(line[:right].decode("utf-8"))
a = view.text_point(l,left)
b = view.text_point(l,right)
char_regions.append( sublime.Region(a,b))
else :
a = view.text_point(left,0)
b = view.text_point(right,0)
line_regions.append( sublime.Region(a,b))
view.set_status("haxe-status" , "Error: " + e["message"] )
view.add_regions("haxe-error-lines" , line_regions , "invalid" , "light_x_bright" , sublime.DRAW_OUTLINED )
view.add_regions("haxe-error" , char_regions , "invalid" , "light_x_bright" , sublime.DRAW_OUTLINED )
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.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 )
self.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 ) :
scopes = view.scope_name(view.sel()[0].end()).split()
if 'source.hxml' in scopes:
view.run_command("save")
self.extract_build_args( view , True )
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 , "*.lime" ) )
for build in nmmls:
# yeah...
if not os.path.exists( build ) :
continue
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.nmml = build
currentBuild.openfl = build.endswith("xml")
currentBuild.lime = build.endswith("lime")
buildPath = os.path.dirname(build)
# TODO delegate compiler options extractions to NME 3.2:
# runcmd("nme diplay project.nmml nme_target")
outp = "NME"
f = codecs.open( build , "r+", "utf-8" , "ignore" )
while 1:
l = f.readline()
if not l :
break;
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
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
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 )
self.add_build( currentBuild )
def read_hxml( self, build ) :
#print("Reading build " + 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
#print( buildPath, build )
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.cwd = buildPath
#print( currentBuild )
f = codecs.open( build , "r+" , "utf-8" , "ignore" )
while 1:
l = f.readline()
if not l :
break;
if l.startswith("--next") :
if len(currentBuild.classpaths) == 0:
currentBuild.classpaths.append( buildPath )
currentBuild.args.append( ("-cp" , buildPath ) )
if currentBuild.is_valid() :
builds.append( currentBuild )
currentBuild = HaxeBuild()
currentBuild.hxml = build
currentBuild.cwd = buildPath
l = l.strip()
if l.startswith("-main") :
spl = l.split(" ")
if len( spl ) == 2 :
currentBuild.main = spl[1]
else :
sublime.status_message( "Invalid build.hxml : no Main class" )
if l.startswith("-lib") :
spl = l.split(" ")
if len( spl ) == 2 :
lib = HaxeLib.get( spl[1] )
currentBuild.libs.append( lib )
else :
sublime.status_message( "Invalid build.hxml : lib not found" )
for flag in [ "cmd" , "-macro" ] :
spl = l.split(" ")
if l.startswith( "-" + flag ) :
currentBuild.args.append( ( spl[0] , " ".join(spl[1:]) ) )
#if l.startswith("--connect") and HaxeComplete.inst.serverMode :
# currentBuild.args.append( ( "--connect" , str(self.serverPort) ))
for flag in [ "lib" , "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( tuple(l.split(" ") ) )
break
for flag in [ "resource" , "xml" , "java-lib" , "net-lib" ] :
if l.startswith( "-"+flag ) :
spl = l.split(" ")
outp = os.path.join( buildPath , " ".join(spl[1:]) )
currentBuild.args.append( ("-"+flag, outp) )
break
#print(HaxeBuild.targets)
for flag in HaxeBuild.targets :
if l.startswith( "-" + flag + " " ) :
spl = l.split(" ")
#outp = os.path.join( folder , " ".join(spl[1:]) )
outp = " ".join(spl[1:])
#currentBuild.args.append( ("-"+flag, outp) )
currentBuild.target = flag
currentBuild.output = outp
break
if l.startswith( "--interp" ) :
currentBuild.target = "-interp" # we add '-' to the target later on
currentBuild.output = ""
if l.startswith( "--run" ) :
spl = l.split(" ")
#outp = os.path.join( folder , " ".join(spl[1:]) )
outp = " ".join(spl[1:])
currentBuild.target = "-run" # we add '-' to the target later on
currentBuild.output = outp
currentBuild.main = outp
if l.startswith("-cp "):
cp = l.split(" ")
#view.set_status( "haxe-status" , "Building..." )
cp.pop(0)
classpath = " ".join( cp )
absClasspath = classpath#os.path.join( buildPath , classpath )
currentBuild.classpaths.append( absClasspath )
currentBuild.args.append( ("-cp" , absClasspath ) )
if len(currentBuild.classpaths) == 0:
currentBuild.classpaths.append( buildPath )
currentBuild.args.append( ("-cp" , buildPath ) )
if currentBuild.is_valid() :
builds.append( currentBuild )
return builds
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 ) :
#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 = 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.split( f )[0]
# crawl other window folders
for f in win_folders :
if f not in crawl_folders :
crawl_folders.append( f )
for f in crawl_folders :
self.find_build_file( f )
if len(self.builds) == 1:
if forcePanel :
sublime.status_message("There is only one build")
# will open the build file
#if forcePanel :
# b = self.builds[0]
# f = b.hxml
# v = view.window().open_file(f,sublime.TRANSIENT)
self.set_current_build( view , int(0), forcePanel )
elif len(self.builds) == 0 and forcePanel :
sublime.status_message("No hxml or nmml file found")
f = os.path.join(folder,"build.hxml")
self.currentBuild = None
self.get_build(view)
self.currentBuild.hxml = f
#for whatever reason generate_build doesn't work without transient
v = view.window().open_file(f,sublime.TRANSIENT)
self.set_current_build( view , int(0), forcePanel )
elif len(self.builds) > 1 and forcePanel :
buildsView = []
for b in self.builds :
#for a in b.args :
# v.append( " ".join(a) )
buildsView.append( [b.to_string(), os.path.basename( b.hxml ) ] )
self.selectingBuild = True
sublime.status_message("Please select your build")
show_quick_panel( view.window() , buildsView , lambda i : self.set_current_build(view, int(i), forcePanel) , sublime.MONOSPACE_FONT )
elif settings.has("haxe-build-id"):
self.set_current_build( view , int(settings.get("haxe-build-id")), forcePanel )
else:
self.set_current_build( view , int(0), forcePanel )
def set_current_build( self , view , id , forcePanel ) :
if id < 0 or id >= len(self.builds) :
id = 0
view.settings().set( "haxe-build-id" , id )