-
Notifications
You must be signed in to change notification settings - Fork 46
/
Copy pathprocessor.py
2090 lines (1708 loc) · 80 KB
/
processor.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 sublime_plugin
import os
import xml
import urllib
import json
import threading
import time
import pprint
import urllib.parse
import shutil
import datetime
import math
from xml.sax.saxutils import unescape
from . import requests, context, util
from .context import COMPONENT_METADATA_SETTINGS
from .salesforce import soap, message
from .salesforce.api.bulk import BulkJob
from .salesforce.api.bulk import BulkApi
from .salesforce.api.metadata import MetadataApi
from .salesforce.api.tooling import ToolingApi
from .salesforce.api.apex import ApexApi
from .salesforce.lib.panel import Printer
from .progress import ThreadProgress, ThreadsProgress
from .salesforce.lib import diff
def handle_populate_users(callback_command, timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
if api.result or api.result["success"]:
records = api.result["records"]
users = {}
for record in records:
if not record["FirstName"]:
name = "%s => %s" % (record["LastName"], record["Username"])
else:
name = "%s => %s" % (
"%s %s" % (record["LastName"], record["FirstName"]),
record["Username"]
)
users[name] = record["Id"]
util.add_config_history("users", users, settings)
sublime.active_window().run_command(callback_command)
# If sobjects is exist in `/.config/users.json`, just return it
settings = context.get_settings()
user_cache = os.path.join(settings["workspace"], ".config", "users.json")
if os.path.isfile(user_cache): return json.loads(open(user_cache).read())
# If not exist, we need to use callback function
api = ToolingApi(settings)
query = "SELECT Id, FirstName, LastName, Username FROM User WHERE IsActive = true"
thread = threading.Thread(target=api.query_all, args=(query,))
thread.start()
handle_thread(thread, timeout)
ThreadProgress(api, thread, "Downloading Users List", "Succeed to download users list")
def populate_sobject_recordtypes():
"""
Get dict ([sobject, recordtype name] => recordtype id) in whole org
@return: {
username , "sobject_recordtypes": {
sobject + rtname: rtid
}
...
}
"""
# Get settings
settings = context.get_settings()
# If sobjects is exist in `/.config/recordtype.json`, just return it
recordtype_path = settings["workspace"] + "/.config/recordtype.json"
if os.path.isfile(recordtype_path):
recordtype = json.loads(open(recordtype_path).read())
return recordtype
# If sobjects is not exist in globals(), post request to pouplate it
api = ToolingApi(settings)
query = "SELECT Id, Name, SobjectType FROM RecordType"
thread = threading.Thread(target=api.query_all, args=(query,))
thread.start()
while thread.is_alive() or not api.result:
time.sleep(1)
# Exception Process
if not api.result["success"]:
Printer.get('error').write(message.SEPRATE.format(util.format_error_message(api.result)))
return
records = api.result["records"]
sobject_recordtypes = {}
for recordtype in records:
sobject_type = recordtype["SobjectType"]
recordtype_name = recordtype["Name"]
recordtype_id = recordtype["Id"]
sobject_recordtypes[sobject_type + ", " + recordtype_name] = recordtype_id
# Add Master of every sobject to List
sobjects_describe = util.populate_sobjects_describe()
for sobject_type in sobjects_describe:
sobject_describe = sobjects_describe[sobject_type]
if not sobject_describe["layoutable"]: continue
sobject_recordtypes[sobject_type + ", Master"] = "012000000000000AAA"
util.add_config_history("recordtype", sobject_recordtypes, settings)
return sobject_recordtypes
def handle_update_user_language(language, timeout=120):
settings = context.get_settings()
api = ToolingApi(settings)
session = util.get_session_info(settings)
if not session:
return Printer.get('error').write("Login is required before this action")
patch_url = "/sobjects/User/%s" % session["user_id"]
thread = threading.Thread(target=api.patch,
args=(patch_url, {"LanguageLocaleKey": language},))
thread.start()
ThreadProgress(api, thread, "Updating User Language to " + language,
"User language is updated to " + language)
def handle_enable_development_mode(user_id, timeout=120):
settings = context.get_settings()
api = ToolingApi(settings)
patch_url = "/sobjects/User/%s" % user_id
thread = threading.Thread(target=api.patch,
args=(patch_url, {"UserPreferencesApexPagesDeveloperMode": True},))
thread.start()
ThreadProgress(api, thread, "Enabling User Development Mode",
"Succeed to Enabling User Development Mode")
def handle_update_user_password(user_id, new_password, timeout=120):
settings = context.get_settings()
api = ToolingApi(settings)
thread = threading.Thread(target=api.manage_password, args=(
user_id, {"NewPassword": new_password},
))
thread.start()
masked_password = new_password[:5] + "*" * len(new_password[3:])
ThreadProgress(api, thread, "Updating User Password to " + masked_password,
"Succeed to update user password to " + masked_password)
def handle_login_thread(callback_options={}, force=False, timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
result = api.result
if result and result["success"]:
if "callback_command" in callback_options:
callback_command = callback_options["callback_command"]
args = callback_options["args"] if "args" in callback_options else {}
sublime.active_window().run_command(callback_command, args)
settings = context.get_settings()
api = ToolingApi(settings)
thread = threading.Thread(target=api.login, args=(force,))
thread.start()
handle_thread(thread, timeout)
default_project_name = settings["default_project_name"]
ThreadProgress(api, thread, "Login to %s" % default_project_name,
default_project_name + " Login Succeed")
def handle_view_code_coverage(component_name, component_id, body, timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
result = api.result
if not result["success"]:
return
if result["totalSize"] == 0:
Printer.get("log").write("There is no available code coverage")
return
# Populate the coverage info from server
uncovered_lines = result["records"][0]["Coverage"]["uncoveredLines"]
covered_lines = result["records"][0]["Coverage"]["coveredLines"]
covered_lines_count = len(covered_lines)
uncovered_lines_count = len(uncovered_lines)
total_lines_count = covered_lines_count + uncovered_lines_count
if total_lines_count == 0:
Printer.get("log").write("There is no available code coverage")
return
coverage_percent = covered_lines_count / total_lines_count * 100
# Append coverage statistic info
coverage_statistic = "%s Coverage: %.2f%%(%s/%s)" % (
component_name, coverage_percent,
covered_lines_count, total_lines_count
)
# 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
split_lines = view.lines(sublime.Region(0, view.size()))
uncovered_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 uncovered_lines:
uncovered_region.append(region)
# Append body with uncovered line
view.add_regions("uncovered_lines", uncovered_region, "invalid", "dot",
sublime.DRAW_SOLID_UNDERLINE | sublime.DRAW_EMPTY_AS_OVERWRITE)
settings = context.get_settings()
api = ToolingApi(settings)
query = "SELECT Coverage FROM ApexCodeCoverageAggregate " + \
"WHERE ApexClassOrTriggerId = '{0}'".format(component_id)
thread = threading.Thread(target=api.query, args=(query, True,))
thread.start()
ThreadProgress(api, thread, "View Code Coverage of " + component_name,
"View Code Coverage of " + component_name + " Succeed")
handle_thread(thread, timeout)
def handle_refresh_folder(types, ignore_package_xml=True, timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
# Not succeed
if not api.result or not api.result["success"]: return
# Get refresh result
result = api.result
# Populate extract_to directory
extract_to = settings["workspace"]
# Extract zip, True means not override package.xml
thread = threading.Thread(target=util.extract_encoded_zipfile,
args=(result["zipFile"], extract_to, ignore_package_xml,))
thread.start()
util.reload_file_attributes(result["fileProperties"], settings)
# Hide panel 0.5 seconds later
sublime.set_timeout_async(Printer.get("log").hide_panel, 500)
# Start to request
settings = context.get_settings()
api = MetadataApi(settings)
thread = threading.Thread(target=api.retrieve, args=({"types": types},))
thread.start()
handle_thread(thread, timeout)
message = "Refresh Folder"
ThreadProgress(api, thread, message, message + " Succeed")
def handle_reload_symbol_tables(timeout=120):
"""
Reload Symbol Tables to Local Cache
"""
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
result = api.result
if not result["success"]: return
# Get the username of default project
username = settings["username"]
# Save symbolTable to component_metadata.sublime-settings
symbol_table_cache = sublime.load_settings("symbol_table.sublime-settings")
symboltable_dict = symbol_table_cache.get(username, {})
for record in result["records"]:
# Sometimes symbolTable is null, just skip
if not record["SymbolTable"]: continue
# Outer completions
outer = util.parse_symbol_table(record["SymbolTable"])
symboltable_dict[record["Name"].lower()] = {
"outer": outer,
"name": record["Name"]
}
# Inner completions
inners = {}
for inn in record["SymbolTable"]["innerClasses"]:
inner = util.parse_symbol_table(inn)
inners[inn["name"].lower()] = inner
symboltable_dict[record["Name"].lower()]["inners"] = inners
symbol_table_cache.set(settings["username"], symboltable_dict)
sublime.save_settings("symbol_table.sublime-settings")
settings = context.get_settings()
api = ToolingApi(settings)
thread = threading.Thread(target=api.query_symbol_table, args=(30,))
thread.start()
wating_message = "Reloading Symbol Tables"
ThreadProgress(api, thread, wating_message, wating_message + " Succeed")
handle_thread(thread, timeout)
def handle_reload_sobjects_completions(timeout=120):
"""
Save sobject describe to local which is used in completions
"""
def handle_threads(apis, threads, timeout):
for thread in threads:
if thread.is_alive():
sublime.set_timeout(lambda: handle_threads(apis, threads, timeout), timeout)
return
# If succeed, get the all sobject describe result
results = []
for api in apis:
results.extend(api.result)
# Save all sobject describe result to sublime settings
s = sublime.load_settings("sobjects_completion.sublime-settings")
sobjects_completion = {"sobjects": {}}
all_parent_relationship_dict = {}
all_child_relationship_dict = {}
for sobject_describe in results:
# Initiate Sobject completions
if "name" not in sobject_describe:
continue
sobject_name = sobject_describe["name"]
# If sobject is excluded sobject, just continue
sobject_name = sobject_name.lower()
sobjects_completion["sobjects"][sobject_name] = {
"name": sobject_describe["name"],
"keyPrefix": sobject_describe["keyPrefix"],
"layoutable": sobject_describe["layoutable"],
"triggerable": sobject_describe["triggerable"]
}
# Combine Fields dict, Picklist Field dict and parent relationship dict
fields_dict = {}
picklist_field_dict = {}
parent_relationship_dict = {}
child_relationship_dict = {}
for f in sobject_describe["fields"]:
field_name = f["name"]
precision = f["precision"]
scale = f["scale"]
field_type = f["type"]
referenceTo = f["referenceTo"] if "referenceTo" in f else []
if f["calculatedFormula"]:
capitalize_field = field_type.capitalize()
field_desc_dict = {
"double": "Formula(%s, %s, %s)" % (capitalize_field, precision, scale),
"currency": "Formula(%s, %s, %s)" % (capitalize_field, precision, scale),
"date": "Formula(Date)",
"datetime": "Formula(Datetime)",
"boolean": "Formula(Boolean)",
"int": "Formula(Integer)",
"reference": ("Reference(%s)" % ",".join(referenceTo)) if referenceTo else "Reference",
"other": "Formula(%s, %s)" % (capitalize_field, f["length"])
}
else:
field_desc_dict = {
"double": "Double(%s, %s)" % (precision, scale),
"currency": "Currency(%s, %s)" % (precision, scale),
"date": "Date",
"datetime": "Datetime",
"boolean": "Boolean",
"reference": ("Reference(%s)" % ",".join(referenceTo)) if referenceTo else "Reference",
"int": "Integer",
"other": "%s(%s)" % (field_type.capitalize(), f["length"])
}
# External Or not
externalUniqueNotation = ""
if f["externalId"] or f["unique"]:
externalUniqueNotation = "[%s%s%s] " % (
"E" if f["externalId"] else "",
"U" if f["unique"] else "",
"R" if not f["nillable"] else ""
)
# If display_field_name_and_label setting is true,
# display both field name and field label
field_name_desc = "%s(%s)" % (field_name, f["label"]) \
if settings["display_field_name_and_label"] else field_name
# Display field type with specified format
field_type_desc = field_desc_dict[field_type] if field_type \
in field_desc_dict else field_desc_dict["other"]
fd = "%s%s\t%s" % (externalUniqueNotation, field_name_desc, field_type_desc)
fields_dict[fd] = field_name
# Picklist Dcit
if f["type"] == "picklist":
picklists = []
for picklistValue in f["picklistValues"]:
picklists.append({
"label": picklistValue["label"],
"value": picklistValue["value"]
})
picklist_field_dict[field_name] = picklists
# List all Reference Field Relationship Name as fields
# Some fields has two more references, we can't list the fields of it
if not len(f["referenceTo"]) == 1: continue
parentRelationshipName = f["relationshipName"]
if not parentRelationshipName: continue
parentSobject = f["referenceTo"][0]
if parentRelationshipName in all_parent_relationship_dict:
is_duplicate = False
for so in all_parent_relationship_dict[parentRelationshipName]:
if parentSobject == so:
is_duplicate = True
break
if not is_duplicate:
all_parent_relationship_dict[parentRelationshipName].append(parentSobject)
else:
all_parent_relationship_dict[parentRelationshipName] = [parentSobject]
# Add Parent Relationship Name
parent_relationship_dict[f["relationshipName"]] = parentSobject
# Child Relationship dict
for f in sobject_describe["childRelationships"]:
childRelationshipName = f["relationshipName"]
childSobject = f["childSObject"]
if not childRelationshipName: continue
# Add Parent Relationship Name as Field
child_relationship_dict[childRelationshipName] = childSobject
# Combine sobject fields dict and sobject child relationship dict
sobjects_completion["sobjects"][sobject_name]["fields"] = fields_dict
sobjects_completion["sobjects"][sobject_name]["picklist_fields"] = picklist_field_dict
sobjects_completion["sobjects"][sobject_name]["parentRelationships"] = parent_relationship_dict
sobjects_completion["sobjects"][sobject_name]["childRelationships"] = child_relationship_dict
# Populate Child Relationship and Parent Relationship
sobjects_completion["parentRelationships"] = all_parent_relationship_dict
# sobjects_completion["childRelationships"] = all_child_relationship_dict
# Every project has unique username
username = settings["username"]
s.set(username, sobjects_completion)
# Save settings
sublime.save_settings("sobjects_completion.sublime-settings")
# Reload cache for completions
from . import completions
sublime.set_timeout(lambda: completions.load_sobject_cache(
True, username
), 5)
def handle_thread(api, thread, timeout=120):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(api, thread, timeout), timeout)
return
# Exception Process
if not api.result or not api.result["success"]:
return
# Get describe result of all sObjects
sobjects_describe = api.result["sobjects"]
sobjects = list(sobjects_describe.keys())
mcc = settings["maximum_concurrent_connections"]
chunked_sobjects = util.list_chunks(sobjects, math.ceil(len(sobjects) / mcc))
threads = []
apis = []
for sobjects in chunked_sobjects:
sobjects = [
{"name": so, "tooling": sobjects_describe[so]["tooling"]}
for so in sobjects
]
api = ToolingApi(settings)
thread = threading.Thread(target=api.describe_sobjects, args=(sobjects,))
thread.start()
threads.append(thread)
apis.append(api)
ThreadsProgress(threads, "Download Cache of Sobjects", "Download Cache of Sobjects Succeed")
handle_threads(apis, threads, 10)
settings = context.get_settings()
api = ToolingApi(settings)
thread = threading.Thread(target=api.get_sobjects, args=())
thread.start()
ThreadProgress(api, thread, "Global Describe", "Global Describe Succeed")
handle_thread(api, thread, timeout)
def handle_destructive_files(dirs_or_files, ignore_folder=True, timeout=120):
"""
Destruct File(s) from Salesforce org and remove from local disk via Metadata API
@param dirs_or_files: lightning direcotry(bundle) or files
@param ignore_folder: ignore the folder itself
@param timeout: timeout in second
@return: None
"""
def handle_destruct_thread(thread, timeout=120):
if thread.is_alive():
sublime.set_timeout(lambda: handle_destruct_thread(thread, timeout), timeout)
return
# After succeed, remove dirs_or_files and related *-meta.xml from local
if "body" in api.result and api.result["body"]["status"] == "Succeeded":
# Remove Component metadata cache
util.delete_component_attribute(dirs_or_files)
# Remove file from local disk and close the related view
win = sublime.active_window()
for _file_or_dir in dirs_or_files:
view = util.get_view_by_file_name(_file_or_dir)
if view:
win.focus_view(view)
win.run_command("close")
if os.path.isfile(_file_or_dir):
os.remove(_file_or_dir)
else:
shutil.rmtree(_file_or_dir)
# Remove related *-meta.xml file from local disk and close the related view
if ignore_folder and os.path.isfile(_file_or_dir + "-meta.xml"):
view = util.get_view_by_file_name(_file_or_dir + "-meta.xml")
if view:
win.focus_view(view)
win.run_command("close")
os.remove(_file_or_dir + "-meta.xml")
settings = context.get_settings()
api = MetadataApi(settings)
base64_encoded_zip = util.build_destructive_package_by_files(dirs_or_files, ignore_folder)
thread = threading.Thread(target=api.deploy, args=(base64_encoded_zip,))
thread.start()
ThreadProgress(api, thread, "Destructing Files", "Destructing Files Succeed")
handle_destruct_thread(thread, timeout)
def handle_destructive_package_xml(types, timeout=120):
def handle_thread(thread, timeout=120):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
settings = context.get_settings()
api = MetadataApi(settings)
base64_encoded_zip = util.build_destructive_package_by_package_xml(types)
thread = threading.Thread(target=api.deploy, args=(base64_encoded_zip,))
thread.start()
ThreadProgress(api, thread, "Destructing Package.xml", "Destructing Package.xml Succeed")
handle_thread(thread, timeout)
def handle_deploy_thread(base64_encoded_zip, source_org=None, element=None,
chosen_classes=[], timeout=120, update_meta=False):
"""
Deploy code to specified Salesforce org via Metadata API
@param base64_encoded_zip: code content in base64 encoded
@param source_org: destination Salesforce org
@param element: aura element in [Application, Component, Event, Controller, Helper,etc.]
@param chosen_classes:
@param timeout: timeout in second
@param update_meta: whether update component metadata after deployed
@return: None
"""
def handle_thread(thread, timeout=120):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
# If source_org is not None, we need to switch project back
if settings["switch_back_after_migration"] and source_org:
util.switch_project(source_org)
result = api.result
body = result["body"]
if body["status"] == "Succeeded" and update_meta:
handle_update_lightning_meta(body, element)
settings = context.get_settings()
api = MetadataApi(settings)
thread = threading.Thread(target=api.deploy, args=(
base64_encoded_zip,
chosen_classes,
))
thread.start()
ThreadProgress(api, thread, "Deploy Metadata to %s" % settings["default_project_name"],
"Metadata Deployment Finished")
handle_thread(thread, timeout)
def handle_update_lightning_meta(body, element, timeout=120):
"""
Update lightning aura/web component metadata via Tooling API after creation
:param body: body data returned from SOAP API
:param element: Aura bundle type in `COMPONENT`, `CONTROLLER`, `HELPER`, `SVG`...
:param timeout: timeout in second
:param cmp_type: type
:return:
"""
def handle_thread(thread, full_name, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, full_name, timeout), timeout)
return
result = api.result
if not result or not result["success"]:
return
if result["totalSize"] == 0:
Printer.get("log").write("There is no component data")
return
elif result["totalSize"] == 1 and bundle_type == "AuraDefinitionBundle":
# save single aura definition file
record = result["records"][0]
cmp_meta = {
"name": full_name[:full_name.find('.')],
"extension": full_name[full_name.find('.'):],
"id": record["Id"],
"lastModifiedDate": record["LastModifiedDate"],
"type": bundle_type,
"DefType": record["DefType"]
}
components_dict[bundle_type][full_name.lower()] = cmp_meta
elif bundle_type == "LightningComponentBundle":
# save multiple Lightning Component Resource files
for record in result["records"]:
_lwc, bundle_name, full_name = record["FilePath"].split("/") # lwc/t2/t2.js-meta.xml
cmp_meta = {
"name": full_name[:full_name.find('.')], # t2.js-meta
"extension": full_name[full_name.find('.'):], # .xml
"id": record["Id"],
"lastModifiedDate": record["LastModifiedDate"],
"type": bundle_type
}
components_dict[bundle_type][full_name.lower()] = cmp_meta
# Save and reload component metadata
if result["totalSize"] >= 1:
s.set(username, components_dict)
sublime.save_settings(context.COMPONENT_METADATA_SETTINGS)
# Refresh metadata settings
sublime.set_timeout(lambda: util.load_metadata_cache(True, settings["username"]), 5)
settings = context.get_settings()
username = settings["username"]
s = sublime.load_settings(context.COMPONENT_METADATA_SETTINGS)
if not s.has(username):
return
component_successes = body["details"]["componentSuccesses"]
if isinstance(component_successes, dict):
component_successes = [component_successes]
for item in component_successes:
bundle_type = item["componentType"]
if bundle_type in ["AuraDefinitionBundle", "LightningComponentBundle"]:
base_name = item["fullName"]
full_name = (base_name + context.EXT_DICT.get(element.lower())) \
if element is not None and bundle_type == "AuraDefinitionBundle" else ""
components_dict = s.get(username, {})
# Prevent exception if no component in org
if bundle_type not in components_dict:
components_dict = {bundle_type: {}}
# Build components dict
api = ToolingApi(settings)
query_str = "SELECT Id, Format, LastModifiedDate, LastModifiedById "
if bundle_type == 'AuraDefinitionBundle':
query_str += ", DefType FROM AuraDefinition WHERE AuraDefinitionBundleId = '%s' and DefType = '%s'"\
% (item['id'], element.upper())
elif bundle_type == 'LightningComponentBundle':
query_str += ", FilePath FROM LightningComponentResource WHERE LightningComponentBundleId = '%s'"\
% (item['id'])
thread = threading.Thread(target=api.query, args=(query_str, True))
thread.start()
ThreadProgress(api, thread, "Update Component Metadata", "Update Component Metadata Finished")
handle_thread(thread, full_name, timeout)
break
def handle_track_all_debug_logs_thread(users, timeout=120):
settings = context.get_settings()
api = ToolingApi(settings)
# Divide users into pieces of dict
pieces = []
maximum_concurrent_connections = settings["maximum_concurrent_connections"]
split = math.ceil(len(users) / maximum_concurrent_connections)
for item in util.dict_chunks(users, split):
pieces.append(item)
threads = []
for users in pieces:
api = ToolingApi(settings)
thread = threading.Thread(target=api.create_trace_flags, args=(users,))
thread.start()
threads.append(thread)
ThreadsProgress(threads, "Creating Trace Flags", "Creating Trace Flags Finished")
def handle_cancel_deployment_thread(async_process_id, timeout=120):
settings = context.get_settings()
api = MetadataApi(settings)
thread = threading.Thread(target=api._invoke_method, args=(
"cancelDeploy", {
"async_process_id": async_process_id,
}
))
thread.start()
ThreadProgress(api, thread, "Canceling Deploy", "Canceling Deploy Succeed")
def handle_close_jobs_thread(job_ids, timeout=120):
settings = context.get_settings()
bulkjob = BulkJob(settings, None, None)
for job_id in job_ids:
thread = threading.Thread(target=bulkjob.close_job, args=(job_id,))
thread.start()
def handle_bulk_operation_thread(sobject, inputfile, operation, timeout=120):
settings = context.get_settings()
bulkapi = BulkApi(settings, sobject, inputfile)
if operation == "insert":
target = bulkapi.insert
elif operation == "update":
target = bulkapi.update
elif operation == "upsert":
target = bulkapi.upsert
elif operation == "delete":
target = bulkapi.delete
thread = threading.Thread(target=target, args=())
thread.start()
progress_message = operation + " " + sobject
ThreadProgress(bulkapi, thread, progress_message, progress_message + " Succeed")
def handle_backup_sobject_thread(sobject, soql=None, timeout=120):
settings = context.get_settings()
bulkapi = BulkApi(settings, sobject, soql)
thread = threading.Thread(target=bulkapi.query, args=())
thread.start()
wait_message = "Export Records of " + sobject
ThreadProgress(bulkapi, thread, wait_message, wait_message + " Succeed")
def handle_backup_all_sobjects_thread(timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
result = api.result
if not result or not result["success"]: return
threads = []
for sobject_describe in api.result["sobjects"]:
if "name" not in sobject_describe: continue
bulkapi = BulkApi(settings, sobject_describe["name"])
thread = threading.Thread(target=bulkapi.query, args=())
thread.start()
threads.append(thread)
wait_message = "Export All Sobjects Records"
ThreadsProgress(threads, wait_message, wait_message + " Succeed")
settings = context.get_settings()
api = ToolingApi(settings)
thread = threading.Thread(target=api.describe_global, args=())
thread.start()
ThreadProgress(api, thread, "Describe Global", "Describe Global Succeed")
handle_thread(thread, timeout)
def handle_export_workflows(settings, timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
# If succeed
sObjects = []
for sd in api.result["sobjects"]:
if "name" not in sd: continue
sObjects.append(sd["name"])
util.parse_workflow_metadata(settings, sObjects)
sublime.active_window().run_command("refresh_folder_list")
outputdir = settings["workspace"] + "/workflow/"
api = ToolingApi(settings)
thread = threading.Thread(target=api.describe_global, args=())
thread.start()
ThreadProgress(api, thread, "Export All Workflows", "Outputdir: " + outputdir)
handle_thread(thread, 10)
def handle_export_validation_rules(settings, timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
# If succeed
sObjects = []
for sd in api.result["sobjects"]:
if "name" not in sd: continue
sObjects.append(sd["name"])
util.parse_validation_rule(settings, sObjects)
sublime.active_window().run_command("refresh_folder_list")
api = ToolingApi(settings)
thread = threading.Thread(target=api.describe_global, args=())
thread.start()
ThreadProgress(api, thread, "Export All Validation Rules", "Validation Rules Export Succeed")
handle_thread(thread, 10)
def handle_export_customfield(timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
# If succeed
result = api.result
if not result or not result["success"]: return
# Write list to csv
outputdir = os.path.join(settings["workspace"], ".export")
if not os.path.exists(outputdir): os.makedirs(outputdir)
records = sorted(result["records"], key=lambda k: k['TableEnumOrId'])
outputfile = os.path.join(outputdir, "CustomField.csv")
util.list2csv(outputfile, records)
# Open the csv file
view = sublime.active_window().open_file(outputfile)
settings = context.get_settings()
api = ToolingApi(settings)
query = "SELECT Id,TableEnumOrId,DeveloperName,NamespacePrefix FROM CustomField"
thread = threading.Thread(target=api.query, args=(query, True,))
thread.start()
ThreadProgress(api, thread, 'Exporting CustomFields', "Exporting CustomFields Succeed")
handle_thread(thread, 10)
def handle_export_role_hierarchy(timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
# If succeed
result = api.result
if not result or not result["success"]: return
records = result["records"]
outputfile = util.export_role_hierarchy(records)
sublime.active_window().run_command("refresh_folder_list")
# Open file
view = sublime.active_window().open_file(outputfile)
settings = context.get_settings()
api = ToolingApi(settings)
soql = "SELECT Id, ParentRoleId, Name, " + \
"(SELECT Id, FirstName, LastName, Username FROM Users " + \
" WHERE IsActive = true AND Profile.UserLicense.Name = 'Salesforce') " + \
"FROM UserRole WHERE PortalType = 'None'"
thread = threading.Thread(target=api.query_all, args=(soql,))
thread.start()
ThreadProgress(api, thread, 'Exporting Role Hierarchy', "Role Hierarchy Exporting Succeed")
handle_thread(thread, 10)
def handle_export_data_template_thread(sobject, recordtype_name, recordtype_id, vertical, timeout=120):
def handle_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_thread(thread, timeout), timeout)
return
# If succeed
result = api.result
if not result or not result["success"]: return
# If outputdir is not exist, just make it
if not os.path.exists(outputdir): os.makedirs(outputdir)
# Write parsed result to csv
if vertical:
util.parse_data_template_vertical(output_file_dir, result)
else:
util.parse_data_template_horizontal(output_file_dir, result)
sublime.active_window().run_command("refresh_folder_list")
Printer.get("log").write("Data Template for %s: %s" % (sobject, output_file_dir))
settings = context.get_settings()
outputdir = settings["workspace"] + "/.export/layoutWorkbooks"
output_file_dir = "%s/%s-%s.csv" % (
outputdir, sobject, recordtype_name
)
api = ToolingApi(settings)
url = "/sobjects/%s/describe/layouts/%s" % (sobject, recordtype_id)
thread = threading.Thread(target=api.get, args=(url,))
thread.start()
wait_message = "Export Data Template of %s=>%s" % (sobject, recordtype_name)
ThreadProgress(api, thread, wait_message, "Outputdir: " + output_file_dir)
handle_thread(thread, 120)
def handle_export_query_to_csv(tooling, soql, csv_name, data=None, timeout=120):
def handle_new_view_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_new_view_thread(thread, timeout), timeout)
return
result = api.result
if "success" in result and not result["success"]:
return
outputdir = os.path.join(settings["workspace"], ".export", "Query2CSV")
if not os.path.exists(outputdir): os.makedirs(outputdir)
time_stamp = time.strftime("%Y-%m-%d-%H-%M", time.localtime())
outputfile = os.path.join(outputdir, "%s.csv" % csv_name)
with open(outputfile, "wb") as fp:
fp.write(util.query_to_csv(result, soql))
view = sublime.active_window().open_file(outputfile)
settings = context.get_settings()
api = ToolingApi(settings)
thread = threading.Thread(target=api.query_all, args=(soql, tooling,))
thread.start()
progress_message = "Export Query To %s.csv" % csv_name
ThreadProgress(api, thread, progress_message, progress_message + " Succeed")
handle_new_view_thread(thread, timeout)
def handle_execute_rest_test(operation, url, data=None, timeout=120):
def handle_new_view_thread(thread, timeout):
if thread.is_alive():
sublime.set_timeout(lambda: handle_new_view_thread(thread, timeout), timeout)
return
result = api.result
# If succeed
if "list" in result:
result = result["list"]
if "str" in result:
result = result["str"]
# If response result is just like '"{\\"name\\":\\"test\\"}"'
# we will remove the \\ and convert it to json automatically
if settings.get("remove_slash_for_rest_response", False):