forked from ermshiperete/git-p4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
git-p4.py25
2102 lines (1730 loc) · 75.1 KB
/
git-p4.py25
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
#!/usr/bin/env python
#
# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
#
# Author: Simon Hausmann <[email protected]>
# Copyright: 2007 Simon Hausmann <[email protected]>
# 2007 Trolltech ASA
# License: MIT <http://www.opensource.org/licenses/mit-license.php>
#
import optparse, sys, os, marshal, subprocess, shelve
import tempfile, getopt, sha, os.path, time, platform
import re
import cStringIO
from sets import Set;
verbose = False
class LargeFileWriter:
"""Wrapper for a file, to get around a windows bug when writing large amounts of data.
When writing to the wrapped file object, writes are broken up so that only 10MB are written at
a time. Otherwise, there is IO exception on Windows.
"""
def __init__(self, filedesc):
self.read = filedesc.read
self.flush = filedesc.flush
self.close = filedesc.close
self.filedesc = filedesc
def write(self, bytes):
chunk = 10*1024*1024 # I don't know how high we can go before the bug is triggered, so we
#only write 10MB at a time.
while len(bytes) > chunk:
self.filedesc.write(bytes[:chunk])
self.filedesc.flush()
bytes = bytes[chunk:]
if len(bytes):
self.filedesc.write(bytes[:chunk])
self.filedesc.flush()
def p4_build_cmd(cmd):
"""Build a suitable p4 command line.
This consolidates building and returning a p4 command line into one
location. It means that hooking into the environment, or other configuration
can be done more easily.
"""
real_cmd = "%s " % "p4"
user = gitConfig("git-p4.user")
if len(user) > 0:
real_cmd += "-u %s " % user
password = gitConfig("git-p4.password")
if len(password) > 0:
real_cmd += "-P %s " % password
port = gitConfig("git-p4.port")
if len(port) > 0:
real_cmd += "-p %s " % port
host = gitConfig("git-p4.host")
if len(host) > 0:
real_cmd += "-h %s " % host
client = gitConfig("git-p4.client")
if len(client) > 0:
real_cmd += "-c %s " % client
real_cmd += "%s" % (cmd)
if verbose:
print real_cmd
return real_cmd
def chdir(dir):
if os.name == 'nt':
os.environ['PWD']=dir
os.chdir(dir)
def die(msg):
if verbose:
raise Exception(msg)
else:
sys.stderr.write(msg + "\n")
sys.exit(1)
def write_pipe(c, str):
if verbose:
sys.stderr.write('Writing pipe: %s\n' % c)
pipe = os.popen(c, 'w')
val = pipe.write(str)
if pipe.close():
die('Command failed: %s' % c)
return val
def p4_write_pipe(c, str):
real_cmd = p4_build_cmd(c)
return write_pipe(real_cmd, str)
def read_pipe(c, ignore_error=False):
if verbose:
sys.stderr.write('Reading pipe: %s\n' % c)
pipe = os.popen(c, 'rb')
val = pipe.read()
if pipe.close() and not ignore_error:
die('Command failed: %s' % c)
return val
def p4_read_pipe(c, ignore_error=False):
real_cmd = p4_build_cmd(c)
return read_pipe(real_cmd, ignore_error)
def read_pipe_lines(c):
if verbose:
sys.stderr.write('Reading pipe: %s\n' % c)
## todo: check return status
pipe = os.popen(c, 'rb')
val = pipe.readlines()
if pipe.close():
die('Command failed: %s' % c)
return val
def p4_read_pipe_lines(c):
"""Specifically invoke p4 on the command supplied. """
real_cmd = p4_build_cmd(c)
return read_pipe_lines(real_cmd)
def system(cmd):
if verbose:
sys.stderr.write("executing %s\n" % cmd)
if os.system(cmd) != 0:
die("command failed: %s" % cmd)
def p4_system(cmd):
"""Specifically invoke p4 as the system command. """
real_cmd = p4_build_cmd(cmd)
return system(real_cmd)
def isP4Exec(kind):
"""Determine if a Perforce 'kind' should have execute permission
'p4 help filetypes' gives a list of the types. If it starts with 'x',
or x follows one of a few letters. Otherwise, if there is an 'x' after
a plus sign, it is also executable"""
return (re.search(r"(^[cku]?x)|\+.*x", kind) != None)
def setP4ExecBit(file, mode):
# Reopens an already open file and changes the execute bit to match
# the execute bit setting in the passed in mode.
p4Type = "+x"
if not isModeExec(mode):
p4Type = getP4OpenedType(file)
p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
if p4Type[-1] == "+":
p4Type = p4Type[0:-1]
p4_system("reopen -t %s %s" % (p4Type, file))
def getP4OpenedType(file):
# Returns the perforce file type for the given file.
result = p4_read_pipe("opened %s" % file)
match = re.match(".*\((.+)\)\r?$", result)
if match:
return match.group(1)
else:
die("Could not determine file type for %s (result: '%s')" % (file, result))
def diffTreePattern():
# This is a simple generator for the diff tree regex pattern. This could be
# a class variable if this and parseDiffTreeEntry were a part of a class.
pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
while True:
yield pattern
def parseDiffTreeEntry(entry):
"""Parses a single diff tree entry into its component elements.
See git-diff-tree(1) manpage for details about the format of the diff
output. This method returns a dictionary with the following elements:
src_mode - The mode of the source file
dst_mode - The mode of the destination file
src_sha1 - The sha1 for the source file
dst_sha1 - The sha1 fr the destination file
status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
status_score - The score for the status (applicable for 'C' and 'R'
statuses). This is None if there is no score.
src - The path for the source file.
dst - The path for the destination file. This is only present for
copy or renames. If it is not present, this is None.
If the pattern is not matched, None is returned."""
match = diffTreePattern().next().match(entry)
if match:
return {
'src_mode': match.group(1),
'dst_mode': match.group(2),
'src_sha1': match.group(3),
'dst_sha1': match.group(4),
'status': match.group(5),
'status_score': match.group(6),
'src': match.group(7),
'dst': match.group(10)
}
return None
def isModeExec(mode):
# Returns True if the given git mode represents an executable file,
# otherwise False.
return mode[-3:] == "755"
def isModeExecChanged(src_mode, dst_mode):
return isModeExec(src_mode) != isModeExec(dst_mode)
# Some commands (eg. p4 print the entire repository) can result in gigabytes of
# data. In order to handle this without running out of memory, we have to
# process these items in batches of maybe 100 at a time. The P4CmdReader class
# handles this chunking of data.
class P4CmdReader:
def __init__(self, cmd, stdin):
self.MAX_CHUNKS = 100
self.p4 = p4CmdListOpen(cmd, stdin)
def __iter__(self):
return self
def next(self):
try:
return marshal.load(self.p4.stdout)
except IOError, e:
print "IOError while reading marshaller: %s" % repr(e)
print e.strerror
raise
except EOFError:
raise StopIteration
def p4CmdListOpen(cmd, stdin=None, stdin_mode='w+b'):
cmd = p4_build_cmd("-G %s" % (cmd))
if verbose:
sys.stderr.write("Opening pipe: %s\n" % cmd)
# Use a temporary file to avoid deadlocks without
# subprocess.communicate(), which would put another copy
# of stdout into memory.
stdin_file = None
if stdin is not None:
stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
stdin_file.write(stdin)
stdin_file.flush()
stdin_file.seek(0)
return subprocess.Popen(cmd, shell=True,
stdin=stdin_file,
stdout=subprocess.PIPE)
def p4CmdList(cmd, stdin=None, stdin_mode='w+b'):
p4 = p4CmdListOpen(cmd, stdin, stdin_mode)
result = []
try:
while True:
entry = marshal.load(p4.stdout)
result.append(entry)
except EOFError:
pass
exitCode = p4.wait()
if exitCode != 0:
entry = {}
entry["p4ExitCode"] = exitCode
result.append(entry)
return result
def p4Cmd(cmd):
list = p4CmdList(cmd)
result = {}
for entry in list:
result.update(entry)
return result;
def p4Where(depotPath):
if not depotPath.endswith("/"):
depotPath += "/"
depotPath = depotPath + "..."
outputList = p4CmdList("where %s" % depotPath)
output = None
for entry in outputList:
print repr(entry)
print "depotPath:" + depotPath
if "depotFile" in entry:
if entry["depotFile"] == depotPath:
output = entry
print "found1"
break
elif "data" in entry:
data = entry.get("data")
space = data.find(" ")
if data[:space] == depotPath:
output = entry
print "found2"
break
else:
print "not found"
if output == None:
return ""
if output["code"] == "error":
return ""
clientPath = ""
if "path" in output:
clientPath = output.get("path")
elif "data" in output:
data = output.get("data")
lastSpace = data.rfind(" ")
clientPath = data[lastSpace + 1:]
if clientPath.endswith("..."):
clientPath = clientPath[:-3]
return clientPath
def currentGitBranch():
return read_pipe("git name-rev HEAD").split(" ")[1].strip()
def isValidGitDir(path):
if (os.path.exists(path + "/HEAD")
and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
return True;
return False
def parseRevision(ref):
return read_pipe("git rev-parse %s" % ref).strip()
def extractLogMessageFromGitCommit(commit):
logMessage = ""
## fixme: title is first line of commit, not 1st paragraph.
foundTitle = False
for log in read_pipe_lines("git cat-file commit %s" % commit):
if not foundTitle:
if len(log) == 1:
foundTitle = True
continue
logMessage += log
return logMessage
def extractSettingsGitLog(log):
values = {}
for line in log.split("\n"):
line = line.strip()
m = re.search (r"^ *\[git-p4: (.*)\]$", line)
if not m:
continue
assignments = m.group(1).split (':')
for a in assignments:
vals = a.split ('=')
key = vals[0].strip()
val = ('='.join (vals[1:])).strip()
if val.endswith ('\"') and val.startswith('"'):
val = val[1:-1]
values[key] = val
paths = values.get("depot-paths")
if not paths:
paths = values.get("depot-path")
if paths:
values['depot-paths'] = paths.split(',')
return values
def gitBranchExists(branch):
proc = subprocess.Popen(["git", "rev-parse", branch],
stderr=subprocess.PIPE, stdout=subprocess.PIPE);
return proc.wait() == 0;
_gitConfig = {}
def gitConfig(key):
if not _gitConfig.has_key(key):
_gitConfig[key] = read_pipe("git config %s" % key, ignore_error=True).strip()
return _gitConfig[key]
def p4BranchesInGit(branchesAreInRemotes = True):
branches = {}
cmdline = "git rev-parse --symbolic "
if branchesAreInRemotes:
cmdline += " --remotes"
else:
cmdline += " --branches"
for line in read_pipe_lines(cmdline):
line = line.strip()
## only import to p4/
if not line.startswith('p4/') or line == "p4/HEAD":
continue
branch = line
# strip off p4
branch = re.sub ("^p4/", "", line)
branches[branch] = parseRevision(line)
return branches
def findUpstreamBranchPoint(head = "HEAD"):
branches = p4BranchesInGit()
# map from depot-path to branch name
branchByDepotPath = {}
for branch in branches.keys():
tip = branches[branch]
log = extractLogMessageFromGitCommit(tip)
settings = extractSettingsGitLog(log)
if settings.has_key("depot-paths"):
paths = ",".join(settings["depot-paths"])
branchByDepotPath[paths] = "remotes/p4/" + branch
settings = None
parent = 0
while parent < 65535:
commit = head + "~%s" % parent
log = extractLogMessageFromGitCommit(commit)
settings = extractSettingsGitLog(log)
if settings.has_key("depot-paths"):
paths = ",".join(settings["depot-paths"])
if branchByDepotPath.has_key(paths):
return [branchByDepotPath[paths], settings]
parent = parent + 1
return ["", settings]
def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
if not silent:
print ("Creating/updating branch(es) in %s based on origin branch(es)"
% localRefPrefix)
originPrefix = "origin/p4/"
for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
line = line.strip()
if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
continue
headName = line[len(originPrefix):]
remoteHead = localRefPrefix + headName
originHead = line
original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
if (not original.has_key('depot-paths')
or not original.has_key('change')):
continue
update = False
if not gitBranchExists(remoteHead):
if verbose:
print "creating %s" % remoteHead
update = True
else:
settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
if settings.has_key('change') > 0:
if settings['depot-paths'] == original['depot-paths']:
originP4Change = int(original['change'])
p4Change = int(settings['change'])
if originP4Change > p4Change:
print ("%s (%s) is newer than %s (%s). "
"Updating p4 branch from origin."
% (originHead, originP4Change,
remoteHead, p4Change))
update = True
else:
print ("Ignoring: %s was imported from %s while "
"%s was imported from %s"
% (originHead, ','.join(original['depot-paths']),
remoteHead, ','.join(settings['depot-paths'])))
if update:
system("git update-ref %s %s" % (remoteHead, originHead))
def originP4BranchesExist():
return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
def p4ChangesForPaths(depotPaths, changeRange):
assert depotPaths
output = p4_read_pipe_lines("changes " + ' '.join (["%s...%s" % (p, changeRange)
for p in depotPaths]))
changes = []
for line in output:
changeNum = line.split(" ")[1]
changes.append(int(changeNum))
changes.sort()
return changes
class Command:
def __init__(self):
self.usage = "usage: %prog [options]"
self.needsGit = True
class P4Debug(Command):
def __init__(self):
Command.__init__(self)
self.options = [
optparse.make_option("--verbose", dest="verbose", action="store_true",
default=False),
]
self.description = "A tool to debug the output of p4 -G."
self.needsGit = False
self.verbose = False
def run(self, args):
j = 0
for output in p4CmdList(" ".join(args)):
print 'Element: %d' % j
j += 1
print output
return True
class P4RollBack(Command):
def __init__(self):
Command.__init__(self)
self.options = [
optparse.make_option("--verbose", dest="verbose", action="store_true"),
optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
]
self.description = "A tool to debug the multi-branch import. Don't use :)"
self.verbose = False
self.rollbackLocalBranches = False
def run(self, args):
if len(args) != 1:
return False
maxChange = int(args[0])
if "p4ExitCode" in p4Cmd("changes -m 1"):
die("Problems executing p4");
if self.rollbackLocalBranches:
refPrefix = "refs/heads/"
lines = read_pipe_lines("git rev-parse --symbolic --branches")
else:
refPrefix = "refs/remotes/"
lines = read_pipe_lines("git rev-parse --symbolic --remotes")
for line in lines:
if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
line = line.strip()
ref = refPrefix + line
log = extractLogMessageFromGitCommit(ref)
settings = extractSettingsGitLog(log)
depotPaths = settings['depot-paths']
change = settings['change']
changed = False
if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
for p in depotPaths]))) == 0:
print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
continue
while change and int(change) > maxChange:
changed = True
if self.verbose:
print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
system("git update-ref %s \"%s^\"" % (ref, ref))
log = extractLogMessageFromGitCommit(ref)
settings = extractSettingsGitLog(log)
depotPaths = settings['depot-paths']
change = settings['change']
if changed:
print "%s rewound to %s" % (ref, change)
return True
class P4FileReader:
Bytes = 0
LastFile = ''
LastBytes = 0
def __init__(self, files, clientSpecDirs):
# Initialize P4FileReader object with a list of files to read. This
# takes into account the clientSpecDirs passed in.
# Each element of files is a dictionary with the following
# elements:
#
# path: The complete path to the file in the depot, starting from "//"
# action: The action to take. Eg: 'delete' 'purge'
# list of files to commit.
self.filesForCommit = []
# list of files to read, filtered according to the client spec.
self.filesToRead = []
# mapping from path to file record.
self.pathMap = {}
self.filesRead = 0
self.filterClientSpec( files, clientSpecDirs )
self.reader = P4CmdReader('-x - print',
stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
for f in self.filesToRead]) )
# leftover record from previous time next() was called.
self.leftover = None
def filterClientSpec( self, files, clientSpecDirs ):
# sets filesForCommit and filesToRead, filtered according to the client spec.
for f in files:
includeFile = False
excludeFile = False
if len(clientSpecDirs):
for val in clientSpecDirs:
if f['path'].startswith(val[0]):
if val[1] > 0:
includeFile = True
else:
excludeFile = True
else:
includeFile = True
if includeFile and not excludeFile:
self.filesForCommit.append(f)
self.pathMap[f['path']] = f
if f['action'] not in ('delete', 'purge'):
self.filesToRead.append(f)
def printStatus(self, filename):
if filename == self.LastFile and self.Bytes - self.LastBytes < 100*1024: return
self.LastFile = filename
self.LastBytes = self.Bytes
if len(filename) <= 60:
line = filename + " " * (63-len(filename))
else:
line = "..." + filename[len(filename)-60:]
print "%s | %.1f MB (%d/%d files)\r" % (line,
float(self.Bytes) / (1024*1024), self.filesRead + 1,
len(self.filesToRead)),
def __iter__(self):
return self
def next(self):
# Return a record containing a file to commit.
#
# Perforce outputs a number of records for each file. The first one
# contains basic information such as the change list and filename. This
# is followed by a number of records containing only "code" and "data"
# fields, which are the file data broken apart.
# while perforce keeps giving us files we didn't ask for,
# (Shouldn't ever happen, but handle it anyway)
while 1:
textBuffer = cStringIO.StringIO()
if self.leftover:
header = self.leftover
self.leftover = None
else:
try:
header = self.reader.next()
except StopIteration:
print "" # newline for status information
raise
# now we have the header record.
if not header.has_key('depotFile'):
die("p4 print fails with: %s\n" % repr(header))
self.printStatus(header['depotFile'])
for record in self.reader:
if record['code'] in ( 'text', 'unicode', 'binary' ):
# encountered subsequent data chunk. Append to file data.
textBuffer.write( record['data'] )
self.Bytes += len(record['data'])
del record['data']
self.printStatus(header['depotFile'])
else:
# encountered the next header.
# store for processing next time.
self.leftover = record
break
text = textBuffer.getvalue()
textBuffer.close()
if header['type'] in ('text+ko', 'unicode+ko', 'binary+ko'):
text = re.sub(r'(?i)\$(Id|Header):[^$]*\$',r'$\1$', text)
elif header['type'] in ('text+k', 'ktext', 'kxtext', 'unicode+k', 'binary+k'):
text = re.sub(r'\$(Id|Header|Author|Date|DateTime|Change|File|Revision):[^$\n]*\$',r'$\1$', text)
file = None
filePath = header['depotFile']
if filePath in self.pathMap:
file = self.pathMap[filePath]
file['data'] = text
self.filesRead += 1
return file
else:
# perforce gave us something we didn't ask for?
print "Bad path: %s" % filePath
continue
class P4Submit(Command):
def __init__(self):
Command.__init__(self)
self.options = [
optparse.make_option("--verbose", dest="verbose", action="store_true"),
optparse.make_option("--origin", dest="origin"),
optparse.make_option("-M", dest="detectRename", action="store_true"),
]
self.description = "Submit changes from git to the perforce depot."
self.usage += " [name of git branch to submit into perforce depot]"
self.interactive = True
self.origin = ""
self.detectRename = False
self.verbose = False
self.isWindows = (platform.system() == "Windows")
def check(self):
if len(p4CmdList("opened ...")) > 0:
die("You have files opened with perforce! Close them before starting the sync.")
# replaces everything between 'Description:' and the next P4 submit template field with the
# commit message
def prepareLogMessage(self, template, message):
result = ""
inDescriptionSection = False
for line in template.split("\n"):
if line.startswith("#"):
result += line + "\n"
continue
if inDescriptionSection:
if line.startswith("Files:"):
inDescriptionSection = False
else:
continue
else:
if line.startswith("Description:"):
inDescriptionSection = True
line += "\n"
for messageLine in message.split("\n"):
line += "\t" + messageLine + "\n"
result += line + "\n"
return result
def prepareSubmitTemplate(self):
# remove lines in the Files section that show changes to files outside the depot path we're committing into
template = ""
inFilesSection = False
for line in p4_read_pipe_lines("change -o"):
if line.endswith("\r\n"):
line = line[:-2] + "\n"
if inFilesSection:
if line.startswith("\t"):
# path starts and ends with a tab
path = line[1:]
lastTab = path.rfind("\t")
if lastTab != -1:
path = path[:lastTab]
if not path.startswith(self.depotPath):
continue
else:
inFilesSection = False
else:
if line.startswith("Files:"):
inFilesSection = True
template += line
return template
def applyCommit(self, id):
print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
diffOpts = ("", "-M")[self.detectRename]
diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (diffOpts, id, id))
filesToAdd = set()
filesToDelete = set()
editedFiles = set()
filesToChangeExecBit = {}
for line in diff:
diff = parseDiffTreeEntry(line)
modifier = diff['status']
path = diff['src']
if modifier == "M":
p4_system("edit \"%s\"" % path)
if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
filesToChangeExecBit[path] = diff['dst_mode']
editedFiles.add(path)
elif modifier == "A":
filesToAdd.add(path)
filesToChangeExecBit[path] = diff['dst_mode']
if path in filesToDelete:
filesToDelete.remove(path)
elif modifier == "D":
filesToDelete.add(path)
if path in filesToAdd:
filesToAdd.remove(path)
elif modifier == "R":
src, dest = diff['src'], diff['dst']
p4_system("integrate -Dt \"%s\" \"%s\"" % (src, dest))
p4_system("edit \"%s\"" % (dest))
if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
filesToChangeExecBit[dest] = diff['dst_mode']
os.unlink(dest)
editedFiles.add(dest)
filesToDelete.add(src)
else:
die("unknown modifier %s for %s" % (modifier, path))
diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
patchcmd = diffcmd + " | git apply "
tryPatchCmd = patchcmd + "--check -"
applyPatchCmd = patchcmd + "--check --apply -"
if os.system(tryPatchCmd) != 0:
print "Unfortunately applying the change failed!"
print "What do you want to do?"
response = "x"
while response != "s" and response != "a" and response != "w":
response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
"and with .rej files / [w]rite the patch to a file (patch.txt) ")
if response == "s":
print "Skipping! Good luck with the next patches..."
for f in editedFiles:
p4_system("revert \"%s\"" % f);
for f in filesToAdd:
system("rm %s" %f)
return
elif response == "a":
os.system(applyPatchCmd)
if len(filesToAdd) > 0:
print "You may also want to call p4 add on the following files:"
print " ".join(filesToAdd)
if len(filesToDelete):
print "The following files should be scheduled for deletion with p4 delete:"
print " ".join(filesToDelete)
die("Please resolve and submit the conflict manually and "
+ "continue afterwards with git-p4 submit --continue")
elif response == "w":
system(diffcmd + " > patch.txt")
print "Patch saved to patch.txt in %s !" % self.clientPath
die("Please resolve and submit the conflict manually and "
"continue afterwards with git-p4 submit --continue")
system(applyPatchCmd)
for f in filesToAdd:
p4_system("add \"%s\"" % f)
for f in filesToDelete:
p4_system("revert \"%s\"" % f)
p4_system("delete \"%s\"" % f)
# Set/clear executable bits
for f in filesToChangeExecBit.keys():
mode = filesToChangeExecBit[f]
setP4ExecBit(f, mode)
logMessage = extractLogMessageFromGitCommit(id)
logMessage = logMessage.strip()
template = self.prepareSubmitTemplate()
if self.interactive:
submitTemplate = self.prepareLogMessage(template, logMessage)
if os.environ.has_key("P4DIFF"):
del(os.environ["P4DIFF"])
diff = p4_read_pipe("diff -du ...")
newdiff = ""
for newFile in filesToAdd:
newdiff += "==== new file ====\n"
newdiff += "--- /dev/null\n"
newdiff += "+++ %s\n" % newFile
f = open(newFile, "r")
for line in f.readlines():
newdiff += "+" + line
f.close()
separatorLine = "######## everything below this line is just the diff #######\n"
[handle, fileName] = tempfile.mkstemp()
tmpFile = os.fdopen(handle, "w+")
if self.isWindows:
submitTemplate = submitTemplate.replace("\n", "\r\n")
separatorLine = separatorLine.replace("\n", "\r\n")
newdiff = newdiff.replace("\n", "\r\n")
tmpFile.write(submitTemplate + separatorLine + diff + newdiff)
tmpFile.close()
mtime = os.stat(fileName).st_mtime
defaultEditor = "vi"
if platform.system() == "Windows":
defaultEditor = "notepad"
if os.environ.has_key("P4EDITOR"):
editor = os.environ.get("P4EDITOR")
else:
editor = os.environ.get("EDITOR", defaultEditor);
system(editor + " " + fileName)
response = "y"
if os.stat(fileName).st_mtime <= mtime:
response = "x"
while response != "y" and response != "n":
response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
if response == "y":
tmpFile = open(fileName, "rb")
message = tmpFile.read()
tmpFile.close()
submitTemplate = message[:message.index(separatorLine)]
if self.isWindows:
submitTemplate = submitTemplate.replace("\r\n", "\n")
p4_write_pipe("submit -i", submitTemplate)
else:
for f in editedFiles:
p4_system("revert \"%s\"" % f);
for f in filesToAdd:
p4_system("revert \"%s\"" % f);
system("rm %s" %f)
os.remove(fileName)
else:
fileName = "submit.txt"
file = open(fileName, "w+")
file.write(self.prepareLogMessage(template, logMessage))
file.close()
print ("Perforce submit template written as %s. "
+ "Please review/edit and then use p4 submit -i < %s to submit directly!"
% (fileName, fileName))
def run(self, args):
if len(args) == 0:
self.master = currentGitBranch()
if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
die("Detecting current git branch failed!")
elif len(args) == 1:
self.master = args[0]
else:
return False
allowSubmit = gitConfig("git-p4.allowSubmit")
if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
die("%s is not in git-p4.allowSubmit" % self.master)
[upstream, settings] = findUpstreamBranchPoint()
self.depotPath = settings['depot-paths'][0]
if len(self.origin) == 0:
self.origin = upstream
if self.verbose:
print "Origin branch is " + self.origin
if len(self.depotPath) == 0:
print "Internal error: cannot locate perforce depot path from existing branches"
sys.exit(128)
self.clientPath = p4Where(self.depotPath)
if len(self.clientPath) == 0:
print "Error: Cannot locate perforce checkout of %s in client view" % self.depotPath
sys.exit(128)
print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
self.oldWorkingDirectory = os.getcwd()
chdir(self.clientPath)
print "Syncronizing p4 checkout..."
p4_system("sync ...")
self.check()