1#!/usr/bin/env python
2#
3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
4#
5# Author: Simon Hausmann <simon@lst.de>
6# Copyright: 2007 Simon Hausmann <simon@lst.de>
7# 2007 Trolltech ASA
8# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
10
11import optparse, sys, os, marshal, popen2, subprocess, shelve
12import tempfile, getopt, sha, os.path, time, platform
13import re
14
15from sets import Set;
16
17gitdir = os.environ.get("GIT_DIR", "")
18verbose = False
19
20def write_pipe(c, str):
21 if verbose:
22 sys.stderr.write('writing pipe: %s\n' % c)
23
24 pipe = os.popen(c, 'w')
25 val = pipe.write(str)
26 if pipe.close():
27 sys.stderr.write('Command failed: %s' % c)
28 sys.exit(1)
29
30 return val
31
32def read_pipe(c, ignore_error=False):
33 if verbose:
34 sys.stderr.write('reading pipe: %s\n' % c)
35
36 pipe = os.popen(c, 'rb')
37 val = pipe.read()
38 if pipe.close() and not ignore_error:
39 sys.stderr.write('Command failed: %s\n' % c)
40 sys.exit(1)
41
42 return val
43
44
45def read_pipe_lines(c):
46 if verbose:
47 sys.stderr.write('reading pipe: %s\n' % c)
48 ## todo: check return status
49 pipe = os.popen(c, 'rb')
50 val = pipe.readlines()
51 if pipe.close():
52 sys.stderr.write('Command failed: %s\n' % c)
53 sys.exit(1)
54
55 return val
56
57def system(cmd):
58 if verbose:
59 sys.stderr.write("executing %s\n" % cmd)
60 if os.system(cmd) != 0:
61 die("command failed: %s" % cmd)
62
63def p4CmdList(cmd):
64 cmd = "p4 -G %s" % cmd
65 pipe = os.popen(cmd, "rb")
66
67 result = []
68 try:
69 while True:
70 entry = marshal.load(pipe)
71 result.append(entry)
72 except EOFError:
73 pass
74 exitCode = pipe.close()
75 if exitCode != None:
76 entry = {}
77 entry["p4ExitCode"] = exitCode
78 result.append(entry)
79
80 return result
81
82def p4Cmd(cmd):
83 list = p4CmdList(cmd)
84 result = {}
85 for entry in list:
86 result.update(entry)
87 return result;
88
89def p4Where(depotPath):
90 if not depotPath.endswith("/"):
91 depotPath += "/"
92 output = p4Cmd("where %s..." % depotPath)
93 if output["code"] == "error":
94 return ""
95 clientPath = ""
96 if "path" in output:
97 clientPath = output.get("path")
98 elif "data" in output:
99 data = output.get("data")
100 lastSpace = data.rfind(" ")
101 clientPath = data[lastSpace + 1:]
102
103 if clientPath.endswith("..."):
104 clientPath = clientPath[:-3]
105 return clientPath
106
107def die(msg):
108 sys.stderr.write(msg + "\n")
109 sys.exit(1)
110
111def currentGitBranch():
112 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
113
114def isValidGitDir(path):
115 if (os.path.exists(path + "/HEAD")
116 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
117 return True;
118 return False
119
120def parseRevision(ref):
121 return read_pipe("git rev-parse %s" % ref).strip()
122
123def extractLogMessageFromGitCommit(commit):
124 logMessage = ""
125
126 ## fixme: title is first line of commit, not 1st paragraph.
127 foundTitle = False
128 for log in read_pipe_lines("git cat-file commit %s" % commit):
129 if not foundTitle:
130 if len(log) == 1:
131 foundTitle = True
132 continue
133
134 logMessage += log
135 return logMessage
136
137def extractSettingsGitLog(log):
138 values = {}
139 for line in log.split("\n"):
140 line = line.strip()
141 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
142 if not m:
143 continue
144
145 assignments = m.group(1).split (':')
146 for a in assignments:
147 vals = a.split ('=')
148 key = vals[0].strip()
149 val = ('='.join (vals[1:])).strip()
150 if val.endswith ('\"') and val.startswith('"'):
151 val = val[1:-1]
152
153 values[key] = val
154
155 values['depot-paths'] = values.get("depot-paths").split(',')
156 return values
157
158def gitBranchExists(branch):
159 proc = subprocess.Popen(["git", "rev-parse", branch],
160 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
161 return proc.wait() == 0;
162
163def gitConfig(key):
164 return read_pipe("git config %s" % key, ignore_error=True).strip()
165
166class Command:
167 def __init__(self):
168 self.usage = "usage: %prog [options]"
169 self.needsGit = True
170
171class P4Debug(Command):
172 def __init__(self):
173 Command.__init__(self)
174 self.options = [
175 optparse.make_option("--verbose", dest="verbose", action="store_true"),
176 ]
177 self.description = "A tool to debug the output of p4 -G."
178 self.needsGit = False
179
180 def run(self, args):
181 for output in p4CmdList(" ".join(args)):
182 print output
183 return True
184
185class P4RollBack(Command):
186 def __init__(self):
187 Command.__init__(self)
188 self.options = [
189 optparse.make_option("--verbose", dest="verbose", action="store_true"),
190 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
191 ]
192 self.description = "A tool to debug the multi-branch import. Don't use :)"
193 self.verbose = False
194 self.rollbackLocalBranches = False
195
196 def run(self, args):
197 if len(args) != 1:
198 return False
199 maxChange = int(args[0])
200
201 if "p4ExitCode" in p4Cmd("changes -m 1"):
202 die("Problems executing p4");
203
204 if self.rollbackLocalBranches:
205 refPrefix = "refs/heads/"
206 lines = read_pipe_lines("git rev-parse --symbolic --branches")
207 else:
208 refPrefix = "refs/remotes/"
209 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
210
211 for line in lines:
212 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
213 line = line.strip()
214 ref = refPrefix + line
215 log = extractLogMessageFromGitCommit(ref)
216 settings = extractSettingsGitLog(log)
217
218 depotPaths = settings['depot-paths']
219 change = settings['change']
220
221 changed = False
222
223 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
224 for p in depotPaths]))) == 0:
225 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
226 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
227 continue
228
229 while change and int(change) > maxChange:
230 changed = True
231 if self.verbose:
232 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
233 system("git update-ref %s \"%s^\"" % (ref, ref))
234 log = extractLogMessageFromGitCommit(ref)
235 settings = extractSettingsGitLog(log)
236
237
238 depotPaths = settings['depot-paths']
239 change = settings['change']
240
241 if changed:
242 print "%s rewound to %s" % (ref, change)
243
244 return True
245
246class P4Submit(Command):
247 def __init__(self):
248 Command.__init__(self)
249 self.options = [
250 optparse.make_option("--continue", action="store_false", dest="firstTime"),
251 optparse.make_option("--verbose", dest="verbose", action="store_true"),
252 optparse.make_option("--origin", dest="origin"),
253 optparse.make_option("--reset", action="store_true", dest="reset"),
254 optparse.make_option("--log-substitutions", dest="substFile"),
255 optparse.make_option("--dry-run", action="store_true"),
256 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
257 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
258 ]
259 self.description = "Submit changes from git to the perforce depot."
260 self.usage += " [name of git branch to submit into perforce depot]"
261 self.firstTime = True
262 self.reset = False
263 self.interactive = True
264 self.dryRun = False
265 self.substFile = ""
266 self.firstTime = True
267 self.origin = ""
268 self.directSubmit = False
269 self.trustMeLikeAFool = False
270
271 self.logSubstitutions = {}
272 self.logSubstitutions["<enter description here>"] = "%log%"
273 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
274
275 def check(self):
276 if len(p4CmdList("opened ...")) > 0:
277 die("You have files opened with perforce! Close them before starting the sync.")
278
279 def start(self):
280 if len(self.config) > 0 and not self.reset:
281 die("Cannot start sync. Previous sync config found at %s\n"
282 "If you want to start submitting again from scratch "
283 "maybe you want to call git-p4 submit --reset" % self.configFile)
284
285 commits = []
286 if self.directSubmit:
287 commits.append("0")
288 else:
289 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
290 commits.append(line.strip())
291 commits.reverse()
292
293 self.config["commits"] = commits
294
295 def prepareLogMessage(self, template, message):
296 result = ""
297
298 for line in template.split("\n"):
299 if line.startswith("#"):
300 result += line + "\n"
301 continue
302
303 substituted = False
304 for key in self.logSubstitutions.keys():
305 if line.find(key) != -1:
306 value = self.logSubstitutions[key]
307 value = value.replace("%log%", message)
308 if value != "@remove@":
309 result += line.replace(key, value) + "\n"
310 substituted = True
311 break
312
313 if not substituted:
314 result += line + "\n"
315
316 return result
317
318 def applyCommit(self, id):
319 if self.directSubmit:
320 print "Applying local change in working directory/index"
321 diff = self.diffStatus
322 else:
323 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
324 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
325 filesToAdd = set()
326 filesToDelete = set()
327 editedFiles = set()
328 for line in diff:
329 modifier = line[0]
330 path = line[1:].strip()
331 if modifier == "M":
332 system("p4 edit \"%s\"" % path)
333 editedFiles.add(path)
334 elif modifier == "A":
335 filesToAdd.add(path)
336 if path in filesToDelete:
337 filesToDelete.remove(path)
338 elif modifier == "D":
339 filesToDelete.add(path)
340 if path in filesToAdd:
341 filesToAdd.remove(path)
342 else:
343 die("unknown modifier %s for %s" % (modifier, path))
344
345 if self.directSubmit:
346 diffcmd = "cat \"%s\"" % self.diffFile
347 else:
348 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
349 patchcmd = diffcmd + " | git apply "
350 tryPatchCmd = patchcmd + "--check -"
351 applyPatchCmd = patchcmd + "--check --apply -"
352
353 if os.system(tryPatchCmd) != 0:
354 print "Unfortunately applying the change failed!"
355 print "What do you want to do?"
356 response = "x"
357 while response != "s" and response != "a" and response != "w":
358 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
359 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
360 if response == "s":
361 print "Skipping! Good luck with the next patches..."
362 return
363 elif response == "a":
364 os.system(applyPatchCmd)
365 if len(filesToAdd) > 0:
366 print "You may also want to call p4 add on the following files:"
367 print " ".join(filesToAdd)
368 if len(filesToDelete):
369 print "The following files should be scheduled for deletion with p4 delete:"
370 print " ".join(filesToDelete)
371 die("Please resolve and submit the conflict manually and "
372 + "continue afterwards with git-p4 submit --continue")
373 elif response == "w":
374 system(diffcmd + " > patch.txt")
375 print "Patch saved to patch.txt in %s !" % self.clientPath
376 die("Please resolve and submit the conflict manually and "
377 "continue afterwards with git-p4 submit --continue")
378
379 system(applyPatchCmd)
380
381 for f in filesToAdd:
382 system("p4 add %s" % f)
383 for f in filesToDelete:
384 system("p4 revert %s" % f)
385 system("p4 delete %s" % f)
386
387 logMessage = ""
388 if not self.directSubmit:
389 logMessage = extractLogMessageFromGitCommit(id)
390 logMessage = logMessage.replace("\n", "\n\t")
391 logMessage = logMessage.strip()
392
393 template = read_pipe("p4 change -o")
394
395 if self.interactive:
396 submitTemplate = self.prepareLogMessage(template, logMessage)
397 diff = read_pipe("p4 diff -du ...")
398
399 for newFile in filesToAdd:
400 diff += "==== new file ====\n"
401 diff += "--- /dev/null\n"
402 diff += "+++ %s\n" % newFile
403 f = open(newFile, "r")
404 for line in f.readlines():
405 diff += "+" + line
406 f.close()
407
408 separatorLine = "######## everything below this line is just the diff #######"
409 if platform.system() == "Windows":
410 separatorLine += "\r"
411 separatorLine += "\n"
412
413 response = "e"
414 if self.trustMeLikeAFool:
415 response = "y"
416
417 firstIteration = True
418 while response == "e":
419 if not firstIteration:
420 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
421 firstIteration = False
422 if response == "e":
423 [handle, fileName] = tempfile.mkstemp()
424 tmpFile = os.fdopen(handle, "w+")
425 tmpFile.write(submitTemplate + separatorLine + diff)
426 tmpFile.close()
427 defaultEditor = "vi"
428 if platform.system() == "Windows":
429 defaultEditor = "notepad"
430 editor = os.environ.get("EDITOR", defaultEditor);
431 system(editor + " " + fileName)
432 tmpFile = open(fileName, "rb")
433 message = tmpFile.read()
434 tmpFile.close()
435 os.remove(fileName)
436 submitTemplate = message[:message.index(separatorLine)]
437
438 if response == "y" or response == "yes":
439 if self.dryRun:
440 print submitTemplate
441 raw_input("Press return to continue...")
442 else:
443 if self.directSubmit:
444 print "Submitting to git first"
445 os.chdir(self.oldWorkingDirectory)
446 write_pipe("git commit -a -F -", submitTemplate)
447 os.chdir(self.clientPath)
448
449 write_pipe("p4 submit -i", submitTemplate)
450 elif response == "s":
451 for f in editedFiles:
452 system("p4 revert \"%s\"" % f);
453 for f in filesToAdd:
454 system("p4 revert \"%s\"" % f);
455 system("rm %s" %f)
456 for f in filesToDelete:
457 system("p4 delete \"%s\"" % f);
458 return
459 else:
460 print "Not submitting!"
461 self.interactive = False
462 else:
463 fileName = "submit.txt"
464 file = open(fileName, "w+")
465 file.write(self.prepareLogMessage(template, logMessage))
466 file.close()
467 print ("Perforce submit template written as %s. "
468 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
469 % (fileName, fileName))
470
471 def run(self, args):
472 global gitdir
473 # make gitdir absolute so we can cd out into the perforce checkout
474 gitdir = os.path.abspath(gitdir)
475 os.environ["GIT_DIR"] = gitdir
476
477 if len(args) == 0:
478 self.master = currentGitBranch()
479 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
480 die("Detecting current git branch failed!")
481 elif len(args) == 1:
482 self.master = args[0]
483 else:
484 return False
485
486 depotPath = ""
487 settings = None
488 if gitBranchExists("p4"):
489 settings = extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
490 if len(depotPath) == 0 and gitBranchExists("origin"):
491 settings = extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
492 depotPaths = settings['depot-paths']
493
494 if len(depotPath) == 0:
495 print "Internal error: cannot locate perforce depot path from existing branches"
496 sys.exit(128)
497
498 self.clientPath = p4Where(depotPath)
499
500 if len(self.clientPath) == 0:
501 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
502 sys.exit(128)
503
504 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
505 self.oldWorkingDirectory = os.getcwd()
506
507 if self.directSubmit:
508 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
509 if len(self.diffStatus) == 0:
510 print "No changes in working directory to submit."
511 return True
512 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
513 self.diffFile = gitdir + "/p4-git-diff"
514 f = open(self.diffFile, "wb")
515 f.write(patch)
516 f.close();
517
518 os.chdir(self.clientPath)
519 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
520 if response == "y" or response == "yes":
521 system("p4 sync ...")
522
523 if len(self.origin) == 0:
524 if gitBranchExists("p4"):
525 self.origin = "p4"
526 else:
527 self.origin = "origin"
528
529 if self.reset:
530 self.firstTime = True
531
532 if len(self.substFile) > 0:
533 for line in open(self.substFile, "r").readlines():
534 tokens = line.strip().split("=")
535 self.logSubstitutions[tokens[0]] = tokens[1]
536
537 self.check()
538 self.configFile = gitdir + "/p4-git-sync.cfg"
539 self.config = shelve.open(self.configFile, writeback=True)
540
541 if self.firstTime:
542 self.start()
543
544 commits = self.config.get("commits", [])
545
546 while len(commits) > 0:
547 self.firstTime = False
548 commit = commits[0]
549 commits = commits[1:]
550 self.config["commits"] = commits
551 self.applyCommit(commit)
552 if not self.interactive:
553 break
554
555 self.config.close()
556
557 if self.directSubmit:
558 os.remove(self.diffFile)
559
560 if len(commits) == 0:
561 if self.firstTime:
562 print "No changes found to apply between %s and current HEAD" % self.origin
563 else:
564 print "All changes applied!"
565 os.chdir(self.oldWorkingDirectory)
566 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
567 if response == "y" or response == "yes":
568 rebase = P4Rebase()
569 rebase.run([])
570 os.remove(self.configFile)
571
572 return True
573
574class P4Sync(Command):
575 def __init__(self):
576 Command.__init__(self)
577 self.options = [
578 optparse.make_option("--branch", dest="branch"),
579 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
580 optparse.make_option("--changesfile", dest="changesFile"),
581 optparse.make_option("--silent", dest="silent", action="store_true"),
582 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
583 optparse.make_option("--verbose", dest="verbose", action="store_true"),
584 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
585 optparse.make_option("--max-changes", dest="maxChanges"),
586 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true')
587 ]
588 self.description = """Imports from Perforce into a git repository.\n
589 example:
590 //depot/my/project/ -- to import the current head
591 //depot/my/project/@all -- to import everything
592 //depot/my/project/@1,6 -- to import only from revision 1 to 6
593
594 (a ... is not needed in the path p4 specification, it's added implicitly)"""
595
596 self.usage += " //depot/path[@revRange]"
597 self.silent = False
598 self.createdBranches = Set()
599 self.committedChanges = Set()
600 self.branch = ""
601 self.detectBranches = False
602 self.detectLabels = False
603 self.changesFile = ""
604 self.syncWithOrigin = True
605 self.verbose = False
606 self.importIntoRemotes = True
607 self.maxChanges = ""
608 self.isWindows = (platform.system() == "Windows")
609 self.keepRepoPath = False
610 self.depotPaths = None
611
612 if gitConfig("git-p4.syncFromOrigin") == "false":
613 self.syncWithOrigin = False
614
615 def p4File(self, depotPath):
616 return read_pipe("p4 print -q \"%s\"" % depotPath)
617
618 def extractFilesFromCommit(self, commit):
619 files = []
620 fnum = 0
621 while commit.has_key("depotFile%s" % fnum):
622 path = commit["depotFile%s" % fnum]
623
624 found = [p for p in self.depotPaths
625 if path.startswith (p)]
626 if not found:
627 fnum = fnum + 1
628 continue
629
630 file = {}
631 file["path"] = path
632 file["rev"] = commit["rev%s" % fnum]
633 file["action"] = commit["action%s" % fnum]
634 file["type"] = commit["type%s" % fnum]
635 files.append(file)
636 fnum = fnum + 1
637 return files
638
639 def stripRepoPath(self, path, prefixes):
640 if self.keepRepoPath:
641 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
642
643 for p in prefixes:
644 if path.startswith(p):
645 path = path[len(p):]
646
647 return path
648
649 def splitFilesIntoBranches(self, commit):
650 branches = {}
651 fnum = 0
652 while commit.has_key("depotFile%s" % fnum):
653 path = commit["depotFile%s" % fnum]
654 found = [p for p in self.depotPaths
655 if path.startswith (p)]
656 if not found:
657 fnum = fnum + 1
658 continue
659
660 file = {}
661 file["path"] = path
662 file["rev"] = commit["rev%s" % fnum]
663 file["action"] = commit["action%s" % fnum]
664 file["type"] = commit["type%s" % fnum]
665 fnum = fnum + 1
666
667 relPath = self.stripRepoPath(path, self.depotPaths)
668
669 for branch in self.knownBranches.keys():
670
671 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
672 if relPath.startswith(branch + "/"):
673 if branch not in branches:
674 branches[branch] = []
675 branches[branch].append(file)
676
677 return branches
678
679 def commit(self, details, files, branch, branchPrefixes, parent = ""):
680 epoch = details["time"]
681 author = details["user"]
682
683 if self.verbose:
684 print "commit into %s" % branch
685
686 self.gitStream.write("commit %s\n" % branch)
687 # gitStream.write("mark :%s\n" % details["change"])
688 self.committedChanges.add(int(details["change"]))
689 committer = ""
690 if author not in self.users:
691 self.getUserMapFromPerforceServer()
692 if author in self.users:
693 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
694 else:
695 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
696
697 self.gitStream.write("committer %s\n" % committer)
698
699 self.gitStream.write("data <<EOT\n")
700 self.gitStream.write(details["desc"])
701 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
702 "options = %s]\n"
703 % (','.join (branchPrefixes), details["change"],
704 details['options']
705 ))
706 self.gitStream.write("EOT\n\n")
707
708 if len(parent) > 0:
709 if self.verbose:
710 print "parent %s" % parent
711 self.gitStream.write("from %s\n" % parent)
712
713 for file in files:
714 path = file["path"]
715
716
717 if not [p for p in branchPrefixes if path.startswith(p)]:
718 continue
719 rev = file["rev"]
720 depotPath = path + "#" + rev
721 relPath = self.stripRepoPath(path, branchPrefixes)
722 action = file["action"]
723
724 if file["type"] == "apple":
725 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
726 continue
727
728 if action == "delete":
729 self.gitStream.write("D %s\n" % relPath)
730 else:
731 mode = 644
732 if file["type"].startswith("x"):
733 mode = 755
734
735 data = self.p4File(depotPath)
736
737 if self.isWindows and file["type"].endswith("text"):
738 data = data.replace("\r\n", "\n")
739
740 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
741 self.gitStream.write("data %s\n" % len(data))
742 self.gitStream.write(data)
743 self.gitStream.write("\n")
744
745 self.gitStream.write("\n")
746
747 change = int(details["change"])
748
749 if self.labels.has_key(change):
750 label = self.labels[change]
751 labelDetails = label[0]
752 labelRevisions = label[1]
753 if self.verbose:
754 print "Change %s is labelled %s" % (change, labelDetails)
755
756 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
757 for p in branchPrefixes]))
758
759 if len(files) == len(labelRevisions):
760
761 cleanedFiles = {}
762 for info in files:
763 if info["action"] == "delete":
764 continue
765 cleanedFiles[info["depotFile"]] = info["rev"]
766
767 if cleanedFiles == labelRevisions:
768 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
769 self.gitStream.write("from %s\n" % branch)
770
771 owner = labelDetails["Owner"]
772 tagger = ""
773 if author in self.users:
774 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
775 else:
776 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
777 self.gitStream.write("tagger %s\n" % tagger)
778 self.gitStream.write("data <<EOT\n")
779 self.gitStream.write(labelDetails["Description"])
780 self.gitStream.write("EOT\n\n")
781
782 else:
783 if not self.silent:
784 print ("Tag %s does not match with change %s: files do not match."
785 % (labelDetails["label"], change))
786
787 else:
788 if not self.silent:
789 print ("Tag %s does not match with change %s: file count is different."
790 % (labelDetails["label"], change))
791
792 def getUserMapFromPerforceServer(self):
793 if self.userMapFromPerforceServer:
794 return
795 self.users = {}
796
797 for output in p4CmdList("users"):
798 if not output.has_key("User"):
799 continue
800 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
801
802 cache = open(gitdir + "/p4-usercache.txt", "wb")
803 for user in self.users.keys():
804 cache.write("%s\t%s\n" % (user, self.users[user]))
805 cache.close();
806 self.userMapFromPerforceServer = True
807
808 def loadUserMapFromCache(self):
809 self.users = {}
810 self.userMapFromPerforceServer = False
811 try:
812 cache = open(gitdir + "/p4-usercache.txt", "rb")
813 lines = cache.readlines()
814 cache.close()
815 for line in lines:
816 entry = line.strip().split("\t")
817 self.users[entry[0]] = entry[1]
818 except IOError:
819 self.getUserMapFromPerforceServer()
820
821 def getLabels(self):
822 self.labels = {}
823
824 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
825 if len(l) > 0 and not self.silent:
826 print "Finding files belonging to labels in %s" % `self.depotPath`
827
828 for output in l:
829 label = output["label"]
830 revisions = {}
831 newestChange = 0
832 if self.verbose:
833 print "Querying files for label %s" % label
834 for file in p4CmdList("files "
835 + ' '.join (["%s...@%s" % (p, label)
836 for p in self.depotPaths])):
837 revisions[file["depotFile"]] = file["rev"]
838 change = int(file["change"])
839 if change > newestChange:
840 newestChange = change
841
842 self.labels[newestChange] = [output, revisions]
843
844 if self.verbose:
845 print "Label changes: %s" % self.labels.keys()
846
847 def getBranchMapping(self):
848
849 ## FIXME - what's a P4 projectName ?
850 self.projectName = self.depotPath[self.depotPath.strip().rfind("/") + 1:]
851
852 for info in p4CmdList("branches"):
853 details = p4Cmd("branch -o %s" % info["branch"])
854 viewIdx = 0
855 while details.has_key("View%s" % viewIdx):
856 paths = details["View%s" % viewIdx].split(" ")
857 viewIdx = viewIdx + 1
858 # require standard //depot/foo/... //depot/bar/... mapping
859 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
860 continue
861 source = paths[0]
862 destination = paths[1]
863 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
864 source = source[len(self.depotPath):-4]
865 destination = destination[len(self.depotPath):-4]
866 if destination not in self.knownBranches:
867 self.knownBranches[destination] = source
868 if source not in self.knownBranches:
869 self.knownBranches[source] = source
870
871 def listExistingP4GitBranches(self):
872 self.p4BranchesInGit = []
873
874 cmdline = "git rev-parse --symbolic "
875 if self.importIntoRemotes:
876 cmdline += " --remotes"
877 else:
878 cmdline += " --branches"
879
880 for line in read_pipe_lines(cmdline):
881 line = line.strip()
882 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD"):
883 continue
884
885 if self.importIntoRemotes:
886 # strip off p4
887 branch = re.sub ("^p4/", "", line)
888
889 self.p4BranchesInGit.append(branch)
890 self.initialParents[self.refPrefix + branch] = parseRevision(line)
891
892 def createOrUpdateBranchesFromOrigin(self):
893 if not self.silent:
894 print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
895
896 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
897 line = line.strip()
898 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
899 continue
900
901 headName = line[len("origin/"):]
902 remoteHead = self.refPrefix + headName
903 originHead = "origin/" + headName
904
905 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
906 if (not original.has_key('depot-paths')
907 or not original.has_key('change')):
908 continue
909
910 update = False
911 if not gitBranchExists(remoteHead):
912 if self.verbose:
913 print "creating %s" % remoteHead
914 update = True
915 else:
916 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
917 if settings.has_key('change') > 0:
918 if settings['depot-paths'] == original['depot-paths']:
919 originP4Change = int(original['change'])
920 p4Change = int(settings['change'])
921 if originP4Change > p4Change:
922 print ("%s (%s) is newer than %s (%s). "
923 "Updating p4 branch from origin."
924 % (originHead, originP4Change,
925 remoteHead, p4Change))
926 update = True
927 else:
928 print ("Ignoring: %s was imported from %s while "
929 "%s was imported from %s"
930 % (originHead, ','.join(original['depot-paths']),
931 remoteHead, ','.join(settings['depot-paths'])))
932
933 if update:
934 system("git update-ref %s %s" % (remoteHead, originHead))
935
936 def updateOptionDict(self, d):
937 option_keys = {}
938 if self.keepRepoPath:
939 option_keys['keepRepoPath'] = 1
940
941 d["options"] = ' '.join(sorted(option_keys.keys()))
942
943 def readOptions(self, d):
944 self.keepRepoPath = (d.has_key('options')
945 and ('keepRepoPath' in d['options']))
946
947 def run(self, args):
948 self.depotPaths = []
949 self.changeRange = ""
950 self.initialParent = ""
951 self.previousDepotPaths = []
952
953 # map from branch depot path to parent branch
954 self.knownBranches = {}
955 self.initialParents = {}
956 self.hasOrigin = gitBranchExists("origin")
957
958 if self.importIntoRemotes:
959 self.refPrefix = "refs/remotes/p4/"
960 else:
961 self.refPrefix = "refs/heads/"
962
963 if self.syncWithOrigin and self.hasOrigin:
964 if not self.silent:
965 print "Syncing with origin first by calling git fetch origin"
966 system("git fetch origin")
967
968 if len(self.branch) == 0:
969 self.branch = self.refPrefix + "master"
970 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
971 system("git update-ref %s refs/heads/p4" % self.branch)
972 system("git branch -D p4");
973 # create it /after/ importing, when master exists
974 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
975 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
976
977 ### FIXME
978 if 1:
979 if self.hasOrigin:
980 self.createOrUpdateBranchesFromOrigin()
981 self.listExistingP4GitBranches()
982
983 if len(self.p4BranchesInGit) > 1:
984 if not self.silent:
985 print "Importing from/into multiple branches"
986 self.detectBranches = True
987
988 if self.verbose:
989 print "branches: %s" % self.p4BranchesInGit
990
991 p4Change = 0
992 for branch in self.p4BranchesInGit:
993 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
994
995 settings = extractSettingsGitLog(logMsg)
996
997 if self.verbose:
998 print "path %s change %s" % (','.join(depotPaths), change)
999
1000 self.readOptions(settings)
1001 if (settings.has_key('depot-paths')
1002 and settings.has_key ('change')):
1003 change = int(settings['change']) + 1
1004 p4Change = max(p4Change, change)
1005
1006 depotPaths = sorted(settings['depot-paths'])
1007 if self.previousDepotPaths == []:
1008 self.previousDepotPaths = depotPaths
1009 else:
1010 paths = []
1011 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1012 for i in range(0, max(len(cur), len(prev))):
1013 if cur[i] <> prev[i]:
1014 break
1015
1016 paths.append (cur[:i])
1017
1018 self.previousDepotPaths = paths
1019
1020 if p4Change > 0:
1021 self.depotPaths = sorted(self.previousDepotPaths)
1022 self.changeRange = "@%s,#head" % p4Change
1023 self.initialParent = parseRevision(self.branch)
1024 if not self.silent and not self.detectBranches:
1025 print "Performing incremental import into %s git branch" % self.branch
1026
1027 if not self.branch.startswith("refs/"):
1028 self.branch = "refs/heads/" + self.branch
1029
1030 if len(args) == 0 and self.depotPaths:
1031 if not self.silent:
1032 print "Depot paths: %s" % ' '.join(self.depotPaths)
1033 else:
1034 if self.depotPaths and self.depotPaths != args:
1035 print ("previous import used depot path %s and now %s was specified. "
1036 "This doesn't work!" % (' '.join (self.depotPaths),
1037 ' '.join (args)))
1038 sys.exit(1)
1039
1040 self.depotPaths = sorted(args)
1041
1042 self.revision = ""
1043 self.users = {}
1044
1045 newPaths = []
1046 for p in self.depotPaths:
1047 if p.find("@") != -1:
1048 atIdx = p.index("@")
1049 self.changeRange = p[atIdx:]
1050 if self.changeRange == "@all":
1051 self.changeRange = ""
1052 elif self.changeRange.find(",") == -1:
1053 self.revision = self.changeRange
1054 self.changeRange = ""
1055 p = p[0:atIdx]
1056 elif p.find("#") != -1:
1057 hashIdx = p.index("#")
1058 self.revision = p[hashIdx:]
1059 p = p[0:hashIdx]
1060 elif self.previousDepotPaths == []:
1061 self.revision = "#head"
1062
1063 p = re.sub ("\.\.\.$", "", p)
1064 if not p.endswith("/"):
1065 p += "/"
1066
1067 newPaths.append(p)
1068
1069 self.depotPaths = newPaths
1070
1071
1072 self.loadUserMapFromCache()
1073 self.labels = {}
1074 if self.detectLabels:
1075 self.getLabels();
1076
1077 if self.detectBranches:
1078 self.getBranchMapping();
1079 if self.verbose:
1080 print "p4-git branches: %s" % self.p4BranchesInGit
1081 print "initial parents: %s" % self.initialParents
1082 for b in self.p4BranchesInGit:
1083 if b != "master":
1084
1085 ## FIXME
1086 b = b[len(self.projectName):]
1087 self.createdBranches.add(b)
1088
1089 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1090
1091 importProcess = subprocess.Popen(["git", "fast-import"],
1092 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1093 stderr=subprocess.PIPE);
1094 self.gitOutput = importProcess.stdout
1095 self.gitStream = importProcess.stdin
1096 self.gitError = importProcess.stderr
1097
1098 if len(self.revision) > 0:
1099 print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
1100
1101 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1102 details["desc"] = ("Initial import of %s from the state at revision %s"
1103 % (' '.join(self.depotPaths), self.revision))
1104 details["change"] = self.revision
1105 newestRevision = 0
1106
1107 fileCnt = 0
1108 for info in p4CmdList("files "
1109 + ' '.join(["%s...%s"
1110 % (p, self.revision)
1111 for p in self.depotPaths])):
1112 change = int(info["change"])
1113 if change > newestRevision:
1114 newestRevision = change
1115
1116 if info["action"] == "delete":
1117 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1118 #fileCnt = fileCnt + 1
1119 continue
1120
1121 for prop in [ "depotFile", "rev", "action", "type" ]:
1122 details["%s%s" % (prop, fileCnt)] = info[prop]
1123
1124 fileCnt = fileCnt + 1
1125
1126 details["change"] = newestRevision
1127 self.updateOptionDict(details)
1128 try:
1129 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1130 except IOError:
1131 print "IO error with git fast-import. Is your git version recent enough?"
1132 print self.gitError.read()
1133
1134 else:
1135 changes = []
1136
1137 if len(self.changesFile) > 0:
1138 output = open(self.changesFile).readlines()
1139 changeSet = Set()
1140 for line in output:
1141 changeSet.add(int(line))
1142
1143 for change in changeSet:
1144 changes.append(change)
1145
1146 changes.sort()
1147 else:
1148 if self.verbose:
1149 print "Getting p4 changes for %s...%s" % (`self.depotPaths`,
1150 self.changeRange)
1151 assert self.depotPaths
1152 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1153 for p in self.depotPaths]))
1154
1155 for line in output:
1156 changeNum = line.split(" ")[1]
1157 changes.append(changeNum)
1158
1159 changes.reverse()
1160
1161 if len(self.maxChanges) > 0:
1162 changes = changes[0:min(int(self.maxChanges), len(changes))]
1163
1164 if len(changes) == 0:
1165 if not self.silent:
1166 print "No changes to import!"
1167 return True
1168
1169 self.updatedBranches = set()
1170
1171 cnt = 1
1172 for change in changes:
1173 description = p4Cmd("describe %s" % change)
1174 self.updateOptionDict(description)
1175
1176 if not self.silent:
1177 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1178 sys.stdout.flush()
1179 cnt = cnt + 1
1180
1181 try:
1182 if self.detectBranches:
1183 branches = self.splitFilesIntoBranches(description)
1184 for branch in branches.keys():
1185 ## HACK --hwn
1186 branchPrefix = self.depotPaths[0] + branch + "/"
1187
1188 parent = ""
1189
1190 filesForCommit = branches[branch]
1191
1192 if self.verbose:
1193 print "branch is %s" % branch
1194
1195 self.updatedBranches.add(branch)
1196
1197 if branch not in self.createdBranches:
1198 self.createdBranches.add(branch)
1199 parent = self.knownBranches[branch]
1200 if parent == branch:
1201 parent = ""
1202 elif self.verbose:
1203 print "parent determined through known branches: %s" % parent
1204
1205 # main branch? use master
1206 if branch == "main":
1207 branch = "master"
1208 else:
1209
1210 ## FIXME
1211 branch = self.projectName + branch
1212
1213 if parent == "main":
1214 parent = "master"
1215 elif len(parent) > 0:
1216 ## FIXME
1217 parent = self.projectName + parent
1218
1219 branch = self.refPrefix + branch
1220 if len(parent) > 0:
1221 parent = self.refPrefix + parent
1222
1223 if self.verbose:
1224 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1225
1226 if len(parent) == 0 and branch in self.initialParents:
1227 parent = self.initialParents[branch]
1228 del self.initialParents[branch]
1229
1230 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1231 else:
1232 files = self.extractFilesFromCommit(description)
1233 self.commit(description, files, self.branch, self.depotPaths,
1234 self.initialParent)
1235 self.initialParent = ""
1236 except IOError:
1237 print self.gitError.read()
1238 sys.exit(1)
1239
1240 if not self.silent:
1241 print ""
1242 if len(self.updatedBranches) > 0:
1243 sys.stdout.write("Updated branches: ")
1244 for b in self.updatedBranches:
1245 sys.stdout.write("%s " % b)
1246 sys.stdout.write("\n")
1247
1248
1249 self.gitStream.close()
1250 if importProcess.wait() != 0:
1251 die("fast-import failed: %s" % self.gitError.read())
1252 self.gitOutput.close()
1253 self.gitError.close()
1254
1255 return True
1256
1257class P4Rebase(Command):
1258 def __init__(self):
1259 Command.__init__(self)
1260 self.options = [ ]
1261 self.description = ("Fetches the latest revision from perforce and "
1262 + "rebases the current work (branch) against it")
1263
1264 def run(self, args):
1265 sync = P4Sync()
1266 sync.run([])
1267 print "Rebasing the current branch"
1268 oldHead = read_pipe("git rev-parse HEAD").strip()
1269 system("git rebase p4")
1270 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1271 return True
1272
1273class P4Clone(P4Sync):
1274 def __init__(self):
1275 P4Sync.__init__(self)
1276 self.description = "Creates a new git repository and imports from Perforce into it"
1277 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1278 self.options.append(
1279 optparse.make_option("--destination", dest="cloneDestination",
1280 action='store', default=None,
1281 help="where to leave result of the clone"))
1282 self.cloneDestination = None
1283 self.needsGit = False
1284
1285 def run(self, args):
1286 global gitdir
1287
1288 if len(args) < 1:
1289 return False
1290
1291 if self.keepRepoPath and not self.cloneDestination:
1292 sys.stderr.write("Must specify destination for --keep-path\n")
1293 sys.exit(1)
1294
1295 depotPaths = args
1296 for p in depotPaths:
1297 if not p.startswith("//"):
1298 return False
1299
1300 if not self.cloneDestination:
1301 depotPath = args[0]
1302 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1303 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1304 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1305 depotDir = re.sub(r"/$", "", depotDir)
1306
1307 self.cloneDestination = os.path.split(depotDir)[1]
1308
1309 print "Importing from %s into %s" % (`depotPaths`, self.cloneDestination)
1310 os.makedirs(self.cloneDestination)
1311 os.chdir(self.cloneDestination)
1312 system("git init")
1313 gitdir = os.getcwd() + "/.git"
1314 if not P4Sync.run(self, depotPaths):
1315 return False
1316 if self.branch != "master":
1317 if gitBranchExists("refs/remotes/p4/master"):
1318 system("git branch master refs/remotes/p4/master")
1319 system("git checkout -f")
1320 else:
1321 print "Could not detect main branch. No checkout/master branch created."
1322 return True
1323
1324class HelpFormatter(optparse.IndentedHelpFormatter):
1325 def __init__(self):
1326 optparse.IndentedHelpFormatter.__init__(self)
1327
1328 def format_description(self, description):
1329 if description:
1330 return description + "\n"
1331 else:
1332 return ""
1333
1334def printUsage(commands):
1335 print "usage: %s <command> [options]" % sys.argv[0]
1336 print ""
1337 print "valid commands: %s" % ", ".join(commands)
1338 print ""
1339 print "Try %s <command> --help for command specific help." % sys.argv[0]
1340 print ""
1341
1342commands = {
1343 "debug" : P4Debug(),
1344 "submit" : P4Submit(),
1345 "sync" : P4Sync(),
1346 "rebase" : P4Rebase(),
1347 "clone" : P4Clone(),
1348 "rollback" : P4RollBack()
1349}
1350
1351
1352def main():
1353 if len(sys.argv[1:]) == 0:
1354 printUsage(commands.keys())
1355 sys.exit(2)
1356
1357 cmd = ""
1358 cmdName = sys.argv[1]
1359 try:
1360 cmd = commands[cmdName]
1361 except KeyError:
1362 print "unknown command %s" % cmdName
1363 print ""
1364 printUsage(commands.keys())
1365 sys.exit(2)
1366
1367 options = cmd.options
1368 cmd.gitdir = gitdir
1369
1370 args = sys.argv[2:]
1371
1372 if len(options) > 0:
1373 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1374
1375 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1376 options,
1377 description = cmd.description,
1378 formatter = HelpFormatter())
1379
1380 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1381 global verbose
1382 verbose = cmd.verbose
1383 if cmd.needsGit:
1384 gitdir = cmd.gitdir
1385 if len(gitdir) == 0:
1386 gitdir = ".git"
1387 if not isValidGitDir(gitdir):
1388 gitdir = read_pipe("git rev-parse --git-dir").strip()
1389 if os.path.exists(gitdir):
1390 cdup = read_pipe("git rev-parse --show-cdup").strip()
1391 if len(cdup) > 0:
1392 os.chdir(cdup);
1393
1394 if not isValidGitDir(gitdir):
1395 if isValidGitDir(gitdir + "/.git"):
1396 gitdir += "/.git"
1397 else:
1398 die("fatal: cannot locate git repository at %s" % gitdir)
1399
1400 os.environ["GIT_DIR"] = gitdir
1401
1402 if not cmd.run(args):
1403 parser.print_help()
1404
1405
1406if __name__ == '__main__':
1407 main()