-
Notifications
You must be signed in to change notification settings - Fork 46
/
main.py
2706 lines (2106 loc) · 95.3 KB
/
main.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 webbrowser
import urllib
import re
import os
import sys
import shutil
import zipfile
import json
import pprint
import time
import xml
import urllib.request
from . import requests
from . import processor
from . import context
from . import util
from .salesforce.lib import xmlformatter
from .salesforce.lib.jsontoapex import JSONConverter
from .salesforce.lib.panel import Printer
from .salesforce import xmltodict
from .salesforce import message
class RemoveComments(sublime_plugin.TextCommand):
def run(self, edit):
comments = self.view.find_by_selector('comment')
for region in reversed(comments):
region = self.view.full_line(region)
self.view.erase(edit, region)
class Haoku(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(Haoku, self).__init__(*args, **kwargs)
def run(self, router=""):
settings = context.get_settings()
session = util.get_session_info(settings)
if not session:
Printer.get("error").write("Please Login Firstly")
return
heroku_host = "https://haoku.herokuapp.com"
# heroku_host = "http://localhost:3000"
show_params = {
"accessToken": session["session_id"],
"instanceUrl": session["instance_url"],
"username": settings["username"],
"router": router
}
show_params = urllib.parse.urlencode(show_params)
open_url = heroku_host + '?%s' % show_params
util.open_with_browser(open_url)
class BaseSelection(object):
def is_enabled(self):
if not self.view.size(): return False
self.selection = self.view.substr(self.view.sel()[0])
self.choose_all = False
if not self.selection:
self.choose_all = True
self.selection = self.view.substr(sublime.Region(0,
self.view.size()))
return True
class BuildCustomLabelsMetadata(sublime_plugin.TextCommand):
def run(self, edit):
try:
file_name = self.view.file_name()
lables_metadata = util.build_metadata(file_name, {
"root": "CustomLabels",
"leaf": "labels",
"xmlNodes": [
"shortDescription", "fullName",
"categories", "protected",
"language", "value"
]
})
formatter = xmlformatter.Formatter(indent=4)
lables_metadata = formatter.format_string(lables_metadata)
except ValueError as ve:
return Printer.get('error').write(str(ve))
view = sublime.active_window().new_file()
view.set_syntax_file("Packages/XML/XML.tmLanguage")
view.run_command("new_view", {
"name": "CustomLabels.labels",
"input": lables_metadata.decode("utf-8")
})
class BuildCustomLabelsTranslationMetadata(sublime_plugin.TextCommand):
def run(self, edit):
try:
file_name = self.view.file_name()
translations = util.build_metadata(file_name, {
"root": "Translations",
"leaf": "customLabels",
"xmlNodes": ["name", "label"]
})
formatter = xmlformatter.Formatter(indent=4)
translations = formatter.format_string(translations)
except ValueError as ve:
raise ve
return Printer.get('error').write(str(ve))
view = sublime.active_window().new_file()
view.set_syntax_file("Packages/XML/XML.tmLanguage")
view.run_command("new_view", {
"name": "Translations.translation",
"input": translations.decode("utf-8")
})
class JsonFormat(BaseSelection, sublime_plugin.TextCommand):
def run(self, edit):
try:
formatted_json = json.dumps(json.loads(self.selection),
ensure_ascii=False, indent=4)
except ValueError as ve:
return Printer.get('error').write(str(ve))
if not self.choose_all:
view = sublime.active_window().new_file()
view.run_command("new_view", {
"name": "FormattedJSON",
"input": formatted_json
})
else:
self.view.window().run_command("new_dynamic_view", {
"view_id": self.view.id(),
"view_name": self.view.name(),
"point": 0,
"erase_all": True,
"input": formatted_json
})
class JsonSerialization(BaseSelection, sublime_plugin.TextCommand):
def run(self, edit):
try:
self.data = json.loads(self.selection)
except ValueError as ve:
return Printer.get('error').write(str(ve))
if not self.choose_all:
view = sublime.active_window().new_file()
view.run_command("new_view", {
"name": "SerializedJSON",
"input": json.dumps(self.data)
})
else:
self.view.window().run_command("new_dynamic_view", {
"view_id": self.view.id(),
"view_name": self.view.name(),
"point": 0,
"erase_all": True,
"input": json.dumps(self.data)
})
class JsonToApex(BaseSelection, sublime_plugin.TextCommand):
def run(self, edit):
try:
self.data = json.loads(self.selection)
except ValueError as ve:
return Printer.get('error').write(str(ve))
sublime.active_window().show_input_panel("Input Class Name: ",
"JSON2Apex", self.on_input_name, None, None)
def on_input_name(self, name):
if not name: name = "JSON2Apex"
# Start converting
snippet = JSONConverter(scope="global").convert2apex(name, self.data).snippet
view = sublime.active_window().new_file()
view.run_command("new_view", {
"name": "JSON2APEX",
"input": snippet
})
class JsonToXml(BaseSelection, sublime_plugin.TextCommand):
def run(self, edit):
try:
data = json.loads(self.selection)
result = xmltodict.unparse(data)
except ValueError as ve:
return Printer.get("error").write(str(ve))
except xml.parsers.expat.ExpatError as ex:
return Printer.get("error").write(str(ex))
new_view = sublime.active_window().new_file()
new_view.set_syntax_file("Packages/XML/XML.tmLanguage")
new_view.run_command("new_view", {
"name": "JSON2XML",
"input": util.format_xml(result).decode("UTF-8")
})
class JsonToCsv(BaseSelection, sublime_plugin.TextCommand):
def run(self, edit):
try:
_list = json.loads(self.selection)
if not isinstance(_list, list):
msg = "Your input is not valid json list"
return Printer.get("error").write(msg)
except ValueError as ve:
return Printer.get("error").write(str(ve))
except xml.parsers.expat.ExpatError as ex:
return Printer.get("error").write(str(ex))
new_view = sublime.active_window().new_file()
new_view.run_command("new_view", {
"name": "JSON2CSV.csv",
"input": util.json2csv(_list)
})
class XmlToJson(BaseSelection, sublime_plugin.TextCommand):
def run(self, edit):
try:
result = xmltodict.parse(self.selection)
except xml.parsers.expat.ExpatError as ex:
message = "You should open a XML file or choose any valid XML content"
if "line 1, column 0" in str(ex):
return Printer.get("error").write(message)
return Printer.get("error").write(str(ex))
new_view = sublime.active_window().new_file()
new_view.run_command("new_view", {
"name": "XML2JSON",
"input": json.dumps(result, indent=4)
})
class XmlFormat(BaseSelection, sublime_plugin.TextCommand):
def run(self, edit):
try:
formatter = xmlformatter.Formatter(indent=4)
formatted_xml = formatter.format_string(self.selection)
except xml.parsers.expat.ExpatError as ex:
message = "You should open a XML file or choose any valid XML content"
if "line 1, column 0" in str(ex):
return Printer.get("error").write(message)
return Printer.get("error").write(str(ex))
if not self.choose_all:
new_view = sublime.active_window().new_file()
new_view.set_syntax_file("Packages/XML/XML.tmLanguage")
new_view.run_command("new_view", {
"name": "XMLFormat",
"input": formatted_xml.decode("utf-8")
})
else:
self.view.window().run_command("new_dynamic_view", {
"view_id": self.view.id(),
"view_name": self.view.name(),
"point": 0,
"erase_all": True,
"input": formatted_xml.decode("utf-8")
})
class DiffWithServer(sublime_plugin.TextCommand):
def run(self, edit, switch=True, source_org=None):
if not source_org:
source_org = self.settings["default_project_name"]
if switch:
return self.view.window().run_command("switch_project", {
"callback_options": {
"callback_command": "diff_with_server",
"args": {
"switch": False,
"source_org": source_org
}
}
})
file_name = self.view.file_name()
attr = util.get_component_attribute(file_name, False, reload_cache=True)[0]
# If this component is not exist in chosen project, just stop
if not attr:
Printer.get("error").write("This component is not exist in chosen project")
return util.switch_project(source_org)
processor.handle_diff_with_server(attr, file_name, source_org)
def is_enabled(self):
self.file_name = self.view.file_name()
if not self.file_name:
return False
self.settings = context.get_settings()
self.attributes = util.get_file_attributes(self.file_name)
diffable_attrbs = ["classes", "triggers", "pages", "components", "aura", "lwc"]
if self.attributes["metadata_folder"] not in diffable_attrbs:
return False
return True
def is_visible(self):
return self.is_enabled()
class DiffWithOtherFile(sublime_plugin.TextCommand):
def run(self, edit):
self.other_open_files = []
for v in self.views:
if v.id() != self.view.id():
if not v.file_name():
continue
self.other_open_files.append(v.file_name())
sublime.active_window().show_quick_panel(self.other_open_files, self.on_done, 1)
def on_done(self, index):
if index == -1:
return
from .salesforce.lib import diff
diff.diff_files(self.view.file_name(), self.other_open_files[index])
def is_enabled(self):
self.views = sublime.active_window().views()
return len(self.views) > 1
def is_visible(self):
view = sublime.active_window().active_view()
return view.file_name() is not None
class ShowMyPanel(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ShowMyPanel, self).__init__(*args, **kwargs)
def run(self, panel):
Printer.get(panel).show_panel()
class ToggleMetadataObjects(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ToggleMetadataObjects, self).__init__(*args, **kwargs)
def run(self, callback_options={}):
self.settings = context.get_settings()
self.callback_options = callback_options
described_metadata = util.get_described_metadata(self.settings)
if not described_metadata:
return self.window.run_command("describe_metadata", {
"callback_options": {
"callback_command": "toggle_metadata_objects"
}
})
self.metadata_objects = described_metadata["metadataObjects"]
smo = self.settings["subscribed_metadata_objects"]
# Key pair between item and metdataObjects
self.item_property = {}
# Add all metadata objects to list
has_subscribed = False
subscribed_items = []
unsubscripted_items = []
for mo in self.metadata_objects:
if mo["xmlName"] in smo:
item = "%s[√] %s" % (" " * 4, mo["xmlName"])
subscribed_items.append(item)
has_subscribed = True
else:
item = "%s[x] %s" % (" " * 4, mo["xmlName"])
unsubscripted_items.append(item)
self.item_property[item] = mo["xmlName"]
# Add item `Select All` to list
item_all = "[%s] All" % ("√" if has_subscribed else "x")
self.items = [item_all]
self.item_property[item_all] = [m["xmlName"] for m in self.metadata_objects]
# Add subscribed ones and unsubscribed ones to list
self.items.extend(sorted(subscribed_items))
self.items.extend(sorted(unsubscripted_items))
self.window.show_quick_panel(self.items, self.on_done,
sublime.MONOSPACE_FONT)
def on_done(self, index):
if index == -1:
if "callback_command" in self.callback_options:
self.window.run_command(self.callback_options["callback_command"])
return
# Get chosen type
chosen_item = self.items[index]
chosen_metadata_objects = self.item_property[chosen_item]
# Get already subscribed metadata objects
s = sublime.load_settings(context.TOOLING_API_SETTINGS)
projects = s.get("projects")
default_project = projects[self.settings["default_project_name"]]
if "subscribed_metadata_objects" in default_project:
subscribed_metadata_objects = default_project["subscribed_metadata_objects"]
else:
subscribed_metadata_objects = []
# Assign new subscribed metadata objects to subscribed list
if isinstance(chosen_metadata_objects, list):
# If already subscribed all, and we click choose all item,
# all subscribed ones will be unsubscripted
if len(subscribed_metadata_objects) == len(self.metadata_objects):
subscribed_metadata_objects = []
else:
subscribed_metadata_objects = chosen_metadata_objects
elif isinstance(chosen_metadata_objects, str):
if chosen_metadata_objects in subscribed_metadata_objects:
subscribed_metadata_objects.remove(chosen_metadata_objects)
else:
subscribed_metadata_objects.append(chosen_metadata_objects)
default_project["subscribed_metadata_objects"] = subscribed_metadata_objects
projects[self.settings["default_project_name"]] = default_project
# Save the updated settings
s.set("projects", projects)
sublime.save_settings(context.TOOLING_API_SETTINGS)
sublime.set_timeout(lambda: sublime.active_window().run_command("toggle_metadata_objects", {
"callback_options": self.callback_options
}), 10)
class ReloadSobjectCacheCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ReloadSobjectCacheCommand, self).__init__(*args, **kwargs)
def run(self):
message = "Are you sure you really want to update sObject cache?"
if not sublime.ok_cancel_dialog(message, "Confirm Reload?"): return
processor.handle_reload_sobjects_completions()
class ReloadSymbolTableCacheCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ReloadSymbolTableCacheCommand, self).__init__(*args, **kwargs)
def run(self):
message = "Are you sure you really want to reload symbol table cache?"
if not sublime.ok_cancel_dialog(message, "Confirm Reload"):
return
processor.handle_reload_symbol_tables()
class ClearSessionCacheCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ClearSessionCacheCommand, self).__init__(*args, **kwargs)
def run(self):
message = "Are you sure you really want to clear session?"
if not sublime.ok_cancel_dialog(message, "Confirm Clear?"): return
settings = context.get_settings()
session_path = settings["workspace"] + "/.config/session.json"
try:
os.remove(session_path)
sublime.status_message("Session cache is cleared")
except:
sublime.status_message("Session cache clear failed")
class ClearCacheCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ClearCacheCommand, self).__init__(*args, **kwargs)
def run(self, cache_name):
self.cache_name = cache_name
self.cache_settings = self.cache_name + ".sublime-settings"
self.caches = util.get_sobject_caches(self.cache_settings)
if not self.caches:
Printer.get('error').write("No cache already")
return
self.window.show_quick_panel(self.caches, self.on_done)
def on_done(self, index):
if index == -1: return
message = "Are you sure you really want to clear this cache?"
if not sublime.ok_cancel_dialog(message, "Confirm Clear"): return
util.clear_cache(self.caches[index][1], self.cache_settings)
sublime.set_timeout(lambda: sublime.active_window().run_command("clear_cache", {
"cache_name": self.cache_name
}), 10)
class Convert15Id218Id(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(Convert15Id218Id, self).__init__(*args, **kwargs)
def run(self):
self.window.show_input_panel("Input 15 Id: ",
"", self.on_input, None, None)
def on_input(self, input):
c18Id = util.convert_15_to_18(input)
Printer.get('log').write("Converted 18 Digit Id: " + c18Id);
class DecodeUrl(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(DecodeUrl, self).__init__(*args, **kwargs)
def run(self):
self.window.show_input_panel("Input your URL to be decoded: ",
"", self.on_input, None, None)
def on_input(self, input):
decodedUrl = urllib.request.unquote(input)
Printer.get('log').write("Decoded URL: " + decodedUrl);
class EncodeUrl(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(EncodeUrl, self).__init__(*args, **kwargs)
def run(self):
self.window.show_input_panel("Input your URL to be encoded: ",
"", self.on_input, None, None)
def on_input(self, input):
encodedUrl = urllib.request.quote(input)
Printer.get('log').write("Encoded URL: " + encodedUrl);
class GenerateSoqlCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(GenerateSoqlCommand, self).__init__(*args, **kwargs)
def run(self):
sobjects_describe = util.populate_sobjects_describe()
self.sobjects = sorted(sobjects_describe.keys())
self.window.show_quick_panel(self.sobjects, self.on_done)
def on_done(self, index):
if index == -1: return
self.sobject = self.sobjects[index]
self.filters = ["all", "updateable", "createable", "custom"]
self.display_filters = [a.capitalize() for a in self.filters]
sublime.set_timeout(lambda: self.window.show_quick_panel(self.display_filters, self.on_choose_action), 10)
def on_choose_action(self, index):
if index == -1: return
processor.handle_generate_sobject_soql(self.sobject, self.filters[index])
class ExportQueryToCsv(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ExportQueryToCsv, self).__init__(*args, **kwargs)
def run(self, tooling=False):
self.tooling = tooling
sublime.active_window().show_input_panel('Input Your %s SOQL:' %
('Tooling' if tooling else ''), "", self.on_input_soql, None, None)
def on_input_soql(self, soql):
self.soql = soql.strip()
# Check whether the soql is valid and not parent-to-child query
match = re.match("[\\n\\s]*SELECT\\s+[*\\w\\n,.:_\\s()]+?\\s+FROM\\s+[1-9_a-zA-Z]+",
self.soql, re.IGNORECASE)
if not match:
Printer.get("error").write("Your input SOQL is not valid")
if sublime.ok_cancel_dialog("Want to try again?"):
self.window.show_input_panel('Input Your SOQL:',
"", self.on_input_soql, None, None)
return
# This feature does not support parent to child query
matchs = re.findall('SELECT\\s+', match.group(0), re.IGNORECASE)
if len(matchs) > 1:
Printer.get("error").write("This feature does not support parent-to-child query")
if sublime.ok_cancel_dialog("Want to try again?"):
self.window.show_input_panel('Input Your SOQL:',
"", self.on_input_soql, None, None)
return
# Parse the sObject Name for CSV name
matchstr = match.group(0)
self.sobject = matchstr[matchstr.rfind(" ") + 1:]
sublime.active_window().show_input_panel('Input CSV Name:',
self.sobject, self.on_input_name, None, None)
def on_input_name(self, name):
if not name: return
processor.handle_export_query_to_csv(self.tooling, self.soql, name)
class ExportDataTemplateCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(ExportDataTemplateCommand, self).__init__(*args, **kwargs)
def run(self, vertical=True):
self.vertical = vertical
self.sobject_recordtypes_attr = processor.populate_sobject_recordtypes()
if not self.sobject_recordtypes_attr: return # Network Issue Cause
self.sobject_recordtypes = sorted(list(self.sobject_recordtypes_attr.keys()))
self.window.show_quick_panel(self.sobject_recordtypes, self.on_choose_recordtype)
def on_choose_recordtype(self, index):
if index == -1: return
# Get chosen item, sobject name and recordtype id
sobject_recordtype = self.sobject_recordtypes[index]
sobject = sobject_recordtype.split(",")[0].strip()
recordtype_name = sobject_recordtype.split(",")[1].strip()
recordtype_id = self.sobject_recordtypes_attr[sobject_recordtype]
# handle this describe request
processor.handle_export_data_template_thread(sobject,
recordtype_name, recordtype_id, self.vertical)
def is_enabled(self):
return util.check_action_enabled()
class ExecuteRestTest(sublime_plugin.TextCommand):
def run(self, edit):
self.items = ["Get", "Post", "Put", "Patch", "Delete", "Tooling Query",
"Query", "Query All", "Search", "Quick Search",
"Head", "Retrieve Body"]
self.view.show_popup_menu(self.items, self.on_choose_action),
def on_choose_action(self, index):
if index == -1: return
self.chosen_action = self.items[index]
if self.chosen_action in ["Post", "Put", "Patch"]:
self.view.window().show_input_panel("Input JSON Body: ", "", self.on_input, None, None)
else:
processor.handle_execute_rest_test(self.chosen_action, self.sel)
def on_input(self, data):
try:
data = json.loads(data) if data else None
except ValueError as ve:
Printer.get('error').write(str(ve))
if not sublime.ok_cancel_dialog("Do you want to try again?", "Yes?"): return
self.view.window().show_input_panel("Input JSON Body: ",
"", self.on_input, None, None)
return
processor.handle_execute_rest_test(self.chosen_action, self.sel, data)
def is_enabled(self):
self.sel = self.view.substr(self.view.sel()[0])
if not self.sel: return False
return True
class GotoComponentCommand(sublime_plugin.TextCommand):
"""
Move the cursor to the class name, press shift key and double click left mouse,
the class file will be open, you can custom the bind key in mousemap path
"""
def run(self, edit, is_background=False, allowed_folders=None):
sel = self.view.sel()[0]
sel_text = self.view.substr(self.view.word(sel.begin()))
settings = context.get_settings()
for ct in settings["subscribed_metadata_objects"]:
if "suffix" not in settings[ct]:
continue
suffix = settings[ct]["suffix"]
folder = settings[ct]["directoryName"]
target_file = os.path.join(settings["workspace"] + \
"/src/%s/%s.%s" % (folder, sel_text, suffix)
)
if os.path.isfile(target_file):
if allowed_folders:
if folder in allowed_folders:
self.view.window().open_file(target_file)
else:
self.view.window().open_file(target_file)
else:
sublime.status_message("You may forget to download the code")
if is_background: self.view.window().focus_view(self.view)
class SetCheckPointCommand(sublime_plugin.TextCommand):
def run(self, edit, mark):
sel = [s for s in self.view.sel()]
self.view.add_regions(mark, sel, "invalid", "dot",
sublime.DRAW_SOLID_UNDERLINE | sublime.DRAW_EMPTY_AS_OVERWRITE)
class RemoveCheckPointCommand(sublime_plugin.TextCommand):
def run(self, edit, mark):
self.view.erase_regions(mark)
class ViewCodeCoverageCommand(sublime_plugin.TextCommand):
def run(self, edit):
processor.handle_fetch_code_coverage(self.attributes["name"], self.body)
def is_enabled(self):
# Must Be File
if not self.view.file_name():
return False
self.file_name = self.view.file_name()
# Must be valid component
if not util.check_enabled(self.file_name):
return False
# Must be class or trigger
self.attributes = util.get_file_attributes(self.file_name)
if not self.attributes["extension"]:
return False
if self.attributes["metadata_folder"] not in ["classes", "triggers"]:
return False
# Can't be Test Class
with open(self.file_name, encoding="utf-8") as fp:
self.body = fp.read()
if "@istest" in self.body.lower():
return False
return True
def is_visible(self):
return self.is_enabled()
class ViewSelectedCodeCoverageCommand(sublime_plugin.TextCommand):
def run(self, edit):
# Keep all open views
openViewIds = [v.id() for v in sublime.active_window().views()]
# Open the related code file
self.view.run_command("goto_component", {
"is_background": False,
"allowed_folders": ["classes", "triggers"]
})
# 1. Open the view of related code file
# 2. Run command `view_code_coverage` to open coverage view
# 3. Close the view of related code file
# 4. Focus on the coverage view
view = sublime.active_window().active_view()
view.run_command("view_code_coverage")
coverage_view = sublime.active_window().active_view()
# If there is no available code file
if coverage_view.id() == view.id():
return
if view.id() not in openViewIds:
sublime.active_window().focus_view(view)
sublime.active_window().run_command("close")
# Move focus to the coverage view
sublime.active_window().focus_view(coverage_view)
class NewViewCommand(sublime_plugin.TextCommand):
"""
Create a new view with specified input
@input: user specified input
Usage:
sublime.active_window().run_command("new_view", {
"name": "ViewName",
"input": "Example"
})
"""
def run(self, edit, point=0, name="", input=""):
view = sublime.active_window().active_view()
view.set_scratch(True)
view.set_name(name)
view.insert(edit, point, input)
class NewDynamicViewCommand(sublime_plugin.TextCommand):
"""
Create a new view with specified input
@input: user specified input
Usage:
sublime.active_window().run_command("new_dynamic_view", {
"view_id": "view_id",
"point": 0,
"input": "Example"
})
"""
def run(self, edit, view_id=None, view_name="", input="", point=0, erase_all=False):
# Get the view which name match the name paramter
view = sublime.active_window().active_view()
if view_id and not view.id() == view_id:
for v in sublime.active_window().views():
if v.id() == view_id:
view = v
view.set_scratch(True)
view.set_name(view_name)
if erase_all: view.erase(edit, sublime.Region(0, view.size()))
view.insert(edit, point, input)
class RefreshFolder(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(RefreshFolder, self).__init__(*args, **kwargs)
def run(self, dirs):
message = "Are you sure you really want to refresh these folders"
if sublime.ok_cancel_dialog(message, "Refresh Folders"):
processor.handle_refresh_folder(self.types)
def is_visible(self, dirs):
if not dirs: return False
self.types = util.build_folder_types(dirs)
if not self.types: return False
return True
class RetrieveMetadataCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(RetrieveMetadataCommand, self).__init__(*args, **kwargs)
def run(self, retrieve_all=True):
message = "Are your sure you really want to continue?"
if not sublime.ok_cancel_dialog(message, "Retrieve Metadata"): return
settings = context.get_settings()
types = {}
if not retrieve_all:
types = {
"CustomObject": ["*"],
"Workflow": ["*"]
}
else:
for m in settings["all_metadata_objects"]:
types[m] = ["*"]
processor.handle_refresh_folder(types, not retrieve_all)
class RenameMetadata(sublime_plugin.TextCommand):
def run(self, edit):
self.view.window().show_input_panel("Input New Name",
self.filename, self.on_input, None, None)
def on_input(self, new_name):
if not new_name or not re.match("\w+[a-zA-Z0-9]+", new_name):
Printer.get('error').write("Input name is not valid")
return
processor.handle_rename_metadata(self.file_name, self.xml_name, self.filename, new_name)
def is_enabled(self):
if not self.view or not self.view.file_name(): return False
self.settings = context.get_settings()
self.file_name = self.view.file_name()
base, filename = os.path.split(self.file_name)
base, folder = os.path.split(base)
if folder not in self.settings["all_metadata_folders"]: return False
if not util.check_enabled(self.view.file_name(), check_cache=False):
return False
self.filename = filename.split(".")[0]
self.xml_name = self.settings[folder]["xmlName"]
return True
class RetrieveFileFromServer(sublime_plugin.TextCommand):
"""
Retrieve Single File From Salesforce via Metadata API
"""
def run(self, edit, switch=True):
files = [self.view.file_name()]
sublime.active_window().run_command("retrieve_files_from_server", {
"files": files,
"switch": switch
})
def is_enabled(self):
if not self.view or not self.view.file_name(): return False
self.settings = context.get_settings()
attributes = util.get_file_attributes(self.view.file_name())
metadata_folder = attributes["metadata_folder"]
if metadata_folder not in self.settings["all_metadata_folders"]: return False
if not util.check_enabled(self.view.file_name(), check_cache=False):
return False
return True
def is_visible(self):
return self.is_enabled()
class RetrieveFilesFromServer(sublime_plugin.WindowCommand):
"""
Retrieve List of files from Salesforce via Metadata API
"""
def __init__(self, *args, **kwargs):
super(RetrieveFilesFromServer, self).__init__(*args, **kwargs)
def run(self, files, switch=True, source_org=None, confirmed=False, extract_to=None):
# Prevent duplicate confirmation
if not confirmed:
_message = "Confirm retrieving %s from server?" % (
"these files" if len(files) > 1 else "this file"
)
if not sublime.ok_cancel_dialog(_message, "Confirm?"):
return
settings = context.get_settings()
if not extract_to:
extract_to = settings["workspace"]
if switch:
return self.window.run_command("switch_project", {
"callback_options": {
"callback_command": "retrieve_files_from_server",
"args": {
"files": files,
"switch": False,
"source_org": settings["default_project_name"],
"confirmed": True,
"extract_to": extract_to
}
}
})
types = {}
for _file in files:
attributes = util.get_file_attributes(_file)
name = attributes["name"]
metadata_folder = attributes["metadata_folder"]
metadata_object_attr = settings[metadata_folder]
metadata_object = metadata_object_attr["xmlName"]
# If file is in folder, we need to add folder/
if metadata_object_attr["inFolder"] == "true":
name = "%s/%s" % (attributes["folder"], attributes["name"])
# If file is AuraDefinitionBundle, we need to add folder
if metadata_folder in ["aura", "lwc"]:
name = "%s" % attributes["folder"]
if metadata_object in types:
types[metadata_object].append(name)
else:
types[metadata_object] = [name]
processor.handle_retrieve_package(types, extract_to,
source_org=source_org, ignore_package_xml=True)
def is_visible(self, files):
if not files:
return False
settings = context.get_settings()
for _file in files:
if not os.path.isfile(_file):
continue # Ignore folder
metadata_folder = util.get_metadata_folder(_file)
if metadata_folder not in settings["all_metadata_folders"]: return False
if not util.check_enabled(_file, check_cache=False):
return False
return True
class CancelDeployment(sublime_plugin.TextCommand):
def run(self, edit):
processor.handle_cancel_deployment_thread(self.sel_text)
def is_enabled(self):
if len(self.view.sel()) == 0: