forked from xjsender/SublimeApex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SublimeApex.py
652 lines (499 loc) · 21.5 KB
/
SublimeApex.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
import sublime
import sublime_plugin
import webbrowser
import urllib
import re
import os
import sys
import shutil
import zipfile
try:
# Python 3.x
from . import requests
from . import processor
from . import context
from .salesforce import util, message
from .salesforce import bulkapi
except:
# Python 2.x
import requests
import processor
import context
from salesforce import util, message, bulkapi
class switchprojectCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(switchprojectCommand, self).__init__(*args, **kwargs)
def run(self):
global projects
toolingapi_settings = context.get_toolingapi_settings()
projects = toolingapi_settings["projects"]
projects = ["(" + str(projects[p]["default"]) + ") " + p for p in projects]
projects = sorted(projects, reverse=True)
self.window.show_quick_panel(projects, self.on_done)
def on_done(self, index):
if index == -1: return
# Change the chosen project as default
# Split with ") " and get the second project name
default_project = projects[index].split(") ")[1]
context.switch_project(default_project)
class newviewCommand(sublime_plugin.TextCommand):
"""
Create a new view with specified input
@input: user specified input
Usage:
sublime.active_window().run_command("newview", {
"name": "ViewName",
"input": "Example"
})
"""
def run(self, edit, name="", input=""):
view = sublime.active_window().active_view()
view.set_scratch(True)
view.set_name(name)
view.insert(edit, 0, input)
class refreshfolderCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(refreshfolderCommand, self).__init__(*args, **kwargs)
def run(self):
global component_types
toolingapi_settings = context.get_toolingapi_settings()
component_types = toolingapi_settings["component_types"]
self.window.show_quick_panel(component_types, self.on_done)
def on_done(self, index):
if index == -1: return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
processor.handle_refresh_folder(component_types[index])
class retrievemetadataCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(retrievemetadataCommand, self).__init__(*args, **kwargs)
def run(self):
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
processor.handle_retrieve_all_thread()
class exportvalidationrulesCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(exportvalidationrulesCommand, self).__init__(*args, **kwargs)
def run(self):
toolingapi_settings = context.get_toolingapi_settings()
workflow_path = toolingapi_settings["workspace"] + "/metadata/unpackaged/objects"
if not os.path.exists(workflow_path):
sublime.error_message(message.SOBJECTS_PATH_CHECK)
return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
processor.handle_parse_validation_rule()
class exportworkflowCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(exportworkflowCommand, self).__init__(*args, **kwargs)
def run(self):
toolingapi_settings = context.get_toolingapi_settings()
workflow_path = toolingapi_settings["workspace"] + "/metadata/unpackaged/workflows"
if not os.path.exists(workflow_path):
sublime.error_message(message.WORKFLOW_PATH_CHECK)
return
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
processor.handle_parse_workflow()
class describecustomfieldCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(describecustomfieldCommand, self).__init__(*args, **kwargs)
def run(self):
global sobjects
sobjects = processor.populate_sobjects()
sobjects = sorted(sobjects)
self.window.show_quick_panel(sobjects, self.on_done)
def on_done(self, index):
if index == -1: return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
processor.handle_describe_customfield(sobjects[index])
class describeglobalCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(describeglobalCommand, self).__init__(*args, **kwargs)
def run(self):
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
processor.handle_describe_global()
class describelayoutCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(describelayoutCommand, self).__init__(*args, **kwargs)
def run(self):
global sobject_recordtypes_attr
global sobject_recordtypes
sobject_recordtypes_attr = processor.populate_sobject_recordtypes()
sobject_recordtypes = sorted(list(sobject_recordtypes_attr.keys()))
self.window.show_quick_panel(sobject_recordtypes, self.on_done)
def on_done(self, index):
if index == -1: return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
# Get chosen item, sobject name and recordtype id
sobject_recordtype = sobject_recordtypes[index]
sobject = sobject_recordtype.split(",")[0].strip()
recordtype_name = sobject_recordtype.split(",")[1].strip()
recordtype_id = sobject_recordtypes_attr[sobject_recordtype]
# handle this describe requst
print (sobject, recordtype_id)
processor.handle_describe_layout(sobject, recordtype_name, recordtype_id)
class backupsobjectsCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(backupsobjectsCommand, self).__init__(*args, **kwargs)
def run(self):
self.window.show_input_panel("Sobjects(* means all, or sobjects seprated with semi-colon)",
"*", self.on_input, None, None)
def on_input(self, input):
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
# Display the fields in a new view
input = input.replace(" ", "")
if input == "*":
processor.handle_backup_all_sobjects(5)
else:
sobjects = input.split(";")
bulkapi.handle_bulkapi_query(sobjects)
class describesobjectCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(describesobjectCommand, self).__init__(*args, **kwargs)
def run(self):
global sobjects
sobjects = processor.populate_sobjects()
sobjects = sorted(sobjects)
self.window.show_quick_panel(sobjects, self.on_done)
def on_done(self, index):
if index == -1: return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
processor.handle_retrieve_fields(sobjects[index])
class exportworkbookCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(exportworkbookCommand, self).__init__(*args, **kwargs)
def run(self):
self.window.show_input_panel("Sobjects(* means all, or sobjects seprated with semi-colon)",
"*", self.on_input, None, None)
def on_input(self, input):
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
# Display the fields in a new view
input = input.replace(" ", "")
if input == "*":
processor.handle_generate_all_workbooks(5)
else:
sobjects = input.split(";")
processor.handle_generate_specified_workbooks(sobjects)
class viewcommponentinsfdcCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(viewcommponentinsfdcCommand, self).__init__(*args, **kwargs)
def run(self):
global all_components
global all_components_name
all_components = processor.populate_components()
if len(all_components) == 0:
sublime.message_dialog("Please click 'New Project' Firstly.")
return
all_components_name = sorted(list(all_components.keys()))
print (all_components_name)
self.window.show_quick_panel(all_components_name, self.on_done)
def on_done(self, index):
if index == -1: return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
class_id = all_components[all_components_name[index]]
startURL = "/" + class_id
self.window.run_command("loginintosfdc", {"startURL": startURL})
class runonetestCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(runonetestCommand, self).__init__(*args, **kwargs)
def run(self):
global classes_attr
global class_names
classes_attr = processor.populate_classes()
classes = classes_attr.keys()
classes = [c for c in classes if "is_test" in classes_attr[c] and classes_attr[c]["is_test"]]
class_names = sorted(list(classes))
self.window.show_quick_panel(class_names, self.on_done)
def on_done(self, index):
if index == -1: return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
class_id = classes_attr[class_names[index]]["id"]
processor.handle_run_test(class_id)
class runtestCommand(sublime_plugin.TextCommand):
def run(self, view):
# Open Console
self.view.window().run_command("show_panel",
{"panel": "console", "toggle": False})
# Get component_attribute by file_name
component_attribute = get_component_attribute(self.view.file_name())[0]
# Process run test
processor.handle_run_test(component_attribute["id"])
def is_enabled(self):
# Get current file name and Read file content
file_name = self.view.file_name()
if file_name == None: return False
try:
# Python 3.x
body = open(file_name, encoding="utf-8").read()
except:
# Python 2.x
body = open(file_name).read().encode()
if ".cls" not in file_name or "@isTest" not in body:
return False
return True
class executesoqlCommand(sublime_plugin.TextCommand):
def run(self, view):
# Open Console
self.view.window().run_command("show_panel",
{"panel": "console", "toggle": False})
# Handle
processor.handle_execute_query(self.selection)
def is_enabled(self):
# Selection must start SELECT,
# otherwise you can't see this command
self.selection = self.view.substr(self.view.sel()[0]).encode('utf-8')
if not self.selection or not self.selection.upper().startswith(b"SELECT"):
return False
return True
class executeanonymousCommand(sublime_plugin.TextCommand):
def run(self, view):
# Open Console
self.view.window().run_command("show_panel",
{"panel": "console", "toggle": False})
# Handle
processor.handle_execute_anonymous(self.selection)
def is_enabled(self):
# You must select some snippets, otherwise
# you can't see this command
self.selection = self.view.substr(self.view.sel()[0])
if not util.is_python3x():
self.selection = self.view.substr(self.view.sel()[0]).encode('utf-8')
if not self.selection:
return False
return True
class viewidinsfdcwebCommand(sublime_plugin.TextCommand):
def run(self, view):
startURL = "/" + self.record_id
if self.record_id.startswith("012"):
startURL = "/setup/ui/recordtypefields.jsp?id=" + self.record_id
if self.record_id.startswith("07L"):
startURL = "/p/setup/layout/ApexDebugLogDetailEdit/d?apex_log_id=" + self.record_id
self.view.window().run_command("loginintosfdc", {"startURL": startURL})
def is_enabled(self):
# Choose the valid Id, you will see this command
if util.is_python3x():
self.record_id = self.view.substr(self.view.sel()[0])
else:
self.record_id = self.view.substr(self.view.sel()[0]).encode("utf-8")
if len(self.record_id) != 15 and len(self.record_id) != 18:
return False
if not re.compile(r'^[a-zA-Z0-9]*$').match(self.record_id):
return False
return True
class showinsfdcwebCommand(sublime_plugin.TextCommand):
def run(self, view):
# Get file_name and component_attribute
component_attribute = get_component_attribute(self.view.file_name())[0]
# Open this component in salesforce web
startURL = "/" + component_attribute["id"]
self.view.window().run_command("loginintosfdc", {"startURL": startURL})
def is_enabled(self):
return check_visible(self.view.file_name())
class loginintosfdcCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(loginintosfdcCommand, self).__init__(*args, **kwargs)
def run(self, startURL=""):
# Get toolingapi settings
toolingapi_settings = context.get_toolingapi_settings()
# Combine Login URL
show_params = {
"un": toolingapi_settings["username"],
"pw": toolingapi_settings["password"],
"startURL": startURL
}
if util.is_python3x():
show_params = urllib.parse.urlencode(show_params)
else:
show_params = urllib.urlencode(show_params)
show_url = toolingapi_settings["login_url"] + '?%s' % show_params
# Open this component in salesforce web
webbrowser.open_new_tab(show_url)
class aboutCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(aboutCommand, self).__init__(*args, **kwargs)
def run(self):
webbrowser.open_new_tab("https://github.com/xjsender/SublimeApex")
class deleteCommand(sublime_plugin.TextCommand):
def run(self, view):
# Get file_name and component_attribute
file_name = self.view.file_name()
component_attribute = get_component_attribute(file_name)[0]
# Confirm Delete Action
confirm = sublime.ok_cancel_dialog(message.DELETE_CONFIRM_MESSAGE)
if confirm == False:
return
# Open Console
self.view.window().run_command("show_panel",
{"panel": "console", "toggle": False})
# Handle Delete
processor.handle_delete_component(component_attribute["url"], file_name)
def is_enabled(self):
return check_visible(self.view.file_name())
class createCommand(sublime_plugin.WindowCommand):
"""
user input, for example,
1. TestTrigger.trigger, sobject_name
2. TestClass.cls
3. TestPage.page
4. TestComponent.component
"""
def __init__(self, *args, **kwargs):
super(createCommand, self).__init__(*args, **kwargs)
def run(self):
self.window.show_input_panel("component_name.extension, Sobject_Name:",
"", self.on_input, None, None)
def on_input(self, input):
# Valid user input
if "." not in input:
sublime.error_message(message.INVALID_NEW_COMPONENT_FORMAT)
return
# Get toolingapi settings
toolingapi_settings = context.get_toolingapi_settings()
# Create component to local according to user input
is_success, sobject_name, file_name = context.make_component(input)
if is_success == False:
sublime.error_message(message.INVALID_NEW_COMPONENT_FORMAT)
return
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
self.window.open_file(file_name)
# Before you save it to server, save it to local
self.view = self.window.active_view()
if self.view.is_dirty():
self.view.run_command("save")
# Get Current File Name
file_name = self.view.file_name()
print(file_name)
# Read file content
body = open(file_name).read()
# Get component type and component_name (Class Name, Trigger Name, etc.)
component_name = util.get_component_name(file_name)
component_type = util.get_component_type(file_name)
# There has bug on creating ApexTrigger, but fixed on 2013 May 6 at 21:
# Create Trigger is different from others, we can't use tooling/sobjects/ApexTrigger,
# We should use sobjects/ApexTrigger
# http://salesforce.stackexchange.com/questions/9603/how-do-i-use-the-tooling-api-to-create-a-new-apex-trigger
# If component type is not in range, just show error message
if component_type not in toolingapi_settings["component_types"]:
sublime.error_message(message.INVALID_COMPONENT)
return
# Get Component body Metadata Attribute in SFDC
component_body = toolingapi_settings[component_type]["body"]
# Compose data
data = {
"name": component_name,
component_body: body,
}
if component_type == "ApexClass":
data["IsValid"] = True
elif component_type == "ApexTrigger":
data["TableEnumOrId"] = sobject_name
elif component_type in ["ApexPage", "ApexComponent"]:
data["MasterLabel"] = component_name
processor.handle_create_component(data, component_name, component_type)
class deployCommand(sublime_plugin.TextCommand):
def run(self, view):
# Automatically save current file if dirty
if self.view.is_dirty():
self.view.run_command("save")
# Get file_name and component_attribute
file_name = self.view.file_name()
component_attribute, component_name = get_component_attribute(file_name)
# Read file content
try:
body = open(file_name, encoding="utf-8").read()
except:
body = open(file_name).read()
# Open Console
self.view.window().run_command("show_panel",
{"panel": "console", "toggle": False})
# Handle Save Current Component
processor.handle_save_component(component_name, component_attribute, body)
def is_enabled(self):
return check_visible(self.view.file_name())
class refreshallCommand(sublime_plugin.WindowCommand):
def __init__(self, *args, **kwargs):
super(refreshallCommand, self).__init__(*args, **kwargs)
def run(self):
# Create Project Directory
context.make_dir()
# Get toolingapi_settings
toolingapi_settings = context.get_toolingapi_settings()
context.add_project_to_workspace(toolingapi_settings["workspace"])
# Open Console
self.window.run_command("show_panel",
{"panel": "console", "toggle": False})
# Handle Refresh All
processor.handle_refresh_components(toolingapi_settings)
class refreshcurrentCommand(sublime_plugin.TextCommand):
def run(self, view):
# Get file_name and component_attribute
file_name = self.view.file_name()
component_attribute = get_component_attribute(file_name)[0]
# Open Console
self.view.window().run_command("show_panel",
{"panel": "console", "toggle": False})
# Handle Refresh Current Component
processor.handle_refresh_component(component_attribute, file_name)
def is_enabled(self):
return check_visible(self.view.file_name())
def get_component_attribute(file_name):
# Get toolingapi settings
toolingapi_settings = context.get_toolingapi_settings()
# Get component type
component_name = util.get_component_name(file_name)
component_type = util.get_component_type(file_name)
# If component type is not in range, just show error message
if component_type not in toolingapi_settings["component_types"]:
return
# Get component_url and component_id
username = toolingapi_settings["username"]
component_attribute = util.get_component_attribute(username, file_name)
return (component_attribute, component_name)
def check_visible(file_name):
"""
Check whether file is ApexTrigger, ApexComponent, ApexPage or ApexClass
Parameters:
file_name: current file name
Return:
Bool
"""
if file_name == None:
return False
# Get toolingapi settings
toolingapi_settings = context.get_toolingapi_settings()
# Get component_type
component_type = util.get_component_type(file_name)
# If component type is not in range, just show error message
if component_type not in toolingapi_settings["component_types"]:
return False
# Get component_url and component_id
username = toolingapi_settings["username"]
try:
component_attribute = util.get_component_attribute(username, file_name)
except KeyError as err:
return False
if component_attribute == None:
return False
return True