3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 import optparse, sys, os, marshal, popen2, subprocess, shelve
12 import tempfile, getopt, sha, os.path, time, platform
23 sys.stderr.write(msg + "\n")
26 def write_pipe(c, str):
28 sys.stderr.write('Writing pipe: %s\n' % c)
30 pipe = os.popen(c, 'w')
33 die('Command failed: %s' % c)
37 def read_pipe(c, ignore_error=False):
39 sys.stderr.write('Reading pipe: %s\n' % c)
41 pipe = os.popen(c, 'rb')
43 if pipe.close() and not ignore_error:
44 die('Command failed: %s' % c)
49 def read_pipe_lines(c):
51 sys.stderr.write('Reading pipe: %s\n' % c)
52 ## todo: check return status
53 pipe = os.popen(c, 'rb')
54 val = pipe.readlines()
56 die('Command failed: %s' % c)
62 sys.stderr.write("executing %s\n" % cmd)
63 if os.system(cmd) != 0:
64 die("command failed: %s" % cmd)
66 def p4CmdList(cmd, stdin=None, stdin_mode='w+b'):
67 cmd = "p4 -G %s" % cmd
69 sys.stderr.write("Opening pipe: %s\n" % cmd)
71 # Use a temporary file to avoid deadlocks without
72 # subprocess.communicate(), which would put another copy
73 # of stdout into memory.
76 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
77 stdin_file.write(stdin)
81 p4 = subprocess.Popen(cmd, shell=True,
83 stdout=subprocess.PIPE)
88 entry = marshal.load(p4.stdout)
95 entry["p4ExitCode"] = exitCode
101 list = p4CmdList(cmd)
107 def p4Where(depotPath):
108 if not depotPath.endswith("/"):
110 output = p4Cmd("where %s..." % depotPath)
111 if output["code"] == "error":
115 clientPath = output.get("path")
116 elif "data" in output:
117 data = output.get("data")
118 lastSpace = data.rfind(" ")
119 clientPath = data[lastSpace + 1:]
121 if clientPath.endswith("..."):
122 clientPath = clientPath[:-3]
125 def currentGitBranch():
126 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
128 def isValidGitDir(path):
129 if (os.path.exists(path + "/HEAD")
130 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
134 def parseRevision(ref):
135 return read_pipe("git rev-parse %s" % ref).strip()
137 def extractLogMessageFromGitCommit(commit):
140 ## fixme: title is first line of commit, not 1st paragraph.
142 for log in read_pipe_lines("git cat-file commit %s" % commit):
151 def extractSettingsGitLog(log):
153 for line in log.split("\n"):
155 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
159 assignments = m.group(1).split (':')
160 for a in assignments:
162 key = vals[0].strip()
163 val = ('='.join (vals[1:])).strip()
164 if val.endswith ('\"') and val.startswith('"'):
169 paths = values.get("depot-paths")
171 paths = values.get("depot-path")
173 values['depot-paths'] = paths.split(',')
176 def gitBranchExists(branch):
177 proc = subprocess.Popen(["git", "rev-parse", branch],
178 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
179 return proc.wait() == 0;
182 return read_pipe("git config %s" % key, ignore_error=True).strip()
184 def p4BranchesInGit(branchesAreInRemotes = True):
187 cmdline = "git rev-parse --symbolic "
188 if branchesAreInRemotes:
189 cmdline += " --remotes"
191 cmdline += " --branches"
193 for line in read_pipe_lines(cmdline):
196 ## only import to p4/
197 if not line.startswith('p4/') or line == "p4/HEAD":
202 branch = re.sub ("^p4/", "", line)
204 branches[branch] = parseRevision(line)
207 def findUpstreamBranchPoint(head = "HEAD"):
208 branches = p4BranchesInGit()
209 # map from depot-path to branch name
210 branchByDepotPath = {}
211 for branch in branches.keys():
212 tip = branches[branch]
213 log = extractLogMessageFromGitCommit(tip)
214 settings = extractSettingsGitLog(log)
215 if settings.has_key("depot-paths"):
216 paths = ",".join(settings["depot-paths"])
217 branchByDepotPath[paths] = "remotes/p4/" + branch
221 while parent < 65535:
222 commit = head + "~%s" % parent
223 log = extractLogMessageFromGitCommit(commit)
224 settings = extractSettingsGitLog(log)
225 if settings.has_key("depot-paths"):
226 paths = ",".join(settings["depot-paths"])
227 if branchByDepotPath.has_key(paths):
228 return [branchByDepotPath[paths], settings]
232 return ["", settings]
236 self.usage = "usage: %prog [options]"
239 class P4Debug(Command):
241 Command.__init__(self)
243 optparse.make_option("--verbose", dest="verbose", action="store_true",
246 self.description = "A tool to debug the output of p4 -G."
247 self.needsGit = False
252 for output in p4CmdList(" ".join(args)):
253 print 'Element: %d' % j
258 class P4RollBack(Command):
260 Command.__init__(self)
262 optparse.make_option("--verbose", dest="verbose", action="store_true"),
263 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
265 self.description = "A tool to debug the multi-branch import. Don't use :)"
267 self.rollbackLocalBranches = False
272 maxChange = int(args[0])
274 if "p4ExitCode" in p4Cmd("changes -m 1"):
275 die("Problems executing p4");
277 if self.rollbackLocalBranches:
278 refPrefix = "refs/heads/"
279 lines = read_pipe_lines("git rev-parse --symbolic --branches")
281 refPrefix = "refs/remotes/"
282 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
285 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
287 ref = refPrefix + line
288 log = extractLogMessageFromGitCommit(ref)
289 settings = extractSettingsGitLog(log)
291 depotPaths = settings['depot-paths']
292 change = settings['change']
296 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
297 for p in depotPaths]))) == 0:
298 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
299 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
302 while change and int(change) > maxChange:
305 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
306 system("git update-ref %s \"%s^\"" % (ref, ref))
307 log = extractLogMessageFromGitCommit(ref)
308 settings = extractSettingsGitLog(log)
311 depotPaths = settings['depot-paths']
312 change = settings['change']
315 print "%s rewound to %s" % (ref, change)
319 class P4Submit(Command):
321 Command.__init__(self)
323 optparse.make_option("--continue", action="store_false", dest="firstTime"),
324 optparse.make_option("--verbose", dest="verbose", action="store_true"),
325 optparse.make_option("--origin", dest="origin"),
326 optparse.make_option("--reset", action="store_true", dest="reset"),
327 optparse.make_option("--log-substitutions", dest="substFile"),
328 optparse.make_option("--dry-run", action="store_true"),
329 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
330 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
332 self.description = "Submit changes from git to the perforce depot."
333 self.usage += " [name of git branch to submit into perforce depot]"
334 self.firstTime = True
336 self.interactive = True
339 self.firstTime = True
341 self.directSubmit = False
342 self.trustMeLikeAFool = False
344 self.isWindows = (platform.system() == "Windows")
346 self.logSubstitutions = {}
347 self.logSubstitutions["<enter description here>"] = "%log%"
348 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
351 if len(p4CmdList("opened ...")) > 0:
352 die("You have files opened with perforce! Close them before starting the sync.")
355 if len(self.config) > 0 and not self.reset:
356 die("Cannot start sync. Previous sync config found at %s\n"
357 "If you want to start submitting again from scratch "
358 "maybe you want to call git-p4 submit --reset" % self.configFile)
361 if self.directSubmit:
364 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
365 commits.append(line.strip())
368 self.config["commits"] = commits
370 def prepareLogMessage(self, template, message):
373 for line in template.split("\n"):
374 if line.startswith("#"):
375 result += line + "\n"
379 for key in self.logSubstitutions.keys():
380 if line.find(key) != -1:
381 value = self.logSubstitutions[key]
382 value = value.replace("%log%", message)
383 if value != "@remove@":
384 result += line.replace(key, value) + "\n"
389 result += line + "\n"
393 def applyCommit(self, id):
394 if self.directSubmit:
395 print "Applying local change in working directory/index"
396 diff = self.diffStatus
398 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
399 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
401 filesToDelete = set()
405 path = line[1:].strip()
407 system("p4 edit \"%s\"" % path)
408 editedFiles.add(path)
409 elif modifier == "A":
411 if path in filesToDelete:
412 filesToDelete.remove(path)
413 elif modifier == "D":
414 filesToDelete.add(path)
415 if path in filesToAdd:
416 filesToAdd.remove(path)
418 die("unknown modifier %s for %s" % (modifier, path))
420 if self.directSubmit:
421 diffcmd = "cat \"%s\"" % self.diffFile
423 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
424 patchcmd = diffcmd + " | git apply "
425 tryPatchCmd = patchcmd + "--check -"
426 applyPatchCmd = patchcmd + "--check --apply -"
428 if os.system(tryPatchCmd) != 0:
429 print "Unfortunately applying the change failed!"
430 print "What do you want to do?"
432 while response != "s" and response != "a" and response != "w":
433 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
434 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
436 print "Skipping! Good luck with the next patches..."
438 elif response == "a":
439 os.system(applyPatchCmd)
440 if len(filesToAdd) > 0:
441 print "You may also want to call p4 add on the following files:"
442 print " ".join(filesToAdd)
443 if len(filesToDelete):
444 print "The following files should be scheduled for deletion with p4 delete:"
445 print " ".join(filesToDelete)
446 die("Please resolve and submit the conflict manually and "
447 + "continue afterwards with git-p4 submit --continue")
448 elif response == "w":
449 system(diffcmd + " > patch.txt")
450 print "Patch saved to patch.txt in %s !" % self.clientPath
451 die("Please resolve and submit the conflict manually and "
452 "continue afterwards with git-p4 submit --continue")
454 system(applyPatchCmd)
457 system("p4 add \"%s\"" % f)
458 for f in filesToDelete:
459 system("p4 revert \"%s\"" % f)
460 system("p4 delete \"%s\"" % f)
463 if not self.directSubmit:
464 logMessage = extractLogMessageFromGitCommit(id)
465 logMessage = logMessage.replace("\n", "\n\t")
467 logMessage = logMessage.replace("\n", "\r\n")
468 logMessage = logMessage.strip()
470 template = read_pipe("p4 change -o")
473 submitTemplate = self.prepareLogMessage(template, logMessage)
474 diff = read_pipe("p4 diff -du ...")
476 for newFile in filesToAdd:
477 diff += "==== new file ====\n"
478 diff += "--- /dev/null\n"
479 diff += "+++ %s\n" % newFile
480 f = open(newFile, "r")
481 for line in f.readlines():
485 separatorLine = "######## everything below this line is just the diff #######"
486 if platform.system() == "Windows":
487 separatorLine += "\r"
488 separatorLine += "\n"
491 if self.trustMeLikeAFool:
494 firstIteration = True
495 while response == "e":
496 if not firstIteration:
497 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
498 firstIteration = False
500 [handle, fileName] = tempfile.mkstemp()
501 tmpFile = os.fdopen(handle, "w+")
502 tmpFile.write(submitTemplate + separatorLine + diff)
505 if platform.system() == "Windows":
506 defaultEditor = "notepad"
507 editor = os.environ.get("EDITOR", defaultEditor);
508 system(editor + " " + fileName)
509 tmpFile = open(fileName, "rb")
510 message = tmpFile.read()
513 submitTemplate = message[:message.index(separatorLine)]
515 submitTemplate = submitTemplate.replace("\r\n", "\n")
517 if response == "y" or response == "yes":
520 raw_input("Press return to continue...")
522 if self.directSubmit:
523 print "Submitting to git first"
524 os.chdir(self.oldWorkingDirectory)
525 write_pipe("git commit -a -F -", submitTemplate)
526 os.chdir(self.clientPath)
528 write_pipe("p4 submit -i", submitTemplate)
529 elif response == "s":
530 for f in editedFiles:
531 system("p4 revert \"%s\"" % f);
533 system("p4 revert \"%s\"" % f);
535 for f in filesToDelete:
536 system("p4 delete \"%s\"" % f);
539 print "Not submitting!"
540 self.interactive = False
542 fileName = "submit.txt"
543 file = open(fileName, "w+")
544 file.write(self.prepareLogMessage(template, logMessage))
546 print ("Perforce submit template written as %s. "
547 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
548 % (fileName, fileName))
552 self.master = currentGitBranch()
553 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
554 die("Detecting current git branch failed!")
556 self.master = args[0]
560 [upstream, settings] = findUpstreamBranchPoint()
561 depotPath = settings['depot-paths'][0]
562 if len(self.origin) == 0:
563 self.origin = upstream
566 print "Origin branch is " + self.origin
568 if len(depotPath) == 0:
569 print "Internal error: cannot locate perforce depot path from existing branches"
572 self.clientPath = p4Where(depotPath)
574 if len(self.clientPath) == 0:
575 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
578 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
579 self.oldWorkingDirectory = os.getcwd()
581 if self.directSubmit:
582 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
583 if len(self.diffStatus) == 0:
584 print "No changes in working directory to submit."
586 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
587 self.diffFile = self.gitdir + "/p4-git-diff"
588 f = open(self.diffFile, "wb")
592 os.chdir(self.clientPath)
593 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
594 if response == "y" or response == "yes":
595 system("p4 sync ...")
598 self.firstTime = True
600 if len(self.substFile) > 0:
601 for line in open(self.substFile, "r").readlines():
602 tokens = line.strip().split("=")
603 self.logSubstitutions[tokens[0]] = tokens[1]
606 self.configFile = self.gitdir + "/p4-git-sync.cfg"
607 self.config = shelve.open(self.configFile, writeback=True)
612 commits = self.config.get("commits", [])
614 while len(commits) > 0:
615 self.firstTime = False
617 commits = commits[1:]
618 self.config["commits"] = commits
619 self.applyCommit(commit)
620 if not self.interactive:
625 if self.directSubmit:
626 os.remove(self.diffFile)
628 if len(commits) == 0:
630 print "No changes found to apply between %s and current HEAD" % self.origin
632 print "All changes applied!"
633 os.chdir(self.oldWorkingDirectory)
634 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
635 if response == "y" or response == "yes":
638 os.remove(self.configFile)
642 class P4Sync(Command):
644 Command.__init__(self)
646 optparse.make_option("--branch", dest="branch"),
647 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
648 optparse.make_option("--changesfile", dest="changesFile"),
649 optparse.make_option("--silent", dest="silent", action="store_true"),
650 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
651 optparse.make_option("--verbose", dest="verbose", action="store_true"),
652 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
653 help="Import into refs/heads/ , not refs/remotes"),
654 optparse.make_option("--max-changes", dest="maxChanges"),
655 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
656 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
658 self.description = """Imports from Perforce into a git repository.\n
660 //depot/my/project/ -- to import the current head
661 //depot/my/project/@all -- to import everything
662 //depot/my/project/@1,6 -- to import only from revision 1 to 6
664 (a ... is not needed in the path p4 specification, it's added implicitly)"""
666 self.usage += " //depot/path[@revRange]"
668 self.createdBranches = Set()
669 self.committedChanges = Set()
671 self.detectBranches = False
672 self.detectLabels = False
673 self.changesFile = ""
674 self.syncWithOrigin = True
676 self.importIntoRemotes = True
678 self.isWindows = (platform.system() == "Windows")
679 self.keepRepoPath = False
680 self.depotPaths = None
681 self.p4BranchesInGit = []
683 if gitConfig("git-p4.syncFromOrigin") == "false":
684 self.syncWithOrigin = False
686 def extractFilesFromCommit(self, commit):
689 while commit.has_key("depotFile%s" % fnum):
690 path = commit["depotFile%s" % fnum]
692 found = [p for p in self.depotPaths
693 if path.startswith (p)]
700 file["rev"] = commit["rev%s" % fnum]
701 file["action"] = commit["action%s" % fnum]
702 file["type"] = commit["type%s" % fnum]
707 def stripRepoPath(self, path, prefixes):
708 if self.keepRepoPath:
709 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
712 if path.startswith(p):
717 def splitFilesIntoBranches(self, commit):
720 while commit.has_key("depotFile%s" % fnum):
721 path = commit["depotFile%s" % fnum]
722 found = [p for p in self.depotPaths
723 if path.startswith (p)]
730 file["rev"] = commit["rev%s" % fnum]
731 file["action"] = commit["action%s" % fnum]
732 file["type"] = commit["type%s" % fnum]
735 relPath = self.stripRepoPath(path, self.depotPaths)
737 for branch in self.knownBranches.keys():
739 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
740 if relPath.startswith(branch + "/"):
741 if branch not in branches:
742 branches[branch] = []
743 branches[branch].append(file)
748 ## Should move this out, doesn't use SELF.
749 def readP4Files(self, files):
750 files = [f for f in files
751 if f['action'] != 'delete']
756 filedata = p4CmdList('-x - print',
757 stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
760 if "p4ExitCode" in filedata[0]:
761 die("Problems executing p4. Error: [%d]."
762 % (filedata[0]['p4ExitCode']));
766 while j < len(filedata):
770 while j < len(filedata) and filedata[j]['code'] in ('text',
772 text += filedata[j]['data']
776 if not stat.has_key('depotFile'):
777 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
780 contents[stat['depotFile']] = text
783 assert not f.has_key('data')
784 f['data'] = contents[f['path']]
786 def commit(self, details, files, branch, branchPrefixes, parent = ""):
787 epoch = details["time"]
788 author = details["user"]
791 print "commit into %s" % branch
793 # start with reading files; if that fails, we should not
797 if [p for p in branchPrefixes if f['path'].startswith(p)]:
800 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
802 self.readP4Files(files)
807 self.gitStream.write("commit %s\n" % branch)
808 # gitStream.write("mark :%s\n" % details["change"])
809 self.committedChanges.add(int(details["change"]))
811 if author not in self.users:
812 self.getUserMapFromPerforceServer()
813 if author in self.users:
814 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
816 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
818 self.gitStream.write("committer %s\n" % committer)
820 self.gitStream.write("data <<EOT\n")
821 self.gitStream.write(details["desc"])
822 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
823 % (','.join (branchPrefixes), details["change"]))
824 if len(details['options']) > 0:
825 self.gitStream.write(": options = %s" % details['options'])
826 self.gitStream.write("]\nEOT\n\n")
830 print "parent %s" % parent
831 self.gitStream.write("from %s\n" % parent)
834 if file["type"] == "apple":
835 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
838 relPath = self.stripRepoPath(file['path'], branchPrefixes)
839 if file["action"] == "delete":
840 self.gitStream.write("D %s\n" % relPath)
843 if file["type"].startswith("x"):
848 if self.isWindows and file["type"].endswith("text"):
849 data = data.replace("\r\n", "\n")
851 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
852 self.gitStream.write("data %s\n" % len(data))
853 self.gitStream.write(data)
854 self.gitStream.write("\n")
856 self.gitStream.write("\n")
858 change = int(details["change"])
860 if self.labels.has_key(change):
861 label = self.labels[change]
862 labelDetails = label[0]
863 labelRevisions = label[1]
865 print "Change %s is labelled %s" % (change, labelDetails)
867 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
868 for p in branchPrefixes]))
870 if len(files) == len(labelRevisions):
874 if info["action"] == "delete":
876 cleanedFiles[info["depotFile"]] = info["rev"]
878 if cleanedFiles == labelRevisions:
879 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
880 self.gitStream.write("from %s\n" % branch)
882 owner = labelDetails["Owner"]
884 if author in self.users:
885 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
887 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
888 self.gitStream.write("tagger %s\n" % tagger)
889 self.gitStream.write("data <<EOT\n")
890 self.gitStream.write(labelDetails["Description"])
891 self.gitStream.write("EOT\n\n")
895 print ("Tag %s does not match with change %s: files do not match."
896 % (labelDetails["label"], change))
900 print ("Tag %s does not match with change %s: file count is different."
901 % (labelDetails["label"], change))
903 def getUserCacheFilename(self):
904 return os.environ["HOME"] + "/.gitp4-usercache.txt"
906 def getUserMapFromPerforceServer(self):
907 if self.userMapFromPerforceServer:
911 for output in p4CmdList("users"):
912 if not output.has_key("User"):
914 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
918 for (key, val) in self.users.items():
919 s += "%s\t%s\n" % (key, val)
921 open(self.getUserCacheFilename(), "wb").write(s)
922 self.userMapFromPerforceServer = True
924 def loadUserMapFromCache(self):
926 self.userMapFromPerforceServer = False
928 cache = open(self.getUserCacheFilename(), "rb")
929 lines = cache.readlines()
932 entry = line.strip().split("\t")
933 self.users[entry[0]] = entry[1]
935 self.getUserMapFromPerforceServer()
940 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
941 if len(l) > 0 and not self.silent:
942 print "Finding files belonging to labels in %s" % `self.depotPath`
945 label = output["label"]
949 print "Querying files for label %s" % label
950 for file in p4CmdList("files "
951 + ' '.join (["%s...@%s" % (p, label)
952 for p in self.depotPaths])):
953 revisions[file["depotFile"]] = file["rev"]
954 change = int(file["change"])
955 if change > newestChange:
956 newestChange = change
958 self.labels[newestChange] = [output, revisions]
961 print "Label changes: %s" % self.labels.keys()
963 def guessProjectName(self):
964 for p in self.depotPaths:
967 p = p[p.strip().rfind("/") + 1:]
968 if not p.endswith("/"):
972 def getBranchMapping(self):
973 lostAndFoundBranches = set()
975 for info in p4CmdList("branches"):
976 details = p4Cmd("branch -o %s" % info["branch"])
978 while details.has_key("View%s" % viewIdx):
979 paths = details["View%s" % viewIdx].split(" ")
980 viewIdx = viewIdx + 1
981 # require standard //depot/foo/... //depot/bar/... mapping
982 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
985 destination = paths[1]
987 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
988 source = source[len(self.depotPaths[0]):-4]
989 destination = destination[len(self.depotPaths[0]):-4]
991 if destination in self.knownBranches:
993 print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
994 print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
997 self.knownBranches[destination] = source
999 lostAndFoundBranches.discard(destination)
1001 if source not in self.knownBranches:
1002 lostAndFoundBranches.add(source)
1005 for branch in lostAndFoundBranches:
1006 self.knownBranches[branch] = branch
1008 def listExistingP4GitBranches(self):
1009 self.p4BranchesInGit = []
1011 cmdline = "git rev-parse --symbolic "
1012 if self.importIntoRemotes:
1013 cmdline += " --remotes"
1015 cmdline += " --branches"
1017 for line in read_pipe_lines(cmdline):
1020 ## only import to p4/
1021 if not line.startswith('p4/') or line == "p4/HEAD":
1026 branch = re.sub ("^p4/", "", line)
1028 self.p4BranchesInGit.append(branch)
1029 self.initialParents[self.refPrefix + branch] = parseRevision(line)
1031 def createOrUpdateBranchesFromOrigin(self):
1033 print ("Creating/updating branch(es) in %s based on origin branch(es)"
1036 originPrefix = "origin/p4/"
1038 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
1040 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
1043 headName = line[len(originPrefix):]
1044 remoteHead = self.refPrefix + headName
1047 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
1048 if (not original.has_key('depot-paths')
1049 or not original.has_key('change')):
1053 if not gitBranchExists(remoteHead):
1055 print "creating %s" % remoteHead
1058 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
1059 if settings.has_key('change') > 0:
1060 if settings['depot-paths'] == original['depot-paths']:
1061 originP4Change = int(original['change'])
1062 p4Change = int(settings['change'])
1063 if originP4Change > p4Change:
1064 print ("%s (%s) is newer than %s (%s). "
1065 "Updating p4 branch from origin."
1066 % (originHead, originP4Change,
1067 remoteHead, p4Change))
1070 print ("Ignoring: %s was imported from %s while "
1071 "%s was imported from %s"
1072 % (originHead, ','.join(original['depot-paths']),
1073 remoteHead, ','.join(settings['depot-paths'])))
1076 system("git update-ref %s %s" % (remoteHead, originHead))
1078 def updateOptionDict(self, d):
1080 if self.keepRepoPath:
1081 option_keys['keepRepoPath'] = 1
1083 d["options"] = ' '.join(sorted(option_keys.keys()))
1085 def readOptions(self, d):
1086 self.keepRepoPath = (d.has_key('options')
1087 and ('keepRepoPath' in d['options']))
1089 def run(self, args):
1090 self.depotPaths = []
1091 self.changeRange = ""
1092 self.initialParent = ""
1093 self.previousDepotPaths = []
1095 # map from branch depot path to parent branch
1096 self.knownBranches = {}
1097 self.initialParents = {}
1098 self.hasOrigin = gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
1099 if not self.syncWithOrigin:
1100 self.hasOrigin = False
1102 if self.importIntoRemotes:
1103 self.refPrefix = "refs/remotes/p4/"
1105 self.refPrefix = "refs/heads/p4/"
1107 if self.syncWithOrigin and self.hasOrigin:
1109 print "Syncing with origin first by calling git fetch origin"
1110 system("git fetch origin")
1112 if len(self.branch) == 0:
1113 self.branch = self.refPrefix + "master"
1114 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1115 system("git update-ref %s refs/heads/p4" % self.branch)
1116 system("git branch -D p4");
1117 # create it /after/ importing, when master exists
1118 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1119 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1121 # TODO: should always look at previous commits,
1122 # merge with previous imports, if possible.
1125 self.createOrUpdateBranchesFromOrigin()
1126 self.listExistingP4GitBranches()
1128 if len(self.p4BranchesInGit) > 1:
1130 print "Importing from/into multiple branches"
1131 self.detectBranches = True
1134 print "branches: %s" % self.p4BranchesInGit
1137 for branch in self.p4BranchesInGit:
1138 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
1140 settings = extractSettingsGitLog(logMsg)
1142 self.readOptions(settings)
1143 if (settings.has_key('depot-paths')
1144 and settings.has_key ('change')):
1145 change = int(settings['change']) + 1
1146 p4Change = max(p4Change, change)
1148 depotPaths = sorted(settings['depot-paths'])
1149 if self.previousDepotPaths == []:
1150 self.previousDepotPaths = depotPaths
1153 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1154 for i in range(0, min(len(cur), len(prev))):
1155 if cur[i] <> prev[i]:
1159 paths.append (cur[:i + 1])
1161 self.previousDepotPaths = paths
1164 self.depotPaths = sorted(self.previousDepotPaths)
1165 self.changeRange = "@%s,#head" % p4Change
1166 if not self.detectBranches:
1167 self.initialParent = parseRevision(self.branch)
1168 if not self.silent and not self.detectBranches:
1169 print "Performing incremental import into %s git branch" % self.branch
1171 if not self.branch.startswith("refs/"):
1172 self.branch = "refs/heads/" + self.branch
1174 if len(args) == 0 and self.depotPaths:
1176 print "Depot paths: %s" % ' '.join(self.depotPaths)
1178 if self.depotPaths and self.depotPaths != args:
1179 print ("previous import used depot path %s and now %s was specified. "
1180 "This doesn't work!" % (' '.join (self.depotPaths),
1184 self.depotPaths = sorted(args)
1190 for p in self.depotPaths:
1191 if p.find("@") != -1:
1192 atIdx = p.index("@")
1193 self.changeRange = p[atIdx:]
1194 if self.changeRange == "@all":
1195 self.changeRange = ""
1196 elif ',' not in self.changeRange:
1197 self.revision = self.changeRange
1198 self.changeRange = ""
1200 elif p.find("#") != -1:
1201 hashIdx = p.index("#")
1202 self.revision = p[hashIdx:]
1204 elif self.previousDepotPaths == []:
1205 self.revision = "#head"
1207 p = re.sub ("\.\.\.$", "", p)
1208 if not p.endswith("/"):
1213 self.depotPaths = newPaths
1216 self.loadUserMapFromCache()
1218 if self.detectLabels:
1221 if self.detectBranches:
1222 ## FIXME - what's a P4 projectName ?
1223 self.projectName = self.guessProjectName()
1225 if not self.hasOrigin:
1226 self.getBranchMapping();
1228 print "p4-git branches: %s" % self.p4BranchesInGit
1229 print "initial parents: %s" % self.initialParents
1230 for b in self.p4BranchesInGit:
1234 b = b[len(self.projectName):]
1235 self.createdBranches.add(b)
1237 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1239 importProcess = subprocess.Popen(["git", "fast-import"],
1240 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1241 stderr=subprocess.PIPE);
1242 self.gitOutput = importProcess.stdout
1243 self.gitStream = importProcess.stdin
1244 self.gitError = importProcess.stderr
1247 print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), self.revision, self.branch)
1249 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1250 details["desc"] = ("Initial import of %s from the state at revision %s"
1251 % (' '.join(self.depotPaths), self.revision))
1252 details["change"] = self.revision
1256 for info in p4CmdList("files "
1257 + ' '.join(["%s...%s"
1258 % (p, self.revision)
1259 for p in self.depotPaths])):
1261 if info['code'] == 'error':
1262 sys.stderr.write("p4 returned an error: %s\n"
1267 change = int(info["change"])
1268 if change > newestRevision:
1269 newestRevision = change
1271 if info["action"] == "delete":
1272 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1273 #fileCnt = fileCnt + 1
1276 for prop in ["depotFile", "rev", "action", "type" ]:
1277 details["%s%s" % (prop, fileCnt)] = info[prop]
1279 fileCnt = fileCnt + 1
1281 details["change"] = newestRevision
1282 self.updateOptionDict(details)
1284 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1286 print "IO error with git fast-import. Is your git version recent enough?"
1287 print self.gitError.read()
1292 if len(self.changesFile) > 0:
1293 output = open(self.changesFile).readlines()
1296 changeSet.add(int(line))
1298 for change in changeSet:
1299 changes.append(change)
1304 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1306 assert self.depotPaths
1307 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1308 for p in self.depotPaths]))
1311 changeNum = line.split(" ")[1]
1312 changes.append(changeNum)
1316 if len(self.maxChanges) > 0:
1317 changes = changes[0:min(int(self.maxChanges), len(changes))]
1319 if len(changes) == 0:
1321 print "No changes to import!"
1324 if not self.silent and not self.detectBranches:
1325 print "Import destination: %s" % self.branch
1327 self.updatedBranches = set()
1330 for change in changes:
1331 description = p4Cmd("describe %s" % change)
1332 self.updateOptionDict(description)
1335 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1340 if self.detectBranches:
1341 branches = self.splitFilesIntoBranches(description)
1342 for branch in branches.keys():
1344 branchPrefix = self.depotPaths[0] + branch + "/"
1348 filesForCommit = branches[branch]
1351 print "branch is %s" % branch
1353 self.updatedBranches.add(branch)
1355 if branch not in self.createdBranches:
1356 self.createdBranches.add(branch)
1357 parent = self.knownBranches[branch]
1358 if parent == branch:
1361 print "parent determined through known branches: %s" % parent
1363 # main branch? use master
1364 if branch == "main":
1369 branch = self.projectName + branch
1371 if parent == "main":
1373 elif len(parent) > 0:
1375 parent = self.projectName + parent
1377 branch = self.refPrefix + branch
1379 parent = self.refPrefix + parent
1382 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1384 if len(parent) == 0 and branch in self.initialParents:
1385 parent = self.initialParents[branch]
1386 del self.initialParents[branch]
1388 self.commit(description, filesForCommit, branch, [branchPrefix], parent)
1390 files = self.extractFilesFromCommit(description)
1391 self.commit(description, files, self.branch, self.depotPaths,
1393 self.initialParent = ""
1395 print self.gitError.read()
1400 if len(self.updatedBranches) > 0:
1401 sys.stdout.write("Updated branches: ")
1402 for b in self.updatedBranches:
1403 sys.stdout.write("%s " % b)
1404 sys.stdout.write("\n")
1407 self.gitStream.close()
1408 if importProcess.wait() != 0:
1409 die("fast-import failed: %s" % self.gitError.read())
1410 self.gitOutput.close()
1411 self.gitError.close()
1415 class P4Rebase(Command):
1417 Command.__init__(self)
1419 self.description = ("Fetches the latest revision from perforce and "
1420 + "rebases the current work (branch) against it")
1421 self.verbose = False
1423 def run(self, args):
1427 [upstream, settings] = findUpstreamBranchPoint()
1428 if len(upstream) == 0:
1429 die("Cannot find upstream branchpoint for rebase")
1431 # the branchpoint may be p4/foo~3, so strip off the parent
1432 upstream = re.sub("~[0-9]+$", "", upstream)
1434 print "Rebasing the current branch onto %s" % upstream
1435 oldHead = read_pipe("git rev-parse HEAD").strip()
1436 system("git rebase %s" % upstream)
1437 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1440 class P4Clone(P4Sync):
1442 P4Sync.__init__(self)
1443 self.description = "Creates a new git repository and imports from Perforce into it"
1444 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1445 self.options.append(
1446 optparse.make_option("--destination", dest="cloneDestination",
1447 action='store', default=None,
1448 help="where to leave result of the clone"))
1449 self.cloneDestination = None
1450 self.needsGit = False
1452 def defaultDestination(self, args):
1453 ## TODO: use common prefix of args?
1455 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1456 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1457 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1458 depotDir = re.sub(r"/$", "", depotDir)
1459 return os.path.split(depotDir)[1]
1461 def run(self, args):
1465 if self.keepRepoPath and not self.cloneDestination:
1466 sys.stderr.write("Must specify destination for --keep-path\n")
1471 if not self.cloneDestination and len(depotPaths) > 1:
1472 self.cloneDestination = depotPaths[-1]
1473 depotPaths = depotPaths[:-1]
1475 for p in depotPaths:
1476 if not p.startswith("//"):
1479 if not self.cloneDestination:
1480 self.cloneDestination = self.defaultDestination(args)
1482 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1483 if not os.path.exists(self.cloneDestination):
1484 os.makedirs(self.cloneDestination)
1485 os.chdir(self.cloneDestination)
1487 self.gitdir = os.getcwd() + "/.git"
1488 if not P4Sync.run(self, depotPaths):
1490 if self.branch != "master":
1491 if gitBranchExists("refs/remotes/p4/master"):
1492 system("git branch master refs/remotes/p4/master")
1493 system("git checkout -f")
1495 print "Could not detect main branch. No checkout/master branch created."
1499 class P4Branches(Command):
1501 Command.__init__(self)
1503 self.description = ("Shows the git branches that hold imports and their "
1504 + "corresponding perforce depot paths")
1505 self.verbose = False
1507 def run(self, args):
1508 cmdline = "git rev-parse --symbolic "
1509 cmdline += " --remotes"
1511 for line in read_pipe_lines(cmdline):
1514 if not line.startswith('p4/') or line == "p4/HEAD":
1518 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
1519 settings = extractSettingsGitLog(log)
1521 print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
1524 class HelpFormatter(optparse.IndentedHelpFormatter):
1526 optparse.IndentedHelpFormatter.__init__(self)
1528 def format_description(self, description):
1530 return description + "\n"
1534 def printUsage(commands):
1535 print "usage: %s <command> [options]" % sys.argv[0]
1537 print "valid commands: %s" % ", ".join(commands)
1539 print "Try %s <command> --help for command specific help." % sys.argv[0]
1544 "submit" : P4Submit,
1546 "rebase" : P4Rebase,
1548 "rollback" : P4RollBack,
1549 "branches" : P4Branches
1554 if len(sys.argv[1:]) == 0:
1555 printUsage(commands.keys())
1559 cmdName = sys.argv[1]
1561 klass = commands[cmdName]
1564 print "unknown command %s" % cmdName
1566 printUsage(commands.keys())
1569 options = cmd.options
1570 cmd.gitdir = os.environ.get("GIT_DIR", None)
1574 if len(options) > 0:
1575 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1577 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1579 description = cmd.description,
1580 formatter = HelpFormatter())
1582 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1584 verbose = cmd.verbose
1586 if cmd.gitdir == None:
1587 cmd.gitdir = os.path.abspath(".git")
1588 if not isValidGitDir(cmd.gitdir):
1589 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1590 if os.path.exists(cmd.gitdir):
1591 cdup = read_pipe("git rev-parse --show-cdup").strip()
1595 if not isValidGitDir(cmd.gitdir):
1596 if isValidGitDir(cmd.gitdir + "/.git"):
1597 cmd.gitdir += "/.git"
1599 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1601 os.environ["GIT_DIR"] = cmd.gitdir
1603 if not cmd.run(args):
1607 if __name__ == '__main__':