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
16 gitdir = os.environ.get("GIT_DIR", "")
19 def write_pipe (c, str):
21 sys.stderr.write ('writing pipe: %s\n' % c)
23 ## todo: check return status
24 pipe = os.popen (c, 'w')
27 sys.stderr.write ('Command failed')
33 sys.stderr.write ('reading pipe: %s\n' % c)
34 ## todo: check return status
35 pipe = os.popen (c, 'rb')
38 sys.stderr.write ('Command failed')
44 def read_pipe_lines (c):
45 sys.stderr.write ('reading pipe: %s\n' % c)
46 ## todo: check return status
47 pipe = os.popen (c, 'rb')
48 val = pipe.readlines()
50 sys.stderr.write ('Command failed')
56 cmd = "p4 -G %s" % cmd
57 pipe = os.popen(cmd, "rb")
62 entry = marshal.load(pipe)
66 exitCode = pipe.close()
69 entry["p4ExitCode"] = exitCode
81 def p4Where(depotPath):
82 if not depotPath.endswith("/"):
84 output = p4Cmd("where %s..." % depotPath)
85 if output["code"] == "error":
89 clientPath = output.get("path")
90 elif "data" in output:
91 data = output.get("data")
92 lastSpace = data.rfind(" ")
93 clientPath = data[lastSpace + 1:]
95 if clientPath.endswith("..."):
96 clientPath = clientPath[:-3]
100 sys.stderr.write(msg + "\n")
103 def currentGitBranch():
104 return read_pipe("git name-rev HEAD").split(" ")[1][:-1]
106 def isValidGitDir(path):
107 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
111 def parseRevision(ref):
112 return read_pipe("git rev-parse %s" % ref)[:-1]
115 if os.system(cmd) != 0:
116 die("command failed: %s" % cmd)
118 def extractLogMessageFromGitCommit(commit):
121 ## fixme: title is first line of commit, not 1st paragraph.
123 for log in read_pipe_lines("git cat-file commit %s" % commit):
132 def extractDepotPathAndChangeFromGitLog(log):
134 for line in log.split("\n"):
136 if line.startswith("[git-p4:") and line.endswith("]"):
137 line = line[8:-1].strip()
138 for assignment in line.split(":"):
139 variable = assignment.strip()
141 equalPos = assignment.find("=")
143 variable = assignment[:equalPos].strip()
144 value = assignment[equalPos + 1:].strip()
145 if value.startswith("\"") and value.endswith("\""):
147 values[variable] = value
149 return values.get("depot-path"), values.get("change")
151 def gitBranchExists(branch):
152 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
153 return proc.wait() == 0;
156 return mypopen("git config %s" % key).read()[:-1]
160 self.usage = "usage: %prog [options]"
163 class P4Debug(Command):
165 Command.__init__(self)
168 self.description = "A tool to debug the output of p4 -G."
169 self.needsGit = False
172 for output in p4CmdList(" ".join(args)):
176 class P4RollBack(Command):
178 Command.__init__(self)
180 optparse.make_option("--verbose", dest="verbose", action="store_true"),
181 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
183 self.description = "A tool to debug the multi-branch import. Don't use :)"
185 self.rollbackLocalBranches = False
190 maxChange = int(args[0])
192 if "p4ExitCode" in p4Cmd("changes -m 1"):
193 die("Problems executing p4");
195 if self.rollbackLocalBranches:
196 refPrefix = "refs/heads/"
197 lines = read_pipe_lines("git rev-parse --symbolic --branches")
199 refPrefix = "refs/remotes/"
200 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
203 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
204 ref = refPrefix + line[:-1]
205 log = extractLogMessageFromGitCommit(ref)
206 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
209 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
210 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
211 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
214 while len(change) > 0 and int(change) > maxChange:
217 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
218 system("git update-ref %s \"%s^\"" % (ref, ref))
219 log = extractLogMessageFromGitCommit(ref)
220 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
223 print "%s rewound to %s" % (ref, change)
227 class P4Submit(Command):
229 Command.__init__(self)
231 optparse.make_option("--continue", action="store_false", dest="firstTime"),
232 optparse.make_option("--origin", dest="origin"),
233 optparse.make_option("--reset", action="store_true", dest="reset"),
234 optparse.make_option("--log-substitutions", dest="substFile"),
235 optparse.make_option("--dry-run", action="store_true"),
236 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
237 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
239 self.description = "Submit changes from git to the perforce depot."
240 self.usage += " [name of git branch to submit into perforce depot]"
241 self.firstTime = True
243 self.interactive = True
246 self.firstTime = True
248 self.directSubmit = False
249 self.trustMeLikeAFool = False
251 self.logSubstitutions = {}
252 self.logSubstitutions["<enter description here>"] = "%log%"
253 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
256 if len(p4CmdList("opened ...")) > 0:
257 die("You have files opened with perforce! Close them before starting the sync.")
260 if len(self.config) > 0 and not self.reset:
261 die("Cannot start sync. Previous sync config found at %s\n"
262 "If you want to start submitting again from scratch "
263 "maybe you want to call git-p4 submit --reset" % self.configFile)
266 if self.directSubmit:
269 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
270 commits.append(line[:-1])
273 self.config["commits"] = commits
275 def prepareLogMessage(self, template, message):
278 for line in template.split("\n"):
279 if line.startswith("#"):
280 result += line + "\n"
284 for key in self.logSubstitutions.keys():
285 if line.find(key) != -1:
286 value = self.logSubstitutions[key]
287 value = value.replace("%log%", message)
288 if value != "@remove@":
289 result += line.replace(key, value) + "\n"
294 result += line + "\n"
298 def applyCommit(self, id):
299 if self.directSubmit:
300 print "Applying local change in working directory/index"
301 diff = self.diffStatus
303 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
304 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
306 filesToDelete = set()
310 path = line[1:].strip()
312 system("p4 edit \"%s\"" % path)
313 editedFiles.add(path)
314 elif modifier == "A":
316 if path in filesToDelete:
317 filesToDelete.remove(path)
318 elif modifier == "D":
319 filesToDelete.add(path)
320 if path in filesToAdd:
321 filesToAdd.remove(path)
323 die("unknown modifier %s for %s" % (modifier, path))
325 if self.directSubmit:
326 diffcmd = "cat \"%s\"" % self.diffFile
328 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
329 patchcmd = diffcmd + " | git apply "
330 tryPatchCmd = patchcmd + "--check -"
331 applyPatchCmd = patchcmd + "--check --apply -"
333 if os.system(tryPatchCmd) != 0:
334 print "Unfortunately applying the change failed!"
335 print "What do you want to do?"
337 while response != "s" and response != "a" and response != "w":
338 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
339 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
341 print "Skipping! Good luck with the next patches..."
343 elif response == "a":
344 os.system(applyPatchCmd)
345 if len(filesToAdd) > 0:
346 print "You may also want to call p4 add on the following files:"
347 print " ".join(filesToAdd)
348 if len(filesToDelete):
349 print "The following files should be scheduled for deletion with p4 delete:"
350 print " ".join(filesToDelete)
351 die("Please resolve and submit the conflict manually and "
352 + "continue afterwards with git-p4 submit --continue")
353 elif response == "w":
354 system(diffcmd + " > patch.txt")
355 print "Patch saved to patch.txt in %s !" % self.clientPath
356 die("Please resolve and submit the conflict manually and "
357 "continue afterwards with git-p4 submit --continue")
359 system(applyPatchCmd)
362 system("p4 add %s" % f)
363 for f in filesToDelete:
364 system("p4 revert %s" % f)
365 system("p4 delete %s" % f)
368 if not self.directSubmit:
369 logMessage = extractLogMessageFromGitCommit(id)
370 logMessage = logMessage.replace("\n", "\n\t")
371 logMessage = logMessage[:-1]
373 template = read_pipe("p4 change -o")
376 submitTemplate = self.prepareLogMessage(template, logMessage)
377 diff = read_pipe("p4 diff -du ...")
379 for newFile in filesToAdd:
380 diff += "==== new file ====\n"
381 diff += "--- /dev/null\n"
382 diff += "+++ %s\n" % newFile
383 f = open(newFile, "r")
384 for line in f.readlines():
388 separatorLine = "######## everything below this line is just the diff #######"
389 if platform.system() == "Windows":
390 separatorLine += "\r"
391 separatorLine += "\n"
394 if self.trustMeLikeAFool:
397 firstIteration = True
398 while response == "e":
399 if not firstIteration:
400 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
401 firstIteration = False
403 [handle, fileName] = tempfile.mkstemp()
404 tmpFile = os.fdopen(handle, "w+")
405 tmpFile.write(submitTemplate + separatorLine + diff)
408 if platform.system() == "Windows":
409 defaultEditor = "notepad"
410 editor = os.environ.get("EDITOR", defaultEditor);
411 system(editor + " " + fileName)
412 tmpFile = open(fileName, "rb")
413 message = tmpFile.read()
416 submitTemplate = message[:message.index(separatorLine)]
418 if response == "y" or response == "yes":
421 raw_input("Press return to continue...")
423 if self.directSubmit:
424 print "Submitting to git first"
425 os.chdir(self.oldWorkingDirectory)
426 write_pipe("git commit -a -F -", submitTemplate)
427 os.chdir(self.clientPath)
429 write_pipe("p4 submit -i", submitTemplate)
430 elif response == "s":
431 for f in editedFiles:
432 system("p4 revert \"%s\"" % f);
434 system("p4 revert \"%s\"" % f);
436 for f in filesToDelete:
437 system("p4 delete \"%s\"" % f);
440 print "Not submitting!"
441 self.interactive = False
443 fileName = "submit.txt"
444 file = open(fileName, "w+")
445 file.write(self.prepareLogMessage(template, logMessage))
447 print ("Perforce submit template written as %s. "
448 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
449 % (fileName, fileName))
453 # make gitdir absolute so we can cd out into the perforce checkout
454 gitdir = os.path.abspath(gitdir)
455 os.environ["GIT_DIR"] = gitdir
458 self.master = currentGitBranch()
459 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
460 die("Detecting current git branch failed!")
462 self.master = args[0]
467 if gitBranchExists("p4"):
468 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
469 if len(depotPath) == 0 and gitBranchExists("origin"):
470 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
472 if len(depotPath) == 0:
473 print "Internal error: cannot locate perforce depot path from existing branches"
476 self.clientPath = p4Where(depotPath)
478 if len(self.clientPath) == 0:
479 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
482 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
483 self.oldWorkingDirectory = os.getcwd()
485 if self.directSubmit:
486 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
487 if len(self.diffStatus) == 0:
488 print "No changes in working directory to submit."
490 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
491 self.diffFile = gitdir + "/p4-git-diff"
492 f = open(self.diffFile, "wb")
496 os.chdir(self.clientPath)
497 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
498 if response == "y" or response == "yes":
499 system("p4 sync ...")
501 if len(self.origin) == 0:
502 if gitBranchExists("p4"):
505 self.origin = "origin"
508 self.firstTime = True
510 if len(self.substFile) > 0:
511 for line in open(self.substFile, "r").readlines():
512 tokens = line[:-1].split("=")
513 self.logSubstitutions[tokens[0]] = tokens[1]
516 self.configFile = gitdir + "/p4-git-sync.cfg"
517 self.config = shelve.open(self.configFile, writeback=True)
522 commits = self.config.get("commits", [])
524 while len(commits) > 0:
525 self.firstTime = False
527 commits = commits[1:]
528 self.config["commits"] = commits
529 self.applyCommit(commit)
530 if not self.interactive:
535 if self.directSubmit:
536 os.remove(self.diffFile)
538 if len(commits) == 0:
540 print "No changes found to apply between %s and current HEAD" % self.origin
542 print "All changes applied!"
543 os.chdir(self.oldWorkingDirectory)
544 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
545 if response == "y" or response == "yes":
548 os.remove(self.configFile)
552 class P4Sync(Command):
554 Command.__init__(self)
556 optparse.make_option("--branch", dest="branch"),
557 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
558 optparse.make_option("--changesfile", dest="changesFile"),
559 optparse.make_option("--silent", dest="silent", action="store_true"),
560 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
561 optparse.make_option("--verbose", dest="verbose", action="store_true"),
562 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
563 optparse.make_option("--max-changes", dest="maxChanges")
565 self.description = """Imports from Perforce into a git repository.\n
567 //depot/my/project/ -- to import the current head
568 //depot/my/project/@all -- to import everything
569 //depot/my/project/@1,6 -- to import only from revision 1 to 6
571 (a ... is not needed in the path p4 specification, it's added implicitly)"""
573 self.usage += " //depot/path[@revRange]"
576 self.createdBranches = Set()
577 self.committedChanges = Set()
579 self.detectBranches = False
580 self.detectLabels = False
581 self.changesFile = ""
582 self.syncWithOrigin = True
584 self.importIntoRemotes = True
586 self.isWindows = (platform.system() == "Windows")
588 if gitConfig("git-p4.syncFromOrigin") == "false":
589 self.syncWithOrigin = False
591 def p4File(self, depotPath):
592 return read_pipe("p4 print -q \"%s\"" % depotPath)
594 def extractFilesFromCommit(self, commit):
597 while commit.has_key("depotFile%s" % fnum):
598 path = commit["depotFile%s" % fnum]
599 if not path.startswith(self.depotPath):
600 # if not self.silent:
601 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
607 file["rev"] = commit["rev%s" % fnum]
608 file["action"] = commit["action%s" % fnum]
609 file["type"] = commit["type%s" % fnum]
614 def splitFilesIntoBranches(self, commit):
618 while commit.has_key("depotFile%s" % fnum):
619 path = commit["depotFile%s" % fnum]
620 if not path.startswith(self.depotPath):
621 # if not self.silent:
622 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
628 file["rev"] = commit["rev%s" % fnum]
629 file["action"] = commit["action%s" % fnum]
630 file["type"] = commit["type%s" % fnum]
633 relPath = path[len(self.depotPath):]
635 for branch in self.knownBranches.keys():
636 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
637 if branch not in branches:
638 branches[branch] = []
639 branches[branch].append(file)
643 def commit(self, details, files, branch, branchPrefix, parent = ""):
644 epoch = details["time"]
645 author = details["user"]
648 print "commit into %s" % branch
650 self.gitStream.write("commit %s\n" % branch)
651 # gitStream.write("mark :%s\n" % details["change"])
652 self.committedChanges.add(int(details["change"]))
654 if author not in self.users:
655 self.getUserMapFromPerforceServer()
656 if author in self.users:
657 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
659 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
661 self.gitStream.write("committer %s\n" % committer)
663 self.gitStream.write("data <<EOT\n")
664 self.gitStream.write(details["desc"])
665 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
666 self.gitStream.write("EOT\n\n")
670 print "parent %s" % parent
671 self.gitStream.write("from %s\n" % parent)
675 if not path.startswith(branchPrefix):
676 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
679 depotPath = path + "#" + rev
680 relPath = path[len(branchPrefix):]
681 action = file["action"]
683 if file["type"] == "apple":
684 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
687 if action == "delete":
688 self.gitStream.write("D %s\n" % relPath)
691 if file["type"].startswith("x"):
694 data = self.p4File(depotPath)
696 if self.isWindows and file["type"].endswith("text"):
697 data = data.replace("\r\n", "\n")
699 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
700 self.gitStream.write("data %s\n" % len(data))
701 self.gitStream.write(data)
702 self.gitStream.write("\n")
704 self.gitStream.write("\n")
706 change = int(details["change"])
708 if self.labels.has_key(change):
709 label = self.labels[change]
710 labelDetails = label[0]
711 labelRevisions = label[1]
713 print "Change %s is labelled %s" % (change, labelDetails)
715 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
717 if len(files) == len(labelRevisions):
721 if info["action"] == "delete":
723 cleanedFiles[info["depotFile"]] = info["rev"]
725 if cleanedFiles == labelRevisions:
726 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
727 self.gitStream.write("from %s\n" % branch)
729 owner = labelDetails["Owner"]
731 if author in self.users:
732 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
734 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
735 self.gitStream.write("tagger %s\n" % tagger)
736 self.gitStream.write("data <<EOT\n")
737 self.gitStream.write(labelDetails["Description"])
738 self.gitStream.write("EOT\n\n")
742 print ("Tag %s does not match with change %s: files do not match."
743 % (labelDetails["label"], change))
747 print ("Tag %s does not match with change %s: file count is different."
748 % (labelDetails["label"], change))
750 def getUserMapFromPerforceServer(self):
751 if self.userMapFromPerforceServer:
755 for output in p4CmdList("users"):
756 if not output.has_key("User"):
758 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
760 cache = open(gitdir + "/p4-usercache.txt", "wb")
761 for user in self.users.keys():
762 cache.write("%s\t%s\n" % (user, self.users[user]))
764 self.userMapFromPerforceServer = True
766 def loadUserMapFromCache(self):
768 self.userMapFromPerforceServer = False
770 cache = open(gitdir + "/p4-usercache.txt", "rb")
771 lines = cache.readlines()
774 entry = line[:-1].split("\t")
775 self.users[entry[0]] = entry[1]
777 self.getUserMapFromPerforceServer()
782 l = p4CmdList("labels %s..." % self.depotPath)
783 if len(l) > 0 and not self.silent:
784 print "Finding files belonging to labels in %s" % self.depotPath
787 label = output["label"]
791 print "Querying files for label %s" % label
792 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
793 revisions[file["depotFile"]] = file["rev"]
794 change = int(file["change"])
795 if change > newestChange:
796 newestChange = change
798 self.labels[newestChange] = [output, revisions]
801 print "Label changes: %s" % self.labels.keys()
803 def getBranchMapping(self):
804 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
806 for info in p4CmdList("branches"):
807 details = p4Cmd("branch -o %s" % info["branch"])
809 while details.has_key("View%s" % viewIdx):
810 paths = details["View%s" % viewIdx].split(" ")
811 viewIdx = viewIdx + 1
812 # require standard //depot/foo/... //depot/bar/... mapping
813 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
816 destination = paths[1]
817 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
818 source = source[len(self.depotPath):-4]
819 destination = destination[len(self.depotPath):-4]
820 if destination not in self.knownBranches:
821 self.knownBranches[destination] = source
822 if source not in self.knownBranches:
823 self.knownBranches[source] = source
825 def listExistingP4GitBranches(self):
826 self.p4BranchesInGit = []
828 cmdline = "git rev-parse --symbolic "
829 if self.importIntoRemotes:
830 cmdline += " --remotes"
832 cmdline += " --branches"
834 for line in read_pipe_lines(cmdline):
835 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
837 if self.importIntoRemotes:
842 self.p4BranchesInGit.append(branch)
843 self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
845 def createOrUpdateBranchesFromOrigin(self):
847 print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
849 for line in mypopen("git rev-parse --symbolic --remotes"):
850 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
853 headName = line[len("origin/"):-1]
854 remoteHead = self.refPrefix + headName
855 originHead = "origin/" + headName
857 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead))
858 if len(originPreviousDepotPath) == 0 or len(originP4Change) == 0:
862 if not gitBranchExists(remoteHead):
864 print "creating %s" % remoteHead
867 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead))
868 if len(p4Change) > 0:
869 if originPreviousDepotPath == p4PreviousDepotPath:
870 originP4Change = int(originP4Change)
871 p4Change = int(p4Change)
872 if originP4Change > p4Change:
873 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead, originP4Change, remoteHead, p4Change)
876 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead, originPreviousDepotPath, remoteHead, p4PreviousDepotPath)
879 system("git update-ref %s %s" % (remoteHead, originHead))
883 self.changeRange = ""
884 self.initialParent = ""
885 self.previousDepotPath = ""
887 # map from branch depot path to parent branch
888 self.knownBranches = {}
889 self.initialParents = {}
890 self.hasOrigin = gitBranchExists("origin")
892 if self.importIntoRemotes:
893 self.refPrefix = "refs/remotes/p4/"
895 self.refPrefix = "refs/heads/"
897 if self.syncWithOrigin and self.hasOrigin:
899 print "Syncing with origin first by calling git fetch origin"
900 system("git fetch origin")
902 if len(self.branch) == 0:
903 self.branch = self.refPrefix + "master"
904 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
905 system("git update-ref %s refs/heads/p4" % self.branch)
906 system("git branch -D p4");
907 # create it /after/ importing, when master exists
908 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
909 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
913 self.createOrUpdateBranchesFromOrigin()
914 self.listExistingP4GitBranches()
916 if len(self.p4BranchesInGit) > 1:
918 print "Importing from/into multiple branches"
919 self.detectBranches = True
922 print "branches: %s" % self.p4BranchesInGit
925 for branch in self.p4BranchesInGit:
926 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
927 (depotPath, change) = extractDepotPathAndChangeFromGitLog(logMsg)
930 print "path %s change %s" % (depotPath, change)
932 if len(depotPath) > 0 and len(change) > 0:
933 change = int(change) + 1
934 p4Change = max(p4Change, change)
936 if len(self.previousDepotPath) == 0:
937 self.previousDepotPath = depotPath
940 l = min(len(self.previousDepotPath), len(depotPath))
941 while i < l and self.previousDepotPath[i] == depotPath[i]:
943 self.previousDepotPath = self.previousDepotPath[:i]
946 self.depotPath = self.previousDepotPath
947 self.changeRange = "@%s,#head" % p4Change
948 self.initialParent = parseRevision(self.branch)
949 if not self.silent and not self.detectBranches:
950 print "Performing incremental import into %s git branch" % self.branch
952 if not self.branch.startswith("refs/"):
953 self.branch = "refs/heads/" + self.branch
955 if len(self.depotPath) != 0:
956 self.depotPath = self.depotPath[:-1]
958 if len(args) == 0 and len(self.depotPath) != 0:
960 print "Depot path: %s" % self.depotPath
964 if len(self.depotPath) != 0 and self.depotPath != args[0]:
965 print ("previous import used depot path %s and now %s was specified. "
966 "This doesn't work!" % (self.depotPath, args[0]))
968 self.depotPath = args[0]
973 if self.depotPath.find("@") != -1:
974 atIdx = self.depotPath.index("@")
975 self.changeRange = self.depotPath[atIdx:]
976 if self.changeRange == "@all":
977 self.changeRange = ""
978 elif self.changeRange.find(",") == -1:
979 self.revision = self.changeRange
980 self.changeRange = ""
981 self.depotPath = self.depotPath[0:atIdx]
982 elif self.depotPath.find("#") != -1:
983 hashIdx = self.depotPath.index("#")
984 self.revision = self.depotPath[hashIdx:]
985 self.depotPath = self.depotPath[0:hashIdx]
986 elif len(self.previousDepotPath) == 0:
987 self.revision = "#head"
989 if self.depotPath.endswith("..."):
990 self.depotPath = self.depotPath[:-3]
992 if not self.depotPath.endswith("/"):
993 self.depotPath += "/"
995 self.loadUserMapFromCache()
997 if self.detectLabels:
1000 if self.detectBranches:
1001 self.getBranchMapping();
1003 print "p4-git branches: %s" % self.p4BranchesInGit
1004 print "initial parents: %s" % self.initialParents
1005 for b in self.p4BranchesInGit:
1007 b = b[len(self.projectName):]
1008 self.createdBranches.add(b)
1010 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1012 importProcess = subprocess.Popen(["git", "fast-import"],
1013 stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
1014 self.gitOutput = importProcess.stdout
1015 self.gitStream = importProcess.stdin
1016 self.gitError = importProcess.stderr
1018 if len(self.revision) > 0:
1019 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
1021 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1022 details["desc"] = ("Initial import of %s from the state at revision %s"
1023 % (self.depotPath, self.revision))
1024 details["change"] = self.revision
1028 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
1029 change = int(info["change"])
1030 if change > newestRevision:
1031 newestRevision = change
1033 if info["action"] == "delete":
1034 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1035 #fileCnt = fileCnt + 1
1038 for prop in [ "depotFile", "rev", "action", "type" ]:
1039 details["%s%s" % (prop, fileCnt)] = info[prop]
1041 fileCnt = fileCnt + 1
1043 details["change"] = newestRevision
1046 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
1048 print "IO error with git fast-import. Is your git version recent enough?"
1049 print self.gitError.read()
1054 if len(self.changesFile) > 0:
1055 output = open(self.changesFile).readlines()
1058 changeSet.add(int(line))
1060 for change in changeSet:
1061 changes.append(change)
1066 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
1067 output = read_pipe_lines("p4 changes %s...%s" % (self.depotPath, self.changeRange))
1070 changeNum = line.split(" ")[1]
1071 changes.append(changeNum)
1075 if len(self.maxChanges) > 0:
1076 changes = changes[0:min(int(self.maxChanges), len(changes))]
1078 if len(changes) == 0:
1080 print "No changes to import!"
1083 self.updatedBranches = set()
1086 for change in changes:
1087 description = p4Cmd("describe %s" % change)
1090 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1095 if self.detectBranches:
1096 branches = self.splitFilesIntoBranches(description)
1097 for branch in branches.keys():
1098 branchPrefix = self.depotPath + branch + "/"
1102 filesForCommit = branches[branch]
1105 print "branch is %s" % branch
1107 self.updatedBranches.add(branch)
1109 if branch not in self.createdBranches:
1110 self.createdBranches.add(branch)
1111 parent = self.knownBranches[branch]
1112 if parent == branch:
1115 print "parent determined through known branches: %s" % parent
1117 # main branch? use master
1118 if branch == "main":
1121 branch = self.projectName + branch
1123 if parent == "main":
1125 elif len(parent) > 0:
1126 parent = self.projectName + parent
1128 branch = self.refPrefix + branch
1130 parent = self.refPrefix + parent
1133 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1135 if len(parent) == 0 and branch in self.initialParents:
1136 parent = self.initialParents[branch]
1137 del self.initialParents[branch]
1139 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1141 files = self.extractFilesFromCommit(description)
1142 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1143 self.initialParent = ""
1145 print self.gitError.read()
1150 if len(self.updatedBranches) > 0:
1151 sys.stdout.write("Updated branches: ")
1152 for b in self.updatedBranches:
1153 sys.stdout.write("%s " % b)
1154 sys.stdout.write("\n")
1157 self.gitStream.close()
1158 if importProcess.wait() != 0:
1159 die("fast-import failed: %s" % self.gitError.read())
1160 self.gitOutput.close()
1161 self.gitError.close()
1165 class P4Rebase(Command):
1167 Command.__init__(self)
1169 self.description = ("Fetches the latest revision from perforce and "
1170 + "rebases the current work (branch) against it")
1172 def run(self, args):
1175 print "Rebasing the current branch"
1176 oldHead = read_pipe("git rev-parse HEAD")[:-1]
1177 system("git rebase p4")
1178 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1181 class P4Clone(P4Sync):
1183 P4Sync.__init__(self)
1184 self.description = "Creates a new git repository and imports from Perforce into it"
1185 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1186 self.needsGit = False
1188 def run(self, args):
1196 destination = args[1]
1200 if not depotPath.startswith("//"):
1203 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1204 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1205 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1206 depotDir = re.sub(r"/$", "", depotDir)
1209 destination = os.path.split(depotDir)[-1]
1211 print "Importing from %s into %s" % (depotPath, destination)
1212 os.makedirs(destination)
1213 os.chdir(destination)
1215 gitdir = os.getcwd() + "/.git"
1216 if not P4Sync.run(self, [depotPath]):
1218 if self.branch != "master":
1219 if gitBranchExists("refs/remotes/p4/master"):
1220 system("git branch master refs/remotes/p4/master")
1221 system("git checkout -f")
1223 print "Could not detect main branch. No checkout/master branch created."
1226 class HelpFormatter(optparse.IndentedHelpFormatter):
1228 optparse.IndentedHelpFormatter.__init__(self)
1230 def format_description(self, description):
1232 return description + "\n"
1236 def printUsage(commands):
1237 print "usage: %s <command> [options]" % sys.argv[0]
1239 print "valid commands: %s" % ", ".join(commands)
1241 print "Try %s <command> --help for command specific help." % sys.argv[0]
1245 "debug" : P4Debug(),
1246 "submit" : P4Submit(),
1248 "rebase" : P4Rebase(),
1249 "clone" : P4Clone(),
1250 "rollback" : P4RollBack()
1253 if len(sys.argv[1:]) == 0:
1254 printUsage(commands.keys())
1258 cmdName = sys.argv[1]
1260 cmd = commands[cmdName]
1262 print "unknown command %s" % cmdName
1264 printUsage(commands.keys())
1267 options = cmd.options
1272 if len(options) > 0:
1273 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1275 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1277 description = cmd.description,
1278 formatter = HelpFormatter())
1280 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1284 if len(gitdir) == 0:
1286 if not isValidGitDir(gitdir):
1287 gitdir = read_pipe("git rev-parse --git-dir")[:-1]
1288 if os.path.exists(gitdir):
1289 cdup = read_pipe("git rev-parse --show-cdup")[:-1];
1293 if not isValidGitDir(gitdir):
1294 if isValidGitDir(gitdir + "/.git"):
1297 die("fatal: cannot locate git repository at %s" % gitdir)
1299 os.environ["GIT_DIR"] = gitdir
1301 if not cmd.run(args):