forked from ericmartel/Sublime-Text-2-Perforce-Plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Perforce.py
1053 lines (819 loc) · 37.8 KB
/
Perforce.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
# Written by Eric Martel ([email protected] / www.ericmartel.com)
# Available commands are listed in Default.sublime-commands
# changelog
# Eric Martel - first implementation of add / checkout
# Tomek Wytrebowicz & Eric Martel - handling of forward slashes in clientspec folder
# Rocco De Angelis & Eric Martel - first implementation of revert
# Eric Martel - first implementation of diff
# Eric Martel - first implementation of Graphical Diff from Depot
# Eric Martel - first pass on changelist manipulation
# Eric Martel - first implementation for rename / delete & added on_modified as a condition to checkout a file
# Jan van Valburg - bug fix for better support of client workspaces
# Eric Martel - better handling of clientspecs
# Rocco De Angelis - parameterized graphical diff
# Eric Martel & adecold - only list pending changelists belonging to the current user
# Eric Martel - source bash_profile when calling p4 on Mac OSX
# Eric Martel - first implementation of submit
# Eric Martel - Better handling of P4CONFIG files
# Andrew Butt & Eric Martel - threading of the diff task and selector for the graphical diff application
# Eric Martel - Added the possibility to Submit the default changelist
import sublime
import sublime_plugin
import os
import stat
import subprocess
import tempfile
import threading
import json
import sys
try:
from Queue import Queue, Empty
except ImportError:
from queue import Queue, Empty # python 3.x
# Plugin Settings are located in 'perforce.sublime-settings' make a copy in the User folder to keep changes
# global variable used when calling p4 - it stores the path of the file in the current view, used to determine with P4CONFIG to use
# whenever a view is selected, the variable gets updated
global_folder = ''
class PerforceP4CONFIGHandler(sublime_plugin.EventListener):
def on_activated(self, view):
if view.file_name():
global global_folder
global_folder, filename = os.path.split(view.file_name())
# Executed at startup to store the path of the plugin... necessary to open files relative to the plugin
perforceplugin_dir = os.getcwd()
# Utility functions
def ConstructCommand(in_command):
command = ''
if(sublime.platform() == "osx"):
command = 'source ~/.bash_profile && '
# Revert change until threading is fixed
# command = getPerforceConfigFromPreferences(command)
command += in_command
return command
def getPerforceConfigFromPreferences(command):
perforce_settings = sublime.load_settings('Perforce.sublime-settings')
# check to see if the sublime preferences include the given p4 config
# if it does, then add it to the command in the form "var=value command"
# so that they get inserted into the environment the command runs in
def addP4Var(command, var):
p4var = perforce_settings.get(var)
if p4var:
if sublime.platform() == "windows":
return command + "SET " + var + "=" + p4var + " && "
return command + var + "=" + p4var + " "
return command
command = addP4Var(command, "P4PORT")
command = addP4Var(command, "P4CLIENT")
command = addP4Var(command, "P4USER")
command = addP4Var(command, "P4PASSWD")
return command
def GetUserFromClientspec():
command = ConstructCommand('p4 info')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
result = result.decode('utf-8')
if(err):
WarnUser("usererr " + err.strip())
return -1
# locate the line containing "User name: " and extract the following name
startindex = result.find("User name: ")
if(startindex == -1):
WarnUser("Unexpected output from 'p4 info'.")
return -1
startindex += 11 # advance after 'User name: '
endindex = result.find("\n", startindex)
if(endindex == -1):
WarnUser("Unexpected output from 'p4 info'.")
return -1
return result[startindex:endindex].strip();
def GetClientRoot(in_dir):
# check if the file is in the depot
command = ConstructCommand('p4 info')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
result = result.decode('utf-8')
if(err):
WarnUser(err.strip())
return -1
# locate the line containing "Client root: " and extract the following path
startindex = result.find("Client root: ")
if(startindex == -1):
# sometimes the clientspec is not displayed
sublime.error_message("Perforce Plugin: p4 info didn't supply a valid clientspec, launching p4 client");
command = ConstructCommand('p4 client')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
return -1
startindex += 13 # advance after 'Client root: '
endindex = result.find("\n", startindex)
if(endindex == -1):
WarnUser("Unexpected output from 'p4 info'.")
return -1
# convert all paths to "os.sep" slashes
convertedclientroot = result[startindex:endindex].strip().replace('\\', os.sep).replace('/', os.sep)
return convertedclientroot
def IsFolderUnderClientRoot(in_folder):
# check if the file is in the depot
clientroot = GetClientRoot(in_folder)
if(clientroot == -1):
return 0
clientroot = clientroot.lower()
if(clientroot == "null"):
return 1
# convert all paths to "os.sep" slashes
convertedfolder = in_folder.lower().replace('\\', os.sep).replace('/', os.sep);
clientrootindex = convertedfolder.find(clientroot);
if(clientrootindex == -1):
return 0
return 1
def IsFileInDepot(in_folder, in_filename):
isUnderClientRoot = IsFolderUnderClientRoot(in_folder);
if(os.path.isfile(os.path.join(in_folder, in_filename))): # file exists on disk, not being added
if(isUnderClientRoot):
return 1
else:
return 0
else:
if(isUnderClientRoot):
return -1 # will be in the depot, it's being added
else:
return 0
def GetPendingChangelists():
# Launch p4 changes to retrieve all the pending changelists
currentuser = GetUserFromClientspec()
if(currentuser == -1):
return 0, "Unexpected output from 'p4 info'."
command = ConstructCommand('p4 changes -s pending -u ' + currentuser)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
result = result.decode('utf-8')
if(not err):
return 1, result
return 0, result
def AppendToChangelistDescription(changelist, input):
# First, create an empty changelist, we will then get the cl number and set the description
command = ConstructCommand('p4 change -o ' + changelist)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
result = result.decode('utf-8')
if(err):
return 0, err.decode('utf-8')
# Find the description field and modify it
lines = result.splitlines()
descriptionindex = -1
for index, line in enumerate(lines):
if(line.strip() == "Description:"):
descriptionindex = index
break;
filesindex = -1
for index, line in enumerate(lines):
if(line.strip() == "Files:"):
filesindex = index
break;
if(filesindex == -1): # The changelist is empty
endindex = index
else:
endindex = filesindex - 1
perforce_settings = sublime.load_settings('Perforce.sublime-settings')
lines.insert(endindex , "\t" + input)
temp_changelist_description_file = open(os.path.join(tempfile.gettempdir(), "tempchangelist.txt"), 'w')
try:
temp_changelist_description_file.write(perforce_settings.get('perforce_end_line_separator').join(lines))
finally:
temp_changelist_description_file.close()
command = ConstructCommand('p4 change -i < ' + temp_changelist_description_file.name)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
# Clean up
os.unlink(temp_changelist_description_file.name)
if(err):
return 0, err
return 1, result.decode('utf-8')
def PerforceCommandOnFile(in_command, in_folder, in_filename):
command = ConstructCommand('p4 ' + in_command + ' "' + in_filename + '"')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
if(not err):
return 1, result.decode('utf-8').strip()
else:
return 0, err.decode('utf-8').strip()
def WarnUser(message):
perforce_settings = sublime.load_settings('Perforce.sublime-settings')
if(perforce_settings.get('perforce_warnings_enabled')):
if(perforce_settings.get('perforce_log_warnings_to_status')):
sublime.status_message("Perforce [warning]: " + message)
else:
print("Perforce [warning]: " + message)
def LogResults(success, message):
if(success >= 0):
print("Perforce: " + message)
else:
WarnUser(message);
def IsFileWritable(in_filename):
if(not in_filename):
return 0
# if it doesn't exist, it's "writable"
if(not os.path.isfile(in_filename)):
return 1
filestats = os.stat(in_filename)[0];
if(filestats & stat.S_IWRITE):
return 1
return 0
# Checkout section
def Checkout(in_filename):
if(IsFileWritable(in_filename)):
return -1, "File is already writable."
folder_name, filename = os.path.split(in_filename)
isInDepot = IsFileInDepot(folder_name, filename)
if(isInDepot != 1):
return -1, "File is not under the client root."
# check out the file
return PerforceCommandOnFile("edit", folder_name, in_filename);
class PerforceAutoCheckout(sublime_plugin.EventListener):
def on_modified(self, view):
if(not view.file_name()):
return
if(IsFileWritable(view.file_name())):
return
perforce_settings = sublime.load_settings('Perforce.sublime-settings')
# check if this part of the plugin is enabled
if(not perforce_settings.get('perforce_auto_checkout') or not perforce_settings.get('perforce_auto_checkout_on_modified')):
return
if(view.is_dirty()):
success, message = Checkout(view.file_name())
LogResults(success, message);
def on_pre_save(self, view):
perforce_settings = sublime.load_settings('Perforce.sublime-settings')
# check if this part of the plugin is enabled
if(not perforce_settings.get('perforce_auto_checkout') or not perforce_settings.get('perforce_auto_checkout_on_save')):
return
if(view.is_dirty()):
success, message = Checkout(view.file_name())
LogResults(success, message);
class PerforceCheckoutCommand(sublime_plugin.TextCommand):
def run(self, edit):
if(self.view.file_name()):
success, message = Checkout(self.view.file_name())
LogResults(success, message)
else:
WarnUser("View does not contain a file")
# Add section
def Add(in_folder, in_filename):
# add the file
return PerforceCommandOnFile("add", in_folder, in_filename);
class PerforceAutoAdd(sublime_plugin.EventListener):
preSaveIsFileInDepot = 0
def on_pre_save(self, view):
# file already exists, no need to add
if view.file_name() and os.path.isfile(view.file_name()):
return
global global_folder
global_folder, filename = os.path.split(view.file_name())
perforce_settings = sublime.load_settings('Perforce.sublime-settings')
self.preSaveIsFileInDepot = 0
# check if this part of the plugin is enabled
if(not perforce_settings.get('perforce_auto_add')):
WarnUser("Auto Add disabled")
return
folder_name, filename = os.path.split(view.file_name())
self.preSaveIsFileInDepot = IsFileInDepot(folder_name, filename)
def on_post_save(self, view):
if(self.preSaveIsFileInDepot == -1):
folder_name, filename = os.path.split(view.file_name())
success, message = Add(folder_name, filename)
LogResults(success, message)
class PerforceAddCommand(sublime_plugin.TextCommand):
def run(self, edit):
if(self.view.file_name()):
folder_name, filename = os.path.split(self.view.file_name())
if(IsFileInDepot(folder_name, filename)):
success, message = Add(folder_name, filename)
else:
success = 0
message = "File is not under the client root."
LogResults(success, message)
else:
WarnUser("View does not contain a file")
# Rename section
def Rename(in_filename, in_newname):
command = ConstructCommand('p4 integrate -d -t -Di -f "' + in_filename + '" "' + in_newname + '"')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
if(err):
return 0, err.decode('utf-8').strip()
command = ConstructCommand('p4 delete "' + in_filename + '" "' + in_newname + '"')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
if(not err):
return 1, result.decode('utf-8').strip()
else:
return 0, err.decode('utf-8').strip()
class PerforceRenameCommand(sublime_plugin.WindowCommand):
def run(self):
# Get the description
self.window.show_input_panel('New File Name', self.window.active_view().file_name(),
self.on_done, self.on_change, self.on_cancel)
def on_done(self, input):
success, message = Rename(self.window.active_view().file_name(), input)
if(success):
self.window.run_command('close')
self.window.open_file(input)
LogResults(success, message)
def on_change(self, input):
pass
def on_cancel(self):
pass
# Delete section
def Delete(in_folder, in_filename):
success, message = PerforceCommandOnFile("delete", in_folder, in_filename)
if(success):
# test if the file is deleted
if(os.path.isfile(os.path.join(in_folder, in_filename))):
success = 0
return success, message
class PerforceDeleteCommand(sublime_plugin.WindowCommand):
def run(self):
if(self.window.active_view().file_name()):
folder_name, filename = os.path.split(self.window.active_view().file_name())
if(IsFileInDepot(folder_name, filename)):
success, message = Delete(folder_name, filename)
if(success): # the file was properly deleted on perforce, ask Sublime Text to close the view
self.window.run_command('close');
else:
success = 0
message = "File is not under the client root."
LogResults(success, message)
else:
WarnUser("View does not contain a file")
# Revert section
def Revert(in_folder, in_filename):
# revert the file
return PerforceCommandOnFile("revert", in_folder, in_filename);
class PerforceRevertCommand(sublime_plugin.TextCommand):
def run_(self, args): # revert cannot be called when an Edit object exists, manually handle the run routine
if(self.view.file_name()):
folder_name, filename = os.path.split(self.view.file_name())
if(IsFileInDepot(folder_name, filename)):
success, message = Revert(folder_name, filename)
if(success): # the file was properly reverted, ask Sublime Text to refresh the view
self.view.run_command('revert');
else:
success = 0
message = "File is not under the client root."
LogResults(success, message)
else:
WarnUser("View does not contain a file")
# Diff section
def Diff(in_folder, in_filename):
# diff the file
return PerforceCommandOnFile("diff", in_folder, in_filename);
class PerforceDiffCommand(sublime_plugin.TextCommand):
def run(self, edit):
if(self.view.file_name()):
folder_name, filename = os.path.split(self.view.file_name())
if(IsFileInDepot(folder_name, filename)):
success, message = Diff(folder_name, filename)
else:
success = 0
message = "File is not under the client root."
LogResults(success, message)
else:
WarnUser("View does not contain a file")
# Graphical Diff With Depot section
class GraphicalDiffThread(threading.Thread):
def __init__(self, in_folder, in_filename, in_endlineseparator, in_command):
self.folder = in_folder
self.filename = in_filename
self.endlineseparator = in_endlineseparator
self.command = in_command
threading.Thread.__init__(self)
def run(self):
success, content = PerforceCommandOnFile("print", self.folder, self.filename)
if(not success):
return 0, content
# Create a temporary file to hold the depot version
depotFileName = "depot"+self.filename
tmp_file = open(os.path.join(tempfile.gettempdir(), depotFileName), 'w')
# Remove the first two lines of content
linebyline = content.splitlines();
content=self.endlineseparator.join(linebyline[1:]);
try:
tmp_file.write(content)
finally:
tmp_file.close()
# Launch P4Diff with both files and the same arguments P4Win passes it
diffCommand = self.command
diffCommand = diffCommand.replace('%depotfile_path', tmp_file.name)
diffCommand = diffCommand.replace('%depotfile_name', depotFileName)
diffCommand = diffCommand.replace('%file_path', os.path.join(self.folder, self.filename))
diffCommand = diffCommand.replace('%file_name', self.filename)
command = ConstructCommand(diffCommand)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
# Clean up
os.unlink(tmp_file.name);
def GraphicalDiffWithDepot(self, in_folder, in_filename):
perforce_settings = sublime.load_settings('Perforce.sublime-settings')
diffcommand = perforce_settings.get('perforce_selectedgraphicaldiffapp_command')
if not diffcommand:
diffcommand = perforce_settings.get('perforce_default_graphical_diff_command')
GraphicalDiffThread(in_folder, in_filename, perforce_settings.get('perforce_end_line_separator'), diffcommand).start()
return 1, "Launching thread for Graphical Diff"
class PerforceGraphicalDiffWithDepotCommand(sublime_plugin.TextCommand):
def run(self, edit):
if(self.view.file_name()):
folder_name, filename = os.path.split(self.view.file_name())
if(IsFileInDepot(folder_name, filename)):
success, message = GraphicalDiffWithDepot(self, folder_name, filename)
else:
success = 0
message = "File is not under the client root."
LogResults(success, message)
else:
WarnUser("View does not contain a file")
class PerforceSelectGraphicalDiffApplicationCommand(sublime_plugin.WindowCommand):
def run(self):
diffapps = []
if os.path.exists(perforceplugin_dir + os.sep + 'graphicaldiffapplications.json'):
f = open(perforceplugin_dir + os.sep + 'graphicaldiffapplications.json')
applications = json.load(f)
f.close()
for entry in applications.get('applications'):
formattedentry = []
formattedentry.append(entry.get('name'))
formattedentry.append(entry.get('exename'))
diffapps.append(formattedentry)
self.window.show_quick_panel(diffapps, self.on_done)
def on_done(self, picked):
if picked == -1:
return
f = open(perforceplugin_dir + os.sep + 'graphicaldiffapplications.json')
applications = json.load(f)
entry = applications.get('applications')[picked]
f.close()
sublime.status_message(__name__ + ': Please make sure that ' + entry['exename'] + " is reachable - you might need to restart Sublime Text 2.")
settings = sublime.load_settings('Perforce.sublime-settings')
settings.set('perforce_selectedgraphicaldiffapp', entry['name'])
settings.set('perforce_selectedgraphicaldiffapp_command', entry['diffcommand'])
sublime.save_settings('Perforce.sublime-settings')
# List Checked Out Files section
class ListCheckedOutFilesThread(threading.Thread):
def __init__(self, window):
self.window = window
threading.Thread.__init__(self)
def ConvertFileNameToFileOnDisk(self, in_filename):
clientroot = GetClientRoot(os.path.dirname(in_filename))
if(clientroot == -1):
return 0
if(clientroot == "null"):
return in_filename
filename = clientroot + os.sep + in_filename.replace('\\', os.sep).replace('/', os.sep)
return filename
def MakeFileListFromChangelist(self, in_changelistline):
files_list = []
currentuser = GetUserFromClientspec()
# Launch p4 opened to retrieve all files from changelist
command = ConstructCommand('p4 opened -c ' + in_changelistline[1] + ' -u ' + currentuser)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
result = result.decode('utf-8')
if(not err):
lines = result.splitlines()
for line in lines:
# remove the change #
poundindex = line.rfind('#')
cleanedfile = line[0:poundindex]
# just keep the filename
cleanedfile = '/'.join(cleanedfile.split('/')[3:])
file_entry = [cleanedfile[cleanedfile.rfind('/')+1:]]
file_entry.append("Changelist: " + in_changelistline[1])
file_entry.append(' '.join(in_changelistline[7:]));
localfile = self.ConvertFileNameToFileOnDisk(cleanedfile)
if(localfile != 0):
file_entry.append(localfile)
files_list.append(file_entry)
return files_list
def MakeCheckedOutFileList(self):
files_list = self.MakeFileListFromChangelist(['','default','','','','','','Default Changelist']);
currentuser = GetUserFromClientspec()
if(currentuser == -1):
return files_list
# Launch p4 changes to retrieve all the pending changelists
command = ConstructCommand('p4 changes -s pending -u ' + currentuser);
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
result = result.decode('utf-8')
if(not err):
changelists = result.splitlines()
# for each line, extract the change, and run p4 opened on it to list all the files
for changelistline in changelists:
changelistlinesplit = changelistline.split(' ')
files_list.extend(self.MakeFileListFromChangelist(changelistlinesplit))
return files_list
def run(self):
self.files_list = self.MakeCheckedOutFileList()
def show_quick_panel():
if not self.files_list:
sublime.error_message(__name__ + ': There are no checked out files to list.')
return
self.window.show_quick_panel(self.files_list, self.on_done)
sublime.set_timeout(show_quick_panel, 10)
def on_done(self, picked):
if picked == -1:
return
file_name = self.files_list[picked][3]
def open_file():
self.window.open_file(file_name)
sublime.set_timeout(open_file, 10)
class PerforceListCheckedOutFilesCommand(sublime_plugin.WindowCommand):
def run(self):
ListCheckedOutFilesThread(self.window).start()
# Create Changelist section
def CreateChangelist(description):
# First, create an empty changelist, we will then get the cl number and set the description
command = ConstructCommand('p4 change -o')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
result = result.decode('utf-8')
if(err):
return 0, err.decode('utf-8')
# Find the description field and modify it
desclabel = 'Description:' + os.linesep
descindex = result.find(desclabel) + len(desclabel)
descend = result.find(os.linesep*2, descindex)
result = result[0:descindex] + '\t' + description + result[descend:]
# Remove all files from the query, we want them to stay in Default
filesindex = result.rfind("Files:")
# The Files: section we want to get rid of is only present if there's files in the default changelist
if(filesindex > 640):
result = result[0:filesindex];
temp_changelist_description_file = open(os.path.join(tempfile.gettempdir(), "tempchangelist.txt"), 'w')
try:
temp_changelist_description_file.write(result)
finally:
temp_changelist_description_file.close()
command = ConstructCommand('p4 change -i < ' + temp_changelist_description_file.name)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
# Clean up
os.unlink(temp_changelist_description_file.name)
if(err):
return 0, err.decode('utf-8')
return 1, result.decode('utf-8')
class PerforceCreateChangelistCommand(sublime_plugin.WindowCommand):
def run(self):
# Get the description
self.window.show_input_panel('Changelist Description', '',
self.on_done, self.on_change, self.on_cancel)
def on_done(self, input):
success, message = CreateChangelist(input)
LogResults(success, message)
def on_change(self, input):
pass
def on_cancel(self):
pass
# Move Current File to Changelist
def MoveFileToChangelist(in_filename, in_changelist):
folder_name, filename = os.path.split(in_filename)
command = ConstructCommand('p4 reopen -c ' + in_changelist + ' "' + filename + '"')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
if(err):
return 0, err.decode('utf-8')
return 1, result.decode('utf-8')
class ListChangelistsAndMoveFileThread(threading.Thread):
def __init__(self, window):
self.window = window
self.view = window.active_view()
threading.Thread.__init__(self)
def MakeChangelistsList(self):
success, rawchangelists = GetPendingChangelists();
resultchangelists = ['New', 'Default'];
if(success):
changelists = rawchangelists.splitlines()
# for each line, extract the change
for changelistline in changelists:
changelistlinesplit = changelistline.split(' ')
# Insert at two because we receive the changelist in the opposite order and want to keep new and default on top
resultchangelists.insert(2, "Changelist " + changelistlinesplit[1] + " - " + ' '.join(changelistlinesplit[7:]))
return resultchangelists
def run(self):
self.changelists_list = self.MakeChangelistsList()
def show_quick_panel():
if not self.changelists_list:
sublime.error_message(__name__ + ': There are no changelists to list.')
return
self.window.show_quick_panel(self.changelists_list, self.on_done)
sublime.set_timeout(show_quick_panel, 10)
def on_done(self, picked):
if picked == -1:
return
changelistlist = self.changelists_list[picked].split(' ')
def move_file():
changelist = 'Default'
if(len(changelistlist) > 1): # Numbered changelist
changelist = changelistlist[1]
else:
changelist = changelistlist[0]
if(changelist == 'New'): # Special Case
self.window.show_input_panel('Changelist Description', '', self.on_description_done, self.on_description_change, self.on_description_cancel)
else:
success, message = MoveFileToChangelist(self.view.file_name(), changelist.lower())
LogResults(success, message);
sublime.set_timeout(move_file, 10)
def on_description_done(self, input):
success, message = CreateChangelist(input)
if(success == 1):
# Extract the changelist name from the message
changelist = message.split(' ')[1]
# Move the file
success, message = MoveFileToChangelist(self.view.file_name(), changelist)
LogResults(success, message)
def on_description_change(self, input):
pass
def on_description_cancel(self):
pass
class PerforceMoveCurrentFileToChangelistCommand(sublime_plugin.WindowCommand):
def run(self):
# first, test if the file is under the client root
folder_name, filename = os.path.split(self.window.active_view().file_name())
isInDepot = IsFileInDepot(folder_name, filename)
if(isInDepot != 1):
WarnUser("File is not under the client root.")
return 0
ListChangelistsAndMoveFileThread(self.window).start()
# Add Line to Changelist Description
class AddLineToChangelistDescriptionThread(threading.Thread):
def __init__(self, window):
self.window = window
self.view = window.active_view()
threading.Thread.__init__(self)
def MakeChangelistsList(self):
success, rawchangelists = GetPendingChangelists();
resultchangelists = [];
if(success):
changelists = rawchangelists.splitlines()
# for each line, extract the change, and run p4 opened on it to list all the files
for changelistline in changelists:
changelistlinesplit = changelistline.split(' ')
# Insert at zero because we receive the changelist in the opposite order
# Might be more efficient to sort...
changelist_entry = ["Changelist " + changelistlinesplit[1]]
changelist_entry.append(' '.join(changelistlinesplit[7:]));
resultchangelists.insert(0, changelist_entry)
return resultchangelists
def run(self):
self.changelists_list = self.MakeChangelistsList()
def show_quick_panel():
if not self.changelists_list:
sublime.error_message(__name__ + ': There are no changelists to list.')
return
self.window.show_quick_panel(self.changelists_list, self.on_done)
sublime.set_timeout(show_quick_panel, 10)
def on_done(self, picked):
if picked == -1:
return
changelistlist = self.changelists_list[picked][0].split(' ')
def get_description_line():
self.changelist = changelistlist[1]
self.window.show_input_panel('Changelist Description', '', self.on_description_done, self.on_description_change, self.on_description_cancel)
sublime.set_timeout(get_description_line, 10)
def on_description_done(self, input):
success, message = AppendToChangelistDescription(self.changelist, input)
LogResults(success, message)
def on_description_change(self, input):
pass
def on_description_cancel(self):
pass
class PerforceAddLineToChangelistDescriptionCommand(sublime_plugin.WindowCommand):
def run(self):
AddLineToChangelistDescriptionThread(self.window).start()
# Submit section
class SubmitThread(threading.Thread):
def __init__(self, window):
self.window = window
self.view = window.active_view()
threading.Thread.__init__(self)
def MakeChangelistsList(self):
success, rawchangelists = GetPendingChangelists();
resultchangelists = ['Default'];
currentuser = GetUserFromClientspec();
command = ConstructCommand('p4 opened -c default -u ' + currentuser)
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
if err:
resultchangelists.pop()
if success:
changelists = rawchangelists.splitlines()
# for each line, extract the change
for changelistline in changelists:
changelistlinesplit = changelistline.split(' ')
# Insert at two because we receive the changelist in the opposite order and want to keep default on top
resultchangelists.insert(1, "Changelist " + changelistlinesplit[1] + " - " + ' '.join(changelistlinesplit[7:]))
return resultchangelists
def run(self):
self.changelists_list = self.MakeChangelistsList()
def show_quick_panel():
if not self.changelists_list:
sublime.error_message(__name__ + ': There are no changelists to list.')
return
self.window.show_quick_panel(self.changelists_list, self.on_done)
sublime.set_timeout(show_quick_panel, 10)
def on_done(self, picked):
if picked == -1:
return
changelist = self.changelists_list[picked]
changelistsections = changelist.split(' ')
command = ''
# Check in the selected changelist
if changelistsections[0] != 'Default':
command = ConstructCommand('p4 submit -c ' + changelistsections[1]);
else:
command = ConstructCommand('p4 submit')
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
result, err = p.communicate()
def on_description_change(self, input):
pass
def on_description_cancel(self):
pass
class PerforceSubmitCommand(sublime_plugin.WindowCommand):
def run(self):
SubmitThread(self.window).start()
class PerforceLogoutCommand(sublime_plugin.WindowCommand):
def run(self):
try:
command = ConstructCommand("p4 set P4PASSWD=")
p = subprocess.Popen(command, stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
p.communicate()
except ValueError:
pass
class PerforceLoginCommand(sublime_plugin.WindowCommand):
def run(self):
self.window.show_input_panel("Enter Perforce Password", "", self.on_done, None, None)
def on_done(self, password):
try:
command = ConstructCommand("p4 logout")
p = subprocess.Popen(command, stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
p.communicate()
#unset var
command = ConstructCommand("p4 set P4PASSWD=" + password)
p = subprocess.Popen(command, stdin=subprocess.PIPE,stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=global_folder, shell=True)
p.communicate()
except ValueError:
pass
class PerforceUnshelveClCommand(sublime_plugin.WindowCommand):
def run(self):
try:
ShelveClCommand(self.window, False).start()
except:
WarnUser("Unknown Error, does the included P4 Version support Shelve?")
return -1
class PerforceShelveClCommand(sublime_plugin.WindowCommand):
def run(self):
try:
ShelveClCommand(self.window, True).start()
except:
WarnUser("Unknown Error, does the included P4 Version support Shelve?")
return -1
class ShelveClCommand(threading.Thread):
def __init__(self, window, shelve=True):