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
17 gitdir = os.environ.get("GIT_DIR", "")
20 def write_pipe(c, str):
22 sys.stderr.write('writing pipe: %s\n' % c)
24 pipe = os.popen(c, 'w')
27 sys.stderr.write('Command %s failed\n' % c)
32 def read_pipe(c, ignore_error=False):
34 sys.stderr.write('reading pipe: %s\n' % c)
36 pipe = os.popen(c, 'rb')
38 if pipe.close() and not ignore_error:
39 sys.stderr.write('Command %s failed\n' % c)
45 def read_pipe_lines(c):
47 sys.stderr.write('reading pipe: %s\n' % c)
48 ## todo: check return status
49 pipe = os.popen(c, 'rb')
50 val = pipe.readlines()
52 sys.stderr.write('Command %s failed\n' % c)
59 sys.stderr.write("executing %s" % cmd)
60 if os.system(cmd) != 0:
61 die("command failed: %s" % cmd)
64 cmd = "p4 -G %s" % cmd
65 pipe = os.popen(cmd, "rb")
70 entry = marshal.load(pipe)
74 exitCode = pipe.close()
77 entry["p4ExitCode"] = exitCode
89 def p4Where(depotPath):
90 if not depotPath.endswith("/"):
92 output = p4Cmd("where %s..." % depotPath)
93 if output["code"] == "error":
97 clientPath = output.get("path")
98 elif "data" in output:
99 data = output.get("data")
100 lastSpace = data.rfind(" ")
101 clientPath = data[lastSpace + 1:]
103 if clientPath.endswith("..."):
104 clientPath = clientPath[:-3]
108 sys.stderr.write(msg + "\n")
111 def currentGitBranch():
112 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
114 def isValidGitDir(path):
115 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
119 def parseRevision(ref):
120 return read_pipe("git rev-parse %s" % ref).strip()
122 def extractLogMessageFromGitCommit(commit):
125 ## fixme: title is first line of commit, not 1st paragraph.
127 for log in read_pipe_lines("git cat-file commit %s" % commit):
136 def extractDepotPathsAndChangeFromGitLog(log):
138 for line in log.split("\n"):
140 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
144 assignments = m.group(1).split (':')
145 for a in assignments:
147 key = vals[0].strip()
148 val = ('='.join (vals[1:])).strip()
149 if val.endswith ('\"') and val.startswith('"'):
154 paths = values.get("depot-path").split(',')
155 return paths, values.get("change")
157 def gitBranchExists(branch):
158 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
159 return proc.wait() == 0;
162 return read_pipe("git config %s" % key, ignore_error=True).strip()
166 self.usage = "usage: %prog [options]"
169 class P4Debug(Command):
171 Command.__init__(self)
173 optparse.make_option("--verbose", dest="verbose", action="store_true"),
175 self.description = "A tool to debug the output of p4 -G."
176 self.needsGit = False
179 for output in p4CmdList(" ".join(args)):
183 class P4RollBack(Command):
185 Command.__init__(self)
187 optparse.make_option("--verbose", dest="verbose", action="store_true"),
188 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
190 self.description = "A tool to debug the multi-branch import. Don't use :)"
192 self.rollbackLocalBranches = False
197 maxChange = int(args[0])
199 if "p4ExitCode" in p4Cmd("changes -m 1"):
200 die("Problems executing p4");
202 if self.rollbackLocalBranches:
203 refPrefix = "refs/heads/"
204 lines = read_pipe_lines("git rev-parse --symbolic --branches")
206 refPrefix = "refs/remotes/"
207 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
210 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
212 ref = refPrefix + line
213 log = extractLogMessageFromGitCommit(ref)
214 depotPaths, change = extractDepotPathsAndChangeFromGitLog(log)
217 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
218 for p in depotPaths]))) == 0:
219 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
220 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
223 while len(change) > 0 and int(change) > maxChange:
226 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
227 system("git update-ref %s \"%s^\"" % (ref, ref))
228 log = extractLogMessageFromGitCommit(ref)
229 depotPaths, change = extractDepotPathsAndChangeFromGitLog(log)
232 print "%s rewound to %s" % (ref, change)
236 class P4Submit(Command):
238 Command.__init__(self)
240 optparse.make_option("--continue", action="store_false", dest="firstTime"),
241 optparse.make_option("--verbose", dest="verbose", action="store_true"),
242 optparse.make_option("--origin", dest="origin"),
243 optparse.make_option("--reset", action="store_true", dest="reset"),
244 optparse.make_option("--log-substitutions", dest="substFile"),
245 optparse.make_option("--dry-run", action="store_true"),
246 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
247 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
249 self.description = "Submit changes from git to the perforce depot."
250 self.usage += " [name of git branch to submit into perforce depot]"
251 self.firstTime = True
253 self.interactive = True
256 self.firstTime = True
258 self.directSubmit = False
259 self.trustMeLikeAFool = False
261 self.logSubstitutions = {}
262 self.logSubstitutions["<enter description here>"] = "%log%"
263 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
266 if len(p4CmdList("opened ...")) > 0:
267 die("You have files opened with perforce! Close them before starting the sync.")
270 if len(self.config) > 0 and not self.reset:
271 die("Cannot start sync. Previous sync config found at %s\n"
272 "If you want to start submitting again from scratch "
273 "maybe you want to call git-p4 submit --reset" % self.configFile)
276 if self.directSubmit:
279 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
280 commits.append(line.strip())
283 self.config["commits"] = commits
285 def prepareLogMessage(self, template, message):
288 for line in template.split("\n"):
289 if line.startswith("#"):
290 result += line + "\n"
294 for key in self.logSubstitutions.keys():
295 if line.find(key) != -1:
296 value = self.logSubstitutions[key]
297 value = value.replace("%log%", message)
298 if value != "@remove@":
299 result += line.replace(key, value) + "\n"
304 result += line + "\n"
308 def applyCommit(self, id):
309 if self.directSubmit:
310 print "Applying local change in working directory/index"
311 diff = self.diffStatus
313 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
314 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
316 filesToDelete = set()
320 path = line[1:].strip()
322 system("p4 edit \"%s\"" % path)
323 editedFiles.add(path)
324 elif modifier == "A":
326 if path in filesToDelete:
327 filesToDelete.remove(path)
328 elif modifier == "D":
329 filesToDelete.add(path)
330 if path in filesToAdd:
331 filesToAdd.remove(path)
333 die("unknown modifier %s for %s" % (modifier, path))
335 if self.directSubmit:
336 diffcmd = "cat \"%s\"" % self.diffFile
338 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
339 patchcmd = diffcmd + " | git apply "
340 tryPatchCmd = patchcmd + "--check -"
341 applyPatchCmd = patchcmd + "--check --apply -"
343 if os.system(tryPatchCmd) != 0:
344 print "Unfortunately applying the change failed!"
345 print "What do you want to do?"
347 while response != "s" and response != "a" and response != "w":
348 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
349 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
351 print "Skipping! Good luck with the next patches..."
353 elif response == "a":
354 os.system(applyPatchCmd)
355 if len(filesToAdd) > 0:
356 print "You may also want to call p4 add on the following files:"
357 print " ".join(filesToAdd)
358 if len(filesToDelete):
359 print "The following files should be scheduled for deletion with p4 delete:"
360 print " ".join(filesToDelete)
361 die("Please resolve and submit the conflict manually and "
362 + "continue afterwards with git-p4 submit --continue")
363 elif response == "w":
364 system(diffcmd + " > patch.txt")
365 print "Patch saved to patch.txt in %s !" % self.clientPath
366 die("Please resolve and submit the conflict manually and "
367 "continue afterwards with git-p4 submit --continue")
369 system(applyPatchCmd)
372 system("p4 add %s" % f)
373 for f in filesToDelete:
374 system("p4 revert %s" % f)
375 system("p4 delete %s" % f)
378 if not self.directSubmit:
379 logMessage = extractLogMessageFromGitCommit(id)
380 logMessage = logMessage.replace("\n", "\n\t")
381 logMessage = logMessage.strip()
383 template = read_pipe("p4 change -o")
386 submitTemplate = self.prepareLogMessage(template, logMessage)
387 diff = read_pipe("p4 diff -du ...")
389 for newFile in filesToAdd:
390 diff += "==== new file ====\n"
391 diff += "--- /dev/null\n"
392 diff += "+++ %s\n" % newFile
393 f = open(newFile, "r")
394 for line in f.readlines():
398 separatorLine = "######## everything below this line is just the diff #######"
399 if platform.system() == "Windows":
400 separatorLine += "\r"
401 separatorLine += "\n"
404 if self.trustMeLikeAFool:
407 firstIteration = True
408 while response == "e":
409 if not firstIteration:
410 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
411 firstIteration = False
413 [handle, fileName] = tempfile.mkstemp()
414 tmpFile = os.fdopen(handle, "w+")
415 tmpFile.write(submitTemplate + separatorLine + diff)
418 if platform.system() == "Windows":
419 defaultEditor = "notepad"
420 editor = os.environ.get("EDITOR", defaultEditor);
421 system(editor + " " + fileName)
422 tmpFile = open(fileName, "rb")
423 message = tmpFile.read()
426 submitTemplate = message[:message.index(separatorLine)]
428 if response == "y" or response == "yes":
431 raw_input("Press return to continue...")
433 if self.directSubmit:
434 print "Submitting to git first"
435 os.chdir(self.oldWorkingDirectory)
436 write_pipe("git commit -a -F -", submitTemplate)
437 os.chdir(self.clientPath)
439 write_pipe("p4 submit -i", submitTemplate)
440 elif response == "s":
441 for f in editedFiles:
442 system("p4 revert \"%s\"" % f);
444 system("p4 revert \"%s\"" % f);
446 for f in filesToDelete:
447 system("p4 delete \"%s\"" % f);
450 print "Not submitting!"
451 self.interactive = False
453 fileName = "submit.txt"
454 file = open(fileName, "w+")
455 file.write(self.prepareLogMessage(template, logMessage))
457 print ("Perforce submit template written as %s. "
458 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
459 % (fileName, fileName))
463 # make gitdir absolute so we can cd out into the perforce checkout
464 gitdir = os.path.abspath(gitdir)
465 os.environ["GIT_DIR"] = gitdir
468 self.master = currentGitBranch()
469 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
470 die("Detecting current git branch failed!")
472 self.master = args[0]
477 if gitBranchExists("p4"):
478 [depotPaths, dummy] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
479 if len(depotPath) == 0 and gitBranchExists("origin"):
480 [depotPaths, dummy] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
482 if len(depotPath) == 0:
483 print "Internal error: cannot locate perforce depot path from existing branches"
486 self.clientPath = p4Where(depotPath)
488 if len(self.clientPath) == 0:
489 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
492 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
493 self.oldWorkingDirectory = os.getcwd()
495 if self.directSubmit:
496 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
497 if len(self.diffStatus) == 0:
498 print "No changes in working directory to submit."
500 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
501 self.diffFile = gitdir + "/p4-git-diff"
502 f = open(self.diffFile, "wb")
506 os.chdir(self.clientPath)
507 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
508 if response == "y" or response == "yes":
509 system("p4 sync ...")
511 if len(self.origin) == 0:
512 if gitBranchExists("p4"):
515 self.origin = "origin"
518 self.firstTime = True
520 if len(self.substFile) > 0:
521 for line in open(self.substFile, "r").readlines():
522 tokens = line.strip().split("=")
523 self.logSubstitutions[tokens[0]] = tokens[1]
526 self.configFile = gitdir + "/p4-git-sync.cfg"
527 self.config = shelve.open(self.configFile, writeback=True)
532 commits = self.config.get("commits", [])
534 while len(commits) > 0:
535 self.firstTime = False
537 commits = commits[1:]
538 self.config["commits"] = commits
539 self.applyCommit(commit)
540 if not self.interactive:
545 if self.directSubmit:
546 os.remove(self.diffFile)
548 if len(commits) == 0:
550 print "No changes found to apply between %s and current HEAD" % self.origin
552 print "All changes applied!"
553 os.chdir(self.oldWorkingDirectory)
554 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
555 if response == "y" or response == "yes":
558 os.remove(self.configFile)
562 class P4Sync(Command):
564 Command.__init__(self)
566 optparse.make_option("--branch", dest="branch"),
567 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
568 optparse.make_option("--changesfile", dest="changesFile"),
569 optparse.make_option("--silent", dest="silent", action="store_true"),
570 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
571 optparse.make_option("--verbose", dest="verbose", action="store_true"),
572 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
573 optparse.make_option("--max-changes", dest="maxChanges"),
574 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true')
576 self.description = """Imports from Perforce into a git repository.\n
578 //depot/my/project/ -- to import the current head
579 //depot/my/project/@all -- to import everything
580 //depot/my/project/@1,6 -- to import only from revision 1 to 6
582 (a ... is not needed in the path p4 specification, it's added implicitly)"""
584 self.usage += " //depot/path[@revRange]"
586 self.createdBranches = Set()
587 self.committedChanges = Set()
589 self.detectBranches = False
590 self.detectLabels = False
591 self.changesFile = ""
592 self.syncWithOrigin = True
594 self.importIntoRemotes = True
596 self.isWindows = (platform.system() == "Windows")
597 self.keepRepoPath = False
598 self.depotPaths = None
600 if gitConfig("git-p4.syncFromOrigin") == "false":
601 self.syncWithOrigin = False
603 def p4File(self, depotPath):
604 return read_pipe("p4 print -q \"%s\"" % depotPath)
606 def extractFilesFromCommit(self, commit):
609 while commit.has_key("depotFile%s" % fnum):
610 path = commit["depotFile%s" % fnum]
612 found = [p for p in self.depotPaths
613 if path.startswith (p)]
620 file["rev"] = commit["rev%s" % fnum]
621 file["action"] = commit["action%s" % fnum]
622 file["type"] = commit["type%s" % fnum]
627 def stripRepoPath(self, path, prefixes):
628 if self.keepRepoPath:
629 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
632 if path.startswith(p):
637 def splitFilesIntoBranches(self, commit):
640 while commit.has_key("depotFile%s" % fnum):
641 path = commit["depotFile%s" % fnum]
642 found = [p for p in self.depotPaths
643 if path.startswith (p)]
650 file["rev"] = commit["rev%s" % fnum]
651 file["action"] = commit["action%s" % fnum]
652 file["type"] = commit["type%s" % fnum]
655 relPath = self.stripRepoPath(path, self.depotPaths)
657 for branch in self.knownBranches.keys():
659 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
660 if relPath.startswith(branch + "/"):
661 if branch not in branches:
662 branches[branch] = []
663 branches[branch].append(file)
667 def commit(self, details, files, branch, branchPrefixes, parent = ""):
668 epoch = details["time"]
669 author = details["user"]
672 print "commit into %s" % branch
674 self.gitStream.write("commit %s\n" % branch)
675 # gitStream.write("mark :%s\n" % details["change"])
676 self.committedChanges.add(int(details["change"]))
678 if author not in self.users:
679 self.getUserMapFromPerforceServer()
680 if author in self.users:
681 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
683 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
685 self.gitStream.write("committer %s\n" % committer)
687 self.gitStream.write("data <<EOT\n")
688 self.gitStream.write(details["desc"])
689 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n"
690 % (','.join (branchPrefixes), details["change"]))
691 self.gitStream.write("EOT\n\n")
695 print "parent %s" % parent
696 self.gitStream.write("from %s\n" % parent)
702 if not [p for p in branchPrefixes if path.startswith(p)]:
705 depotPath = path + "#" + rev
706 relPath = self.stripRepoPath(path, branchPrefixes)
707 action = file["action"]
709 if file["type"] == "apple":
710 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
713 if action == "delete":
714 self.gitStream.write("D %s\n" % relPath)
717 if file["type"].startswith("x"):
720 data = self.p4File(depotPath)
722 if self.isWindows and file["type"].endswith("text"):
723 data = data.replace("\r\n", "\n")
725 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
726 self.gitStream.write("data %s\n" % len(data))
727 self.gitStream.write(data)
728 self.gitStream.write("\n")
730 self.gitStream.write("\n")
732 change = int(details["change"])
734 if self.labels.has_key(change):
735 label = self.labels[change]
736 labelDetails = label[0]
737 labelRevisions = label[1]
739 print "Change %s is labelled %s" % (change, labelDetails)
741 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
742 for p in branchPrefixes]))
744 if len(files) == len(labelRevisions):
748 if info["action"] == "delete":
750 cleanedFiles[info["depotFile"]] = info["rev"]
752 if cleanedFiles == labelRevisions:
753 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
754 self.gitStream.write("from %s\n" % branch)
756 owner = labelDetails["Owner"]
758 if author in self.users:
759 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
761 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
762 self.gitStream.write("tagger %s\n" % tagger)
763 self.gitStream.write("data <<EOT\n")
764 self.gitStream.write(labelDetails["Description"])
765 self.gitStream.write("EOT\n\n")
769 print ("Tag %s does not match with change %s: files do not match."
770 % (labelDetails["label"], change))
774 print ("Tag %s does not match with change %s: file count is different."
775 % (labelDetails["label"], change))
777 def getUserMapFromPerforceServer(self):
778 if self.userMapFromPerforceServer:
782 for output in p4CmdList("users"):
783 if not output.has_key("User"):
785 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
787 cache = open(gitdir + "/p4-usercache.txt", "wb")
788 for user in self.users.keys():
789 cache.write("%s\t%s\n" % (user, self.users[user]))
791 self.userMapFromPerforceServer = True
793 def loadUserMapFromCache(self):
795 self.userMapFromPerforceServer = False
797 cache = open(gitdir + "/p4-usercache.txt", "rb")
798 lines = cache.readlines()
801 entry = line.strip().split("\t")
802 self.users[entry[0]] = entry[1]
804 self.getUserMapFromPerforceServer()
809 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
810 if len(l) > 0 and not self.silent:
811 print "Finding files belonging to labels in %s" % `self.depotPath`
814 label = output["label"]
818 print "Querying files for label %s" % label
819 for file in p4CmdList("files "
820 + ' '.join (["%s...@%s" % (p, label)
821 for p in self.depotPaths])):
822 revisions[file["depotFile"]] = file["rev"]
823 change = int(file["change"])
824 if change > newestChange:
825 newestChange = change
827 self.labels[newestChange] = [output, revisions]
830 print "Label changes: %s" % self.labels.keys()
832 def getBranchMapping(self):
834 ## FIXME - what's a P4 projectName ?
835 self.projectName = self.depotPath[self.depotPath.strip().rfind("/") + 1:]
837 for info in p4CmdList("branches"):
838 details = p4Cmd("branch -o %s" % info["branch"])
840 while details.has_key("View%s" % viewIdx):
841 paths = details["View%s" % viewIdx].split(" ")
842 viewIdx = viewIdx + 1
843 # require standard //depot/foo/... //depot/bar/... mapping
844 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
847 destination = paths[1]
848 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
849 source = source[len(self.depotPath):-4]
850 destination = destination[len(self.depotPath):-4]
851 if destination not in self.knownBranches:
852 self.knownBranches[destination] = source
853 if source not in self.knownBranches:
854 self.knownBranches[source] = source
856 def listExistingP4GitBranches(self):
857 self.p4BranchesInGit = []
859 cmdline = "git rev-parse --symbolic "
860 if self.importIntoRemotes:
861 cmdline += " --remotes"
863 cmdline += " --branches"
865 for line in read_pipe_lines(cmdline):
867 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
870 if self.importIntoRemotes:
872 branch = re.sub ("^p4/", "", line)
874 self.p4BranchesInGit.append(branch)
875 self.initialParents[self.refPrefix + branch] = parseRevision(line)
877 def createOrUpdateBranchesFromOrigin(self):
879 print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
881 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
883 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
886 headName = line[len("origin/")]
887 remoteHead = self.refPrefix + headName
888 originHead = "origin/" + headName
890 [originPreviousDepotPaths, originP4Change] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead))
891 if len(originPreviousDepotPaths) == 0 or len(originP4Change) == 0:
895 if not gitBranchExists(remoteHead):
897 print "creating %s" % remoteHead
900 [p4PreviousDepotPaths, p4Change] = extractDepotPathsAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead))
901 if len(p4Change) > 0:
902 if originPreviousDepotPaths == p4PreviousDepotPaths:
903 originP4Change = int(originP4Change)
904 p4Change = int(p4Change)
905 if originP4Change > p4Change:
906 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead, originP4Change, remoteHead, p4Change)
909 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead, originPreviousDepotPaths, remoteHead, p4PreviousDepotPaths)
912 system("git update-ref %s %s" % (remoteHead, originHead))
917 self.changeRange = ""
918 self.initialParent = ""
919 self.previousDepotPaths = []
921 # map from branch depot path to parent branch
922 self.knownBranches = {}
923 self.initialParents = {}
924 self.hasOrigin = gitBranchExists("origin")
926 if self.importIntoRemotes:
927 self.refPrefix = "refs/remotes/p4/"
929 self.refPrefix = "refs/heads/"
931 if self.syncWithOrigin and self.hasOrigin:
933 print "Syncing with origin first by calling git fetch origin"
934 system("git fetch origin")
936 if len(self.branch) == 0:
937 self.branch = self.refPrefix + "master"
938 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
939 system("git update-ref %s refs/heads/p4" % self.branch)
940 system("git branch -D p4");
941 # create it /after/ importing, when master exists
942 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
943 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
947 self.createOrUpdateBranchesFromOrigin()
948 self.listExistingP4GitBranches()
950 if len(self.p4BranchesInGit) > 1:
952 print "Importing from/into multiple branches"
953 self.detectBranches = True
956 print "branches: %s" % self.p4BranchesInGit
959 for branch in self.p4BranchesInGit:
960 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
961 (depotPaths, change) = extractDepotPathsAndChangeFromGitLog(logMsg)
964 print "path %s change %s" % (','.join(depotPaths), change)
966 if len(depotPaths) > 0 and len(change) > 0:
967 change = int(change) + 1
968 p4Change = max(p4Change, change)
970 if len(self.previousDepotPaths) == 0:
971 self.previousDepotPaths = depotPaths
975 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
976 for i in range(0, max(len(cur), len(prev))):
977 if cur[i] <> prev[i]:
980 paths.append (cur[:i])
982 self.previousDepotPaths = paths
985 self.depotPaths = self.previousDepotPaths
986 self.changeRange = "@%s,#head" % p4Change
987 self.initialParent = parseRevision(self.branch)
988 if not self.silent and not self.detectBranches:
989 print "Performing incremental import into %s git branch" % self.branch
991 if not self.branch.startswith("refs/"):
992 self.branch = "refs/heads/" + self.branch
994 if len(args) == 0 and self.depotPaths:
996 print "Depot paths: %s" % ' '.join(self.depotPaths)
998 if self.depotPaths and self.depotPaths != args:
999 print ("previous import used depot path %s and now %s was specified. "
1000 "This doesn't work!" % (' '.join (self.depotPaths),
1004 self.depotPaths = args
1010 for p in self.depotPaths:
1011 if p.find("@") != -1:
1012 atIdx = p.index("@")
1013 self.changeRange = p[atIdx:]
1014 if self.changeRange == "@all":
1015 self.changeRange = ""
1016 elif self.changeRange.find(",") == -1:
1017 self.revision = self.changeRange
1018 self.changeRange = ""
1020 elif p.find("#") != -1:
1021 hashIdx = p.index("#")
1022 self.revision = p[hashIdx:]
1024 elif self.previousDepotPaths == []:
1025 self.revision = "#head"
1027 p = re.sub ("\.\.\.$", "", p)
1028 if not p.endswith("/"):
1033 self.depotPaths = newPaths
1036 self.loadUserMapFromCache()
1038 if self.detectLabels:
1041 if self.detectBranches:
1042 self.getBranchMapping();
1044 print "p4-git branches: %s" % self.p4BranchesInGit
1045 print "initial parents: %s" % self.initialParents
1046 for b in self.p4BranchesInGit:
1050 b = b[len(self.projectName):]
1051 self.createdBranches.add(b)
1053 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1055 importProcess = subprocess.Popen(["git", "fast-import"],
1056 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1057 stderr=subprocess.PIPE);
1058 self.gitOutput = importProcess.stdout
1059 self.gitStream = importProcess.stdin
1060 self.gitError = importProcess.stderr
1062 if len(self.revision) > 0:
1063 print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
1065 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1066 details["desc"] = ("Initial import of %s from the state at revision %s"
1067 % (' '.join(self.depotPaths), self.revision))
1068 details["change"] = self.revision
1072 for info in p4CmdList("files "
1073 + ' '.join(["%s...%s"
1074 % (p, self.revision)
1075 for p in self.depotPaths])):
1076 change = int(info["change"])
1077 if change > newestRevision:
1078 newestRevision = change
1080 if info["action"] == "delete":
1081 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1082 #fileCnt = fileCnt + 1
1085 for prop in [ "depotFile", "rev", "action", "type" ]:
1086 details["%s%s" % (prop, fileCnt)] = info[prop]
1088 fileCnt = fileCnt + 1
1090 details["change"] = newestRevision
1093 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1095 print "IO error with git fast-import. Is your git version recent enough?"
1096 print self.gitError.read()
1101 if len(self.changesFile) > 0:
1102 output = open(self.changesFile).readlines()
1105 changeSet.add(int(line))
1107 for change in changeSet:
1108 changes.append(change)
1113 print "Getting p4 changes for %s...%s" % (`self.depotPaths`,
1115 assert self.depotPaths
1116 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1117 for p in self.depotPaths]))
1120 changeNum = line.split(" ")[1]
1121 changes.append(changeNum)
1125 if len(self.maxChanges) > 0:
1126 changes = changes[0:min(int(self.maxChanges), len(changes))]
1128 if len(changes) == 0:
1130 print "No changes to import!"
1133 self.updatedBranches = set()
1136 for change in changes:
1137 description = p4Cmd("describe %s" % change)
1140 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1145 if self.detectBranches:
1146 branches = self.splitFilesIntoBranches(description)
1147 for branch in branches.keys():
1149 branchPrefix = self.depotPaths[0] + branch + "/"
1153 filesForCommit = branches[branch]
1156 print "branch is %s" % branch
1158 self.updatedBranches.add(branch)
1160 if branch not in self.createdBranches:
1161 self.createdBranches.add(branch)
1162 parent = self.knownBranches[branch]
1163 if parent == branch:
1166 print "parent determined through known branches: %s" % parent
1168 # main branch? use master
1169 if branch == "main":
1174 branch = self.projectName + branch
1176 if parent == "main":
1178 elif len(parent) > 0:
1180 parent = self.projectName + parent
1182 branch = self.refPrefix + branch
1184 parent = self.refPrefix + parent
1187 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1189 if len(parent) == 0 and branch in self.initialParents:
1190 parent = self.initialParents[branch]
1191 del self.initialParents[branch]
1193 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1195 files = self.extractFilesFromCommit(description)
1196 self.commit(description, files, self.branch, self.depotPaths,
1198 self.initialParent = ""
1200 print self.gitError.read()
1205 if len(self.updatedBranches) > 0:
1206 sys.stdout.write("Updated branches: ")
1207 for b in self.updatedBranches:
1208 sys.stdout.write("%s " % b)
1209 sys.stdout.write("\n")
1212 self.gitStream.close()
1213 if importProcess.wait() != 0:
1214 die("fast-import failed: %s" % self.gitError.read())
1215 self.gitOutput.close()
1216 self.gitError.close()
1220 class P4Rebase(Command):
1222 Command.__init__(self)
1224 self.description = ("Fetches the latest revision from perforce and "
1225 + "rebases the current work (branch) against it")
1227 def run(self, args):
1230 print "Rebasing the current branch"
1231 oldHead = read_pipe("git rev-parse HEAD").strip()
1232 system("git rebase p4")
1233 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1236 class P4Clone(P4Sync):
1238 P4Sync.__init__(self)
1239 self.description = "Creates a new git repository and imports from Perforce into it"
1240 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1241 self.needsGit = False
1243 def run(self, args):
1249 if self.keepRepoPath:
1250 destination = args[-1]
1252 elif len(args) == 2:
1253 destination = args[1]
1258 for p in depotPaths:
1259 if not p.startswith("//"):
1264 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1265 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1266 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1267 depotDir = re.sub(r"/$", "", depotDir)
1269 destination = os.path.split(depotDir)[1]
1271 print "Importing from %s into %s" % (`depotPaths`, destination)
1272 os.makedirs(destination)
1273 os.chdir(destination)
1275 gitdir = os.getcwd() + "/.git"
1276 if not P4Sync.run(self, depotPaths):
1278 if self.branch != "master":
1279 if gitBranchExists("refs/remotes/p4/master"):
1280 system("git branch master refs/remotes/p4/master")
1281 system("git checkout -f")
1283 print "Could not detect main branch. No checkout/master branch created."
1286 class HelpFormatter(optparse.IndentedHelpFormatter):
1288 optparse.IndentedHelpFormatter.__init__(self)
1290 def format_description(self, description):
1292 return description + "\n"
1296 def printUsage(commands):
1297 print "usage: %s <command> [options]" % sys.argv[0]
1299 print "valid commands: %s" % ", ".join(commands)
1301 print "Try %s <command> --help for command specific help." % sys.argv[0]
1305 "debug" : P4Debug(),
1306 "submit" : P4Submit(),
1308 "rebase" : P4Rebase(),
1309 "clone" : P4Clone(),
1310 "rollback" : P4RollBack()
1313 if len(sys.argv[1:]) == 0:
1314 printUsage(commands.keys())
1318 cmdName = sys.argv[1]
1320 cmd = commands[cmdName]
1322 print "unknown command %s" % cmdName
1324 printUsage(commands.keys())
1327 options = cmd.options
1332 if len(options) > 0:
1333 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1335 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1337 description = cmd.description,
1338 formatter = HelpFormatter())
1340 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1342 verbose = cmd.verbose
1345 if len(gitdir) == 0:
1347 if not isValidGitDir(gitdir):
1348 gitdir = read_pipe("git rev-parse --git-dir").strip()
1349 if os.path.exists(gitdir):
1350 cdup = read_pipe("git rev-parse --show-cdup").strip()
1354 if not isValidGitDir(gitdir):
1355 if isValidGitDir(gitdir + "/.git"):
1358 die("fatal: cannot locate git repository at %s" % gitdir)
1360 os.environ["GIT_DIR"] = gitdir
1362 if not cmd.run(args):