-
Notifications
You must be signed in to change notification settings - Fork 46
/
util.py
3898 lines (3068 loc) · 129 KB
/
util.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
import sublime
import os
import sys
import json
import csv
import urllib
import pprint
import sys
import re
import time
import datetime
import base64
import zipfile
import shutil
import subprocess
import webbrowser
import xml.dom.minidom
from .salesforce.lib import xmlformatter
from .salesforce import message
from .salesforce import xmltodict
from .salesforce.lib import dateutil
from .salesforce.lib.dateutil import tz
from .salesforce.lib.panel import Printer
from . import context
from xml.sax.saxutils import unescape
def load_templates():
"""
Load code template files from haoide package to working project .templates folder
"""
settings = context.get_settings()
target_dir = os.path.join(settings["workspace"], ".templates")
if not os.path.exists(target_dir):
os.makedirs(target_dir)
templates_dir = os.path.join(target_dir, "templates.json")
lwc_dir = os.path.join(target_dir, "Lwc") # Check exist lwc logic
lwc_ele_dir = os.path.join(target_dir, "LwcElement") # Check exist lwc element logic
# for the updating of Lwc, old project should update the template files
if not os.path.isfile(templates_dir) or not os.path.exists(lwc_dir) or not os.path.exists(lwc_ele_dir):
# get the installed haoide package directory
source_dir = os.path.join(
sublime.installed_packages_path(),
"haoide.sublime-package"
)
if os.path.isfile(source_dir):
# default situation, installed haoide package, copy files from zip file sub folders
zfile = zipfile.ZipFile(source_dir, 'r')
for filename in zfile.namelist():
if filename.endswith('/'):
continue
if filename.startswith("config/templates/"):
f = os.path.join(
target_dir,
filename.replace("config/templates/", "")
)
if not os.path.exists(os.path.dirname(f)):
os.makedirs(os.path.dirname(f))
with open(f, "wb") as fp:
fp.write(zfile.read(filename))
zfile.close()
else:
# when develop haoide, use local package templates files
source_dir = os.path.join(
sublime.packages_path(), "haoide2/config/templates"
)
copy_files_in_folder(source_dir, target_dir)
with open(templates_dir) as fp:
templates = json.loads(fp.read())
return templates
def copy_files_in_folder(source_dir, target_dir):
""" Copy folders and files in source dir to target dir
Paramter:
@source_dir -- Source Directory
@target_dir -- Target Directory
"""
for _file in os.listdir(source_dir):
sourceFile = os.path.join(source_dir, _file)
targetFile = os.path.join(target_dir, _file)
if os.path.isfile(sourceFile):
if not os.path.exists(target_dir):
os.makedirs(target_dir)
if not os.path.exists(targetFile) or (
os.path.exists(targetFile) and (
os.path.getsize(targetFile) != os.path.getsize(sourceFile)
)):
open(targetFile, "wb").write(open(sourceFile, "rb").read())
if os.path.isdir(sourceFile):
copy_files_in_folder(sourceFile, targetFile)
def copy_files(attributes, target_dir):
""" Copy files and its related meta file to target dir
Paramter:
@files -- file attributes, example: {
"fileDir": ".../classes/ABC.cls",
"fullName": "ABC"
}
@target_dir -- Target Directory
"""
try:
for attribute in attributes:
# Copy file to target dir
#
# Build target metdata folder, make it if not exist
target_meta_folder = os.path.join(
target_dir, "src",
attribute["metadata_folder"],
attribute.get("folder", "")
)
if not os.path.exists(target_meta_folder):
os.makedirs(target_meta_folder)
# Build target file
target_file = os.path.join(
target_meta_folder,
attribute["fullName"]
)
# Copy file to target file
fileDir = attribute["fileDir"]
with open(fileDir, "rb") as fread:
content = fread.read()
with open(target_file, "wb") as fwrite:
fwrite.write(content)
# Write meta file to target dir if exist
metaFileDir = fileDir + "-meta.xml"
if os.path.isfile(metaFileDir):
target_meta_file = target_file + "-meta.xml"
with open(metaFileDir, "rb") as fread:
content = fread.read()
with open(target_meta_file, "wb") as fwrite:
fwrite.write(content)
except Exception as ex:
Printer.get("error").write(str(ex))
return False
return True
def get_described_metadata(settings):
cache_file = os.path.join(
settings["workspace"],
".config",
"metadata.json"
)
described_metadata = None
if os.path.isfile(cache_file):
with open(cache_file) as fp:
described_metadata = json.loads(fp.read())
return described_metadata
def get_instance(settings):
""" Get instance by instance_url
Return:
* instance -- instance of active project, for example,
if instance_url is https://ap1.salesforce.com,
instance will be `ap1`,
if instance_url is https://company-name.cs18.my.salesforce.com
instance will be `company-name.cs18.my`
"""
session = get_session_info(settings)
instance_url = session["instance_url"]
base_url = re.compile("//[\s\S]+?\.").search(instance_url).group()
instance = base_url[2:-1]
return instance
def get_session_info(settings):
""" Get Session Info
Arguments:
* settings -- plugin settings
Return:
* session -- Session Info
"""
session = None
session_directory = os.path.join(settings["workspace"], ".config", "session.json")
if os.path.isfile(session_directory):
with open(session_directory) as fp:
session = json.loads(fp.read())
return session
def get_package_info(settings):
package = None
package_directory = os.path.join(settings["workspace"], ".config", "package.json")
if os.path.isfile(package_directory):
with open(package_directory) as fp:
package = json.loads(fp.read())
return package
def get_completion_from_cache(settings, component_type, is_lightning=False):
""" Get component completion list from .config/package.json
* settings -- plugin settings
* component_type -- metadata objec type, StaticResource, CustomLabel, etc.
"""
package_cache = get_package_info(settings)
completion_list = []
if package_cache:
namespace = "c." if is_lightning else ""
members = package_cache.get(component_type, [])
for member in members:
completion_list.append((
"%s%s\t%s" % (namespace, member.get("fullName"), component_type),
"%s%s" % (namespace, member.get("fullName"))
))
else:
sublime.status_message("Info: Not found " + component_type)
return completion_list
def view_coverage(file_name, record, body):
"""
View Apex Class/Trigger code coverage like developer console UI
@param file_name: name of the apex class/trigger file
@param record: dict of {Coverage:{coveredLines:[], uncoveredLines:[]}, NumLinesUncovered:0, NumLinesCovered:0}
@param body: the apex class/trigger file body
@return: a new view with code coverage information
"""
coverage = record.get("Coverage")
num_lines_uncovered = record.get("NumLinesUncovered", 0)
num_lines_cover = record.get("NumLinesCovered", 0)
num_lines = num_lines_uncovered + num_lines_cover
if num_lines == 0:
return Printer.get("error").write("There is no code coverage (0% coverage)")
# Append coverage statistic info
coverage_statistic = "%s Coverage: %.2f%%(%s/%s)" % (
file_name, num_lines_cover / num_lines * 100,
num_lines_cover, num_lines
)
# If has coverage, just add coverage info to new view
view = sublime.active_window().new_file()
view.run_command("new_view", {
"name": coverage_statistic,
"input": body
})
# Calculate line coverage
lines_uncovered = coverage.get("uncoveredLines")
lines_covered = coverage.get("coveredLines")
split_lines = view.lines(sublime.Region(0, view.size()))
uncovered_region = []
covered_region = []
for region in split_lines:
# The first four Lines are the coverage info
line = view.rowcol(region.begin() + 1)[0] + 1
if line in lines_uncovered:
uncovered_region.append(region)
elif line in lines_covered:
covered_region.append(region)
# Append body with uncovered line
view.add_regions("numLocationsNotCovered", uncovered_region, "invalid", "dot",
sublime.DRAW_SOLID_UNDERLINE | sublime.DRAW_EMPTY_AS_OVERWRITE)
view.add_regions("numLocationsCovered", covered_region, "comment", "cross",
sublime.DRAW_SOLID_UNDERLINE | sublime.DRAW_EMPTY_AS_OVERWRITE)
def get_local_timezone_offset():
""" Return the timezone offset of local time with GMT standard
Return:
* offset_hours -- date time offset hours with GMT
"""
localtz = dateutil.tz.tzlocal()
localoffset = localtz.utcoffset(datetime.datetime.now(localtz))
offset_hours = localoffset.total_seconds() / 3600
return offset_hours
# https://docs.python.org/3.2/library/datetime.html#strftime-and-strptime-behavior
# http://stackoverflow.com/questions/12015170/how-do-i-automatically-get-the-timezone-offset-for-my-local-time-zone
def local_datetime(server_datetime_str):
""" Convert the Datetime got from server to local GMT Datetime
Return:
* local_datetime -- local datetime with GMT offset
"""
offset = get_local_timezone_offset()
local_datetime = datetime.datetime.strptime(server_datetime_str[:19], '%Y-%m-%dT%H:%M:%S')
local_datetime += datetime.timedelta(hours=offset)
return local_datetime
def server_datetime(local_datetime):
""" Convert the Datetime got from local to GMT Standard
Return:
* server_datetime -- standard GMT server datetime
"""
offset = get_local_timezone_offset()
server_datetime = local_datetime + datetime.timedelta(hours=-offset)
return server_datetime
def populate_all_components():
""" Get all components from local cache
"""
# Get username
settings = context.get_settings()
username = settings["username"]
# If sobjects is exist in local cache, just return it
component_metadata = sublime.load_settings(context.COMPONENT_METADATA_SETTINGS)
if not component_metadata.has(username):
Printer.get('error').write("No Cache, Please New Project Firstly.")
return {}
return_component_attributes = {}
for component_type in component_metadata.get(username).keys():
component_attributes = component_metadata.get(username)[component_type]
for key in component_attributes.keys():
component_id = component_attributes[key]["id"]
component_type = component_attributes[key]["type"]
component_name = component_attributes[key]["name"]
return_component_attributes[component_type + "." + component_name] = component_id
return return_component_attributes
def populate_components(_type):
"""
Get dict (Class Name => Class Id) which NamespacePrefix is null in whole org
@return: {
classname: classid
...
}
"""
# Get username
settings = context.get_settings()
username = settings["username"]
# If sobjects is exist in local cache, just return it
component_settings = sublime.load_settings(context.COMPONENT_METADATA_SETTINGS)
if not component_settings.has(username):
message = "Please execute `Cache > Reload Sobject Cache` command before execute this command"
Printer.get("error").write(message)
return {}
return component_settings.get(username).get(_type)
def populate_lighting_applications():
settings = context.get_settings()
workspace = settings["workspace"]
username = settings["username"]
aura_path = os.path.join(workspace, "src", "aura")
component_settings = sublime.load_settings(context.COMPONENT_METADATA_SETTINGS)
if not component_settings.has(username):
return {}
aura_attributes = {}
aura_cache = component_settings.get(username).get("AuraDefinitionBundle")
for name in aura_cache:
aura_name, element_name = aura_cache[name]["fullName"].split("/")
if element_name.endswith(".app"):
aura_attributes[aura_name] = aura_cache[name]
return aura_attributes
def populate_sobjects_describe():
"""
Get the sobjects list in org.
"""
# Get username
settings = context.get_settings()
username = settings["username"]
# If sobjects is exist in sobjects_completion.sublime-settings, just return it
sobjects_completions = sublime.load_settings("sobjects_completion.sublime-settings")
if not sobjects_completions.has(username):
message = "Please execute `Cache > Reload Sobject Cache` command before execute this command"
Printer.get('error').write(message)
return
sobjects_describe = {}
sd = sobjects_completions.get(username)["sobjects"]
for key in sd:
sobject_describe = sd[key]
sobjects_describe[sobject_describe["name"]] = sobject_describe
return sobjects_describe
def populate_all_test_classes():
# Get username
settings = context.get_settings()
username = settings["username"]
component_metadata = sublime.load_settings(context.COMPONENT_METADATA_SETTINGS)
if not component_metadata.has(username):
Printer.get('error').write("No cache, please create new project firstly.")
return
classes = component_metadata.get(username)["ApexClass"]
test_class_ids = []
for class_name, class_attr in classes.items():
if not class_attr["is_test"]: continue
test_class_ids.append(class_attr["id"])
return test_class_ids
def set_component_attribute(attributes, lastModifiedDate):
""" Set the LastModifiedDate for specified component
Params:
* attributes -- component attributes
* lastModifiedDate -- LastModifiedDate of component
"""
# If sobjects is exist in local cache, just return it
settings = context.get_settings()
username = settings["username"]
s = sublime.load_settings(context.COMPONENT_METADATA_SETTINGS)
if not s.has(username):
return
_type = attributes["type"]
fullName = attributes["name"] + attributes["extension"]
components_dict = s.get(username, {})
# Prevent exception if no component in org
if _type not in components_dict:
components_dict = {_type: {}}
# update components dict lastModifiedDate atrribute
attr = components_dict[_type][fullName.lower()]
attr["lastModifiedDate"] = lastModifiedDate
# Comment out unnecessary assignment
# components_dict[_type][fullName.lower()] = attr
# Save settings and show success message
s.set(username, components_dict)
sublime.save_settings(context.COMPONENT_METADATA_SETTINGS)
def get_sobject_caches(setting_name):
""" Return the specified local cache of default project
Return:
* caches -- sobject local cache in default project
"""
config_settings = context.get_settings()
projects = config_settings["projects"]
settings = sublime.load_settings(setting_name)
caches = []
for p in projects:
if settings.has(projects[p]["username"]):
caches.append([p, projects[p]["username"]])
return caches
def clear_cache(username, setting_name):
""" Clear the specified local cache of default project
Arguments:
* username -- the login username of default project
"""
settings = sublime.load_settings(setting_name)
settings = settings.erase(username)
sublime.save_settings(setting_name)
sublime.status_message(username + " cache is cleared")
def get_sobject_metadata(username):
""" Return the sobject cache of default project
Arguments:
* username -- username of current default project
Returns:
* sobject metadata -- the sobject metadata of default project
"""
sobjects_settings = sublime.load_settings("sobjects_completion.sublime-settings")
sobjects_metadata = {}
if sobjects_settings.has(username):
sobjects_metadata = sobjects_settings.get(username, {})
return sobjects_metadata
def get_symbol_tables(username):
""" Return the sobject cache of default project
Arguments:
* username -- username of current default project
Returns:
* sobject metadata -- the sobject metadata of default project
"""
symbol_tables = {}
symbol_tables_settings = sublime.load_settings("symbol_table.sublime-settings")
if symbol_tables_settings.has(username):
symbol_tables = symbol_tables_settings.get(username, {})
return symbol_tables
def get_sobject_completion_list(
sobject_describe,
prefix="",
display_fields=True,
display_parent_relationships=True,
display_child_relationships=True):
""" Return the formatted completion list of sobject
Arguments:
* sobject_describe -- describe result of sobject
* prefix -- optional; sometimes, parent relationshipName may refer to multiple sobject,
so we need to add the prefix to distinct different completions
* display_child_relationships -- optional; indicate whether display sobject child relationship names
"""
# Fields Describe
completion_list = []
if display_fields:
fields = sobject_describe["fields"]
for field_name_desc in sorted(fields):
field_name = fields[field_name_desc]
completion = ("%s%s" % (prefix, field_name_desc), field_name)
completion_list.append(completion)
# Parent Relationship Describe
if display_parent_relationships:
for key in sorted(sobject_describe["parentRelationships"]):
parent_sobject = sobject_describe["parentRelationships"][key]
completion_list.append((prefix + key + "\t" + parent_sobject + "(c2p)", key))
# Child Relationship Describe
if display_child_relationships:
for key in sorted(sobject_describe["childRelationships"]):
child_sobject = sobject_describe["childRelationships"][key]
completion_list.append((prefix + key + "\t" + child_sobject + "(p2c)", key))
return completion_list
def get_component_completion(username, component_type, tag_has_ending=False):
""" Return the formatted completion list of custom Apex/Lightning component
from local src path
Return:
* completion_list -- all Apex/Lightning component completion list
"""
lightning = {".cmp": "LightningComponent"}
completion_list = []
component_settings = sublime.load_settings(context.COMPONENT_METADATA_SETTINGS)
if not component_settings.has(username):
return completion_list
component_attrs = component_settings.get(username)
if component_type in component_attrs:
components = component_attrs[component_type]
for component in components:
component_extension = components[component]["extension"]
none_lightning = component_type == "AuraDefinitionBundle" and component_extension not in lightning
if "name" not in components[component] or none_lightning:
continue
component_name = components[component]["name"]
if component_type in ["ApexComponent", "AuraDefinitionBundle"]:
c_type = lightning.get(component_extension, component_type)
display = "c:%s\t%s" % (component_name, c_type)
value = "c:%s%s" % (component_name, "" if tag_has_ending else "$1>")
completion_list.append((display, value))
else:
completion_list.append((component_name + "\t" + component_type, component_name))
return completion_list
def get_component_attributes(settings, component_name, is_lightning=False):
if is_lightning:
component_dir = os.path.join(settings["workspace"], "src",
"aura", component_name, component_name + ".cmp")
else:
component_dir = os.path.join(settings["workspace"], "src",
"components", component_name + ".component")
attributes = []
if os.path.isfile(component_dir):
name, _type, description = "", "", ""
with open(component_dir, "rb") as fp:
try:
content = fp.read()
except UnicodeDecodeError as ex:
sublime.status_message(str(ex))
return attributes
pattern = "<%s:attribute[\\S\\s]*?>" % (
"aura" if is_lightning else "apex"
)
for match in re.findall(pattern, content.decode("utf-8"), re.IGNORECASE):
pattern = '\\w+\\s*=\\s*"[\\s\\S]*?"'
for m in re.findall(pattern, match, re.IGNORECASE):
attr, value = m.split('=')
attr, value = attr.strip(), value.strip()
value = value[1:-1]
if attr.lower() == "name":
name = value
if attr.lower() == "type":
_type = value
if attr.lower() == "description":
description = value
if name and _type:
attributes.append({
"name": name,
"type": _type,
"description": description
})
return attributes
def get_attribute_completion(settings, component_name, is_lightning=False):
completion_list = []
for attribute in get_component_attributes(settings, component_name, is_lightning):
display = "%s\t%s(%s)" % (
attribute["name"],
attribute["description"],
attribute["type"].capitalize()
)
value = '%s="$1"$0' % attribute["name"]
completion_list.append((display, value))
return completion_list
def convert_15_to_18(the15Id):
""" Convert Salesforce 15 Id to 18 Id
Arguments:
* the15Id - to be converted 15 Id
Return:
* 18 Id - converted 18 Id
"""
if not the15Id or len(the15Id) != 15: return the15Id
cmap = {
"00000": "A", "00001": "B", "00010": "C", "00011": "D", "00100": "E",
"00101": "F", "00110": "G", "00111": "H", "01000": "I", "01001": "J",
"01010": "K", "01011": "L", "01100": "M", "01101": "N", "01110": "O",
"01111": "P", "10000": "Q", "10001": "R", "10010": "S", "10011": "T",
"10100": "U", "10101": "V", "10110": "W", "10111": "X", "11000": "Y",
"11001": "Z", "11010": "0", "11011": "1", "11100": "2", "11101": "3",
"11110": "4", "11111": "5"
}
chars = [cmap["".join(["1" if c.isupper() else "0" for c in char[::-1]])] \
for char in list_chunks(the15Id, 5)]
return the15Id + "".join(chars)
def list_chunks(l, n):
""" Yield successive n-sized chunks from l.
Arguments:
* l - to be chunked list
* n - split size
"""
for i in range(0, len(l), n):
yield l[i:i + n]
def dict_chunks(data, SIZE=10000):
from itertools import islice
it = iter(data)
for i in range(0, len(data), SIZE):
yield {k: data[k] for k in islice(it, SIZE)}
def open_with_browser(show_url, use_default_chrome=True):
""" Utility for open file in browser
Arguments:
* use_default_browser -- optional; if true, use chrome configed in settings to open it
"""
settings = context.get_settings()
browser_path = settings["default_chrome_path"]
if not use_default_chrome or not os.path.exists(browser_path):
webbrowser.open_new_tab(show_url)
else:
webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(browser_path))
webbrowser.get('chrome').open_new_tab(show_url)
def remove_comments(view, regions):
# Get all comment regions
comment_regions = view.find_by_selector('comment')
matched_regions = []
for region in regions:
# check whether region is comment statement
invalid_region = False
for comment_region in comment_regions:
if comment_region.contains(region):
invalid_region = True
break
if "\n" in view.substr(region):
invalid_region = True
break
# Check whether DML statement, for example
# insert prd | update prd | delete prd
# insert is not the correct variable type
pattern = '(insert|update|upsert|delete|undelete)+\\s+'
if re.match(pattern, view.substr(region), re.IGNORECASE):
continue
# If region is comment statement, just skip
if not invalid_region:
matched_regions.append(region)
return matched_regions
def get_variable_type(view, pt, pattern):
"""Return the matched soql region
Arguments:
* view -- current active view
* pt - the cursor point
* pattern - the regular expression for finding matched region
"""
# Get the matched variable type
matched_regions = view.find_all(pattern, sublime.IGNORECASE)
uncomment_regions = remove_comments(view, matched_regions)
# Three scenarios:
# 1. If no matched regions
# 2. Only one matched region
# 3. More than one matched region
if not uncomment_regions:
return ""
elif len(uncomment_regions) == 1:
matched_region = uncomment_regions[0]
else:
row_region = {} # Row => Region
for mr in uncomment_regions:
row, col = view.rowcol(mr.begin())
row_region[row] = mr
# Get the cursor row
cursor_row = view.rowcol(pt)[0]
# Three steps:
# 1. Add the cursor row and matched rows together
# 2. Sort all rows by ASC
# 3. Get the previous row of cursor row
rows = list(row_region.keys())
rows.append(cursor_row)
rows = sorted(rows)
cursor_index = rows.index(cursor_row)
matched_region = row_region[rows[cursor_index - 1]]
# Get the content of matched region
matched_str = view.substr(matched_region).strip()
# If list, map, set
if "<" in matched_str and ">" in matched_str:
variable_type = matched_str.split("<")[0].strip()
# String[] strs;
elif "[]" in matched_str:
variable_type = 'list'
# String str;
else:
variable_type = matched_str.split(" ")[0]
return variable_type
def get_soql_match_region(view, pt):
"""Return the mgatched soql region
Arguments:
* view -- current Active View
Return:
* matched_region -- Found SOQL
* sobject_name -- Found Sobject Name in SOQL
* is_between_start_and_from -- the cursor point is between start and the last from
"""
pattern = "SELECT\\s+[^;]+FROM\\s+[1-9_a-zA-Z]+"
matched_regions = view.find_all(pattern, sublime.IGNORECASE)
matched_region = None
is_between_start_and_from = False
sobject_name = None
for m in matched_regions:
if m.contains(pt):
matched_region = m
break
if not matched_region:
return (matched_region, is_between_start_and_from, sobject_name)
match_str = view.substr(matched_region)
match_begin = matched_region.begin()
select_pos = match_str.lower().find("select")
from_pos = match_str.lower().rfind("from")
if pt >= (select_pos + match_begin) and pt <= (from_pos + match_begin):
is_between_start_and_from = True
sobject_name = match_str[from_pos + 5:]
sobject_name = sobject_name.strip()
return (matched_region, is_between_start_and_from, sobject_name)
def parse_symbol_table(symbol_table):
"""Parse the symbol_table to completion (Copied From MavensMate)
Arguments:
* symbol_table -- ApexClass Symbol Table
"""
completions = {}
if not symbol_table:
return completions;
for c in symbol_table.get('constructors', []):
params = []
modifiers = " ".join(c.get("modifiers", []))
if 'parameters' in c and type(c['parameters']) is list and len(c['parameters']) > 0:
for p in c['parameters']:
params.append(p["type"].capitalize() + " " + p["name"])
paramStrings = []
for i, p in enumerate(params):
paramStrings.append("${" + str(i + 1) + ":" + params[i] + "}")
paramString = ", ".join(paramStrings)
completions[modifiers + " " + c["name"] + "(" + ", ".join(params) + ")"] = \
"%s(%s)" % (c["name"], paramString)
else:
completions[modifiers + " " + c["name"] + "()"] = c["name"] + "()${1:}"
for c in symbol_table.get('properties', []):
modifiers = " ".join(c.get("modifiers", []))
property_type = c["type"].capitalize() if "type" in c and c["type"] else ""
completions[modifiers + " " + c["name"] + "\t" + property_type] = c["name"]
for c in symbol_table.get('methods', []):
params = []
modifiers = " ".join(c.get("modifiers", []))
if 'parameters' in c and type(c['parameters']) is list and len(c['parameters']) > 0:
for p in c['parameters']:
params.append(p["type"] + " " + p["name"])
if len(params) == 1:
completions[modifiers + " " + c["name"] + "(" + ", ".join(params) + ") \t" + c['returnType']] = \
"%s(${1:%s})" % (c["name"], ", ".join(params))
elif len(params) > 1:
paramStrings = []
for i, p in enumerate(params):
paramStrings.append("${" + str(i + 1) + ":" + params[i] + "}")
paramString = ", ".join(paramStrings)
completions[modifiers + " " + c["name"] + "(" + ", ".join(params) + ") \t" + c['returnType']] = \
c["name"] + "(" + paramString + ")"
else:
completions[modifiers + " " + c["name"] + "(" + ", ".join(params) + ") \t" + c['returnType']] = \
c["name"] + "()${1:}"
for c in symbol_table.get("innerClasses", []):
tableDeclaration = c.get("tableDeclaration")
modifiers = " ".join(tableDeclaration.get("modifiers", []))
modifiers = modifiers + " " if modifiers else ""
# Add inner class completion without parameters
completions["%s%s\tInner Class" % (modifiers, c["name"])] = "%s$1" % c["name"]
# Add inner class constructor completion
if 'constructors' in c and len(c['constructors']) > 0:
for con in c['constructors']:
modifiers = " ".join(con.get("modifiers", []))
params = []
if 'parameters' in con and type(con['parameters']) is list and len(con['parameters']) > 0:
for p in con['parameters']:
params.append(p["type"].capitalize() + " " + p["name"])
paramStrings = []
for i, p in enumerate(params):
paramStrings.append("${" + str(i + 1) + ":" + params[i] + "}")
paramString = ", ".join(paramStrings)
completions[modifiers + " " + con["name"] + "(" + ", ".join(params) + ")"] = \
c["name"] + "(" + paramString + ")"
else:
completions[modifiers + " " + con["name"] + "()"] = \
c["name"] + "()${1:}"
return completions
def add_operation_history(operation, history_content):
"""Keep the history in the local history
Arguments:
* operation -- the operation source
* history_content -- the content needed to keep
"""
settings = context.get_settings()
if not settings["keep_operation_history"]: return
splits = operation.split("/")
if len(splits) == 1:
folder, operation = "", splits[0]
elif len(splits) == 2:
folder, operation = splits
outputdir = settings["workspace"] + "/.history/" + folder
if not os.path.exists(outputdir):
os.makedirs(outputdir)
time_stamp = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
history = "%s\n```java\n%s\n```\n\n" % (time_stamp, history_content)
fp = open(outputdir + "/%s.md" % operation, "ab")
fp.write(history.encode("utf-8"))
fp.close()
def add_config_history(operation, content, settings, ext="json"):
"""Keep the history in the local history
Arguments:
* operation -- the operation source
* history_content -- the content needed to keep
"""
outputdir = os.path.join(settings["workspace"], ".config")