3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <hausmann@kde.org>
6 # Copyright: 2007 Simon Hausmann <hausmann@kde.org>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
10 # TODO: * Consider making --with-origin the default, assuming that the git
11 # protocol is always more efficient. (needs manual testing first :)
14 import optparse, sys, os, marshal, popen2, subprocess, shelve
15 import tempfile, getopt, sha, os.path, time, platform
18 gitdir = os.environ.get("GIT_DIR", "")
21 return os.popen(command, "rb");
24 cmd = "p4 -G %s" % cmd
25 pipe = os.popen(cmd, "rb")
30 entry = marshal.load(pipe)
34 exitCode = pipe.close()
36 result["p4ExitCode"] = exitCode
47 def p4Where(depotPath):
48 if not depotPath.endswith("/"):
50 output = p4Cmd("where %s..." % depotPath)
51 if output["code"] == "error":
55 clientPath = output.get("path")
56 elif "data" in output:
57 data = output.get("data")
58 lastSpace = data.rfind(" ")
59 clientPath = data[lastSpace + 1:]
61 if clientPath.endswith("..."):
62 clientPath = clientPath[:-3]
66 sys.stderr.write(msg + "\n")
69 def currentGitBranch():
70 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
72 def isValidGitDir(path):
73 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
77 def parseRevision(ref):
78 return mypopen("git rev-parse %s" % ref).read()[:-1]
81 if os.system(cmd) != 0:
82 die("command failed: %s" % cmd)
84 def extractLogMessageFromGitCommit(commit):
87 for log in mypopen("git cat-file commit %s" % commit).readlines():
96 def extractDepotPathAndChangeFromGitLog(log):
98 for line in log.split("\n"):
100 if line.startswith("[git-p4:") and line.endswith("]"):
101 line = line[8:-1].strip()
102 for assignment in line.split(":"):
103 variable = assignment.strip()
105 equalPos = assignment.find("=")
107 variable = assignment[:equalPos].strip()
108 value = assignment[equalPos + 1:].strip()
109 if value.startswith("\"") and value.endswith("\""):
111 values[variable] = value
113 return values.get("depot-path"), values.get("change")
115 def gitBranchExists(branch):
116 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
117 return proc.wait() == 0;
121 self.usage = "usage: %prog [options]"
124 class P4Debug(Command):
126 Command.__init__(self)
129 self.description = "A tool to debug the output of p4 -G."
130 self.needsGit = False
133 for output in p4CmdList(" ".join(args)):
137 class P4RollBack(Command):
139 Command.__init__(self)
141 optparse.make_option("--verbose", dest="verbose", action="store_true"),
142 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
144 self.description = "A tool to debug the multi-branch import. Don't use :)"
146 self.rollbackLocalBranches = False
151 maxChange = int(args[0])
153 if self.rollbackLocalBranches:
154 refPrefix = "refs/heads/"
155 lines = mypopen("git rev-parse --symbolic --branches").readlines()
157 refPrefix = "refs/remotes/"
158 lines = mypopen("git rev-parse --symbolic --remotes").readlines()
161 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
162 ref = refPrefix + line[:-1]
163 log = extractLogMessageFromGitCommit(ref)
164 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
167 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
168 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
169 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
172 while len(change) > 0 and int(change) > maxChange:
175 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
176 system("git update-ref %s \"%s^\"" % (ref, ref))
177 log = extractLogMessageFromGitCommit(ref)
178 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
181 print "%s rewound to %s" % (ref, change)
185 class P4Submit(Command):
187 Command.__init__(self)
189 optparse.make_option("--continue", action="store_false", dest="firstTime"),
190 optparse.make_option("--origin", dest="origin"),
191 optparse.make_option("--reset", action="store_true", dest="reset"),
192 optparse.make_option("--log-substitutions", dest="substFile"),
193 optparse.make_option("--noninteractive", action="store_false"),
194 optparse.make_option("--dry-run", action="store_true"),
195 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
197 self.description = "Submit changes from git to the perforce depot."
198 self.usage += " [name of git branch to submit into perforce depot]"
199 self.firstTime = True
201 self.interactive = True
204 self.firstTime = True
206 self.directSubmit = False
208 self.logSubstitutions = {}
209 self.logSubstitutions["<enter description here>"] = "%log%"
210 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
213 if len(p4CmdList("opened ...")) > 0:
214 die("You have files opened with perforce! Close them before starting the sync.")
217 if len(self.config) > 0 and not self.reset:
218 die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self.configFile)
221 if self.directSubmit:
224 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
225 commits.append(line[:-1])
228 self.config["commits"] = commits
230 def prepareLogMessage(self, template, message):
233 for line in template.split("\n"):
234 if line.startswith("#"):
235 result += line + "\n"
239 for key in self.logSubstitutions.keys():
240 if line.find(key) != -1:
241 value = self.logSubstitutions[key]
242 value = value.replace("%log%", message)
243 if value != "@remove@":
244 result += line.replace(key, value) + "\n"
249 result += line + "\n"
254 if self.directSubmit:
255 print "Applying local change in working directory/index"
256 diff = self.diffStatus
258 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
259 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
261 filesToDelete = set()
265 path = line[1:].strip()
267 system("p4 edit \"%s\"" % path)
268 editedFiles.add(path)
269 elif modifier == "A":
271 if path in filesToDelete:
272 filesToDelete.remove(path)
273 elif modifier == "D":
274 filesToDelete.add(path)
275 if path in filesToAdd:
276 filesToAdd.remove(path)
278 die("unknown modifier %s for %s" % (modifier, path))
280 if self.directSubmit:
281 diffcmd = "cat \"%s\"" % self.diffFile
283 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
284 patchcmd = diffcmd + " | git apply "
285 tryPatchCmd = patchcmd + "--check -"
286 applyPatchCmd = patchcmd + "--check --apply -"
288 if os.system(tryPatchCmd) != 0:
289 print "Unfortunately applying the change failed!"
290 print "What do you want to do?"
292 while response != "s" and response != "a" and response != "w":
293 response = raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
295 print "Skipping! Good luck with the next patches..."
297 elif response == "a":
298 os.system(applyPatchCmd)
299 if len(filesToAdd) > 0:
300 print "You may also want to call p4 add on the following files:"
301 print " ".join(filesToAdd)
302 if len(filesToDelete):
303 print "The following files should be scheduled for deletion with p4 delete:"
304 print " ".join(filesToDelete)
305 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
306 elif response == "w":
307 system(diffcmd + " > patch.txt")
308 print "Patch saved to patch.txt in %s !" % self.clientPath
309 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
311 system(applyPatchCmd)
314 system("p4 add %s" % f)
315 for f in filesToDelete:
316 system("p4 revert %s" % f)
317 system("p4 delete %s" % f)
320 if not self.directSubmit:
321 logMessage = extractLogMessageFromGitCommit(id)
322 logMessage = logMessage.replace("\n", "\n\t")
323 logMessage = logMessage[:-1]
325 template = mypopen("p4 change -o").read()
328 submitTemplate = self.prepareLogMessage(template, logMessage)
329 diff = mypopen("p4 diff -du ...").read()
331 for newFile in filesToAdd:
332 diff += "==== new file ====\n"
333 diff += "--- /dev/null\n"
334 diff += "+++ %s\n" % newFile
335 f = open(newFile, "r")
336 for line in f.readlines():
340 separatorLine = "######## everything below this line is just the diff #######"
341 if platform.system() == "Windows":
342 separatorLine += "\r"
343 separatorLine += "\n"
346 firstIteration = True
347 while response == "e":
348 if not firstIteration:
349 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
350 firstIteration = False
352 [handle, fileName] = tempfile.mkstemp()
353 tmpFile = os.fdopen(handle, "w+")
354 tmpFile.write(submitTemplate + separatorLine + diff)
357 if platform.system() == "Windows":
358 defaultEditor = "notepad"
359 editor = os.environ.get("EDITOR", defaultEditor);
360 system(editor + " " + fileName)
361 tmpFile = open(fileName, "rb")
362 message = tmpFile.read()
365 submitTemplate = message[:message.index(separatorLine)]
367 if response == "y" or response == "yes":
370 raw_input("Press return to continue...")
372 if self.directSubmit:
373 print "Submitting to git first"
374 os.chdir(self.oldWorkingDirectory)
375 pipe = os.popen("git commit -a -F -", "wb")
376 pipe.write(submitTemplate)
378 os.chdir(self.clientPath)
380 pipe = os.popen("p4 submit -i", "wb")
381 pipe.write(submitTemplate)
383 elif response == "s":
384 for f in editedFiles:
385 system("p4 revert \"%s\"" % f);
387 system("p4 revert \"%s\"" % f);
389 for f in filesToDelete:
390 system("p4 delete \"%s\"" % f);
393 print "Not submitting!"
394 self.interactive = False
396 fileName = "submit.txt"
397 file = open(fileName, "w+")
398 file.write(self.prepareLogMessage(template, logMessage))
400 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
404 # make gitdir absolute so we can cd out into the perforce checkout
405 gitdir = os.path.abspath(gitdir)
406 os.environ["GIT_DIR"] = gitdir
409 self.master = currentGitBranch()
410 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
411 die("Detecting current git branch failed!")
413 self.master = args[0]
418 if gitBranchExists("p4"):
419 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
420 if len(depotPath) == 0 and gitBranchExists("origin"):
421 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
423 if len(depotPath) == 0:
424 print "Internal error: cannot locate perforce depot path from existing branches"
427 self.clientPath = p4Where(depotPath)
429 if len(self.clientPath) == 0:
430 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
433 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
434 self.oldWorkingDirectory = os.getcwd()
436 if self.directSubmit:
437 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
438 if len(self.diffStatus) == 0:
439 print "No changes in working directory to submit."
441 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
442 self.diffFile = gitdir + "/p4-git-diff"
443 f = open(self.diffFile, "wb")
447 os.chdir(self.clientPath)
448 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
449 if response == "y" or response == "yes":
450 system("p4 sync ...")
452 if len(self.origin) == 0:
453 if gitBranchExists("p4"):
456 self.origin = "origin"
459 self.firstTime = True
461 if len(self.substFile) > 0:
462 for line in open(self.substFile, "r").readlines():
463 tokens = line[:-1].split("=")
464 self.logSubstitutions[tokens[0]] = tokens[1]
467 self.configFile = gitdir + "/p4-git-sync.cfg"
468 self.config = shelve.open(self.configFile, writeback=True)
473 commits = self.config.get("commits", [])
475 while len(commits) > 0:
476 self.firstTime = False
478 commits = commits[1:]
479 self.config["commits"] = commits
481 if not self.interactive:
486 if self.directSubmit:
487 os.remove(self.diffFile)
489 if len(commits) == 0:
491 print "No changes found to apply between %s and current HEAD" % self.origin
493 print "All changes applied!"
494 os.chdir(self.oldWorkingDirectory)
495 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
496 if response == "y" or response == "yes":
499 os.remove(self.configFile)
503 class P4Sync(Command):
505 Command.__init__(self)
507 optparse.make_option("--branch", dest="branch"),
508 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
509 optparse.make_option("--changesfile", dest="changesFile"),
510 optparse.make_option("--silent", dest="silent", action="store_true"),
511 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
512 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
513 optparse.make_option("--verbose", dest="verbose", action="store_true"),
514 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
515 optparse.make_option("--max-changes", dest="maxChanges")
517 self.description = """Imports from Perforce into a git repository.\n
519 //depot/my/project/ -- to import the current head
520 //depot/my/project/@all -- to import everything
521 //depot/my/project/@1,6 -- to import only from revision 1 to 6
523 (a ... is not needed in the path p4 specification, it's added implicitly)"""
525 self.usage += " //depot/path[@revRange]"
528 self.createdBranches = Set()
529 self.committedChanges = Set()
531 self.detectBranches = False
532 self.detectLabels = False
533 self.changesFile = ""
534 self.syncWithOrigin = False
536 self.importIntoRemotes = True
539 def p4File(self, depotPath):
540 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
542 def extractFilesFromCommit(self, commit):
545 while commit.has_key("depotFile%s" % fnum):
546 path = commit["depotFile%s" % fnum]
547 if not path.startswith(self.depotPath):
548 # if not self.silent:
549 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
555 file["rev"] = commit["rev%s" % fnum]
556 file["action"] = commit["action%s" % fnum]
557 file["type"] = commit["type%s" % fnum]
562 def splitFilesIntoBranches(self, commit):
566 while commit.has_key("depotFile%s" % fnum):
567 path = commit["depotFile%s" % fnum]
568 if not path.startswith(self.depotPath):
569 # if not self.silent:
570 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
576 file["rev"] = commit["rev%s" % fnum]
577 file["action"] = commit["action%s" % fnum]
578 file["type"] = commit["type%s" % fnum]
581 relPath = path[len(self.depotPath):]
583 for branch in self.knownBranches.keys():
584 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
585 if branch not in branches:
586 branches[branch] = []
587 branches[branch].append(file)
591 def commit(self, details, files, branch, branchPrefix, parent = ""):
592 epoch = details["time"]
593 author = details["user"]
596 print "commit into %s" % branch
598 self.gitStream.write("commit %s\n" % branch)
599 # gitStream.write("mark :%s\n" % details["change"])
600 self.committedChanges.add(int(details["change"]))
602 if author not in self.users:
603 self.getUserMapFromPerforceServer()
604 if author in self.users:
605 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
607 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
609 self.gitStream.write("committer %s\n" % committer)
611 self.gitStream.write("data <<EOT\n")
612 self.gitStream.write(details["desc"])
613 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
614 self.gitStream.write("EOT\n\n")
618 print "parent %s" % parent
619 self.gitStream.write("from %s\n" % parent)
623 if not path.startswith(branchPrefix):
625 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
628 depotPath = path + "#" + rev
629 relPath = path[len(branchPrefix):]
630 action = file["action"]
632 if file["type"] == "apple":
633 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
636 if action == "delete":
637 self.gitStream.write("D %s\n" % relPath)
640 if file["type"].startswith("x"):
643 data = self.p4File(depotPath)
645 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
646 self.gitStream.write("data %s\n" % len(data))
647 self.gitStream.write(data)
648 self.gitStream.write("\n")
650 self.gitStream.write("\n")
652 change = int(details["change"])
654 if self.labels.has_key(change):
655 label = self.labels[change]
656 labelDetails = label[0]
657 labelRevisions = label[1]
659 print "Change %s is labelled %s" % (change, labelDetails)
661 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
663 if len(files) == len(labelRevisions):
667 if info["action"] == "delete":
669 cleanedFiles[info["depotFile"]] = info["rev"]
671 if cleanedFiles == labelRevisions:
672 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
673 self.gitStream.write("from %s\n" % branch)
675 owner = labelDetails["Owner"]
677 if author in self.users:
678 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
680 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
681 self.gitStream.write("tagger %s\n" % tagger)
682 self.gitStream.write("data <<EOT\n")
683 self.gitStream.write(labelDetails["Description"])
684 self.gitStream.write("EOT\n\n")
688 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
692 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
694 def getUserMapFromPerforceServer(self):
697 for output in p4CmdList("users"):
698 if not output.has_key("User"):
700 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
702 cache = open(gitdir + "/p4-usercache.txt", "wb")
703 for user in self.users.keys():
704 cache.write("%s\t%s\n" % (user, self.users[user]))
707 def loadUserMapFromCache(self):
710 cache = open(gitdir + "/p4-usercache.txt", "rb")
711 lines = cache.readlines()
714 entry = line[:-1].split("\t")
715 self.users[entry[0]] = entry[1]
717 self.getUserMapFromPerforceServer()
722 l = p4CmdList("labels %s..." % self.depotPath)
723 if len(l) > 0 and not self.silent:
724 print "Finding files belonging to labels in %s" % self.depotPath
727 label = output["label"]
731 print "Querying files for label %s" % label
732 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
733 revisions[file["depotFile"]] = file["rev"]
734 change = int(file["change"])
735 if change > newestChange:
736 newestChange = change
738 self.labels[newestChange] = [output, revisions]
741 print "Label changes: %s" % self.labels.keys()
743 def getBranchMapping(self):
744 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
746 for info in p4CmdList("branches"):
747 details = p4Cmd("branch -o %s" % info["branch"])
749 while details.has_key("View%s" % viewIdx):
750 paths = details["View%s" % viewIdx].split(" ")
751 viewIdx = viewIdx + 1
752 # require standard //depot/foo/... //depot/bar/... mapping
753 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
756 destination = paths[1]
757 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
758 source = source[len(self.depotPath):-4]
759 destination = destination[len(self.depotPath):-4]
760 if destination not in self.knownBranches:
761 self.knownBranches[destination] = source
762 if source not in self.knownBranches:
763 self.knownBranches[source] = source
765 def listExistingP4GitBranches(self):
766 self.p4BranchesInGit = []
768 cmdline = "git rev-parse --symbolic "
769 if self.importIntoRemotes:
770 cmdline += " --remotes"
772 cmdline += " --branches"
774 for line in mypopen(cmdline).readlines():
775 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
777 if self.importIntoRemotes:
782 self.p4BranchesInGit.append(branch)
783 self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
787 self.changeRange = ""
788 self.initialParent = ""
789 self.previousDepotPath = ""
790 # map from branch depot path to parent branch
791 self.knownBranches = {}
792 self.initialParents = {}
794 if self.importIntoRemotes:
795 self.refPrefix = "refs/remotes/p4/"
797 self.refPrefix = "refs/heads/"
799 createP4HeadRef = False;
801 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists(self.refPrefix + "master") and not self.detectBranches and self.importIntoRemotes:
802 ### needs to be ported to multi branch import
804 print "Syncing with origin first as requested by calling git fetch origin"
805 system("git fetch origin")
806 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
807 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
808 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
809 if originPreviousDepotPath == p4PreviousDepotPath:
810 originP4Change = int(originP4Change)
811 p4Change = int(p4Change)
812 if originP4Change > p4Change:
813 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
814 system("git update-ref " + self.refPrefix + "master origin");
816 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
818 if len(self.branch) == 0:
819 self.branch = self.refPrefix + "master"
820 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
821 system("git update-ref %s refs/heads/p4" % self.branch)
822 system("git branch -D p4");
823 # create it /after/ importing, when master exists
824 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
825 createP4HeadRef = True
827 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
828 self.listExistingP4GitBranches()
829 if len(self.p4BranchesInGit) > 1 and not self.silent:
830 print "Importing from/into multiple branches"
831 self.detectBranches = True
834 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
835 ### needs to be ported to multi branch import
837 print "Creating %s branch in git repository based on origin" % self.branch
839 if not branch.startswith("refs"):
840 branch = "refs/heads/" + branch
841 system("git update-ref %s origin" % branch)
844 print "branches: %s" % self.p4BranchesInGit
847 for branch in self.p4BranchesInGit:
848 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.refPrefix + branch))
851 print "path %s change %s" % (depotPath, change)
853 if len(depotPath) > 0 and len(change) > 0:
854 change = int(change) + 1
855 p4Change = max(p4Change, change)
857 if len(self.previousDepotPath) == 0:
858 self.previousDepotPath = depotPath
861 l = min(len(self.previousDepotPath), len(depotPath))
862 while i < l and self.previousDepotPath[i] == depotPath[i]:
864 self.previousDepotPath = self.previousDepotPath[:i]
867 self.depotPath = self.previousDepotPath
868 self.changeRange = "@%s,#head" % p4Change
869 self.initialParent = parseRevision(self.branch)
870 if not self.silent and not self.detectBranches:
871 print "Performing incremental import into %s git branch" % self.branch
873 if not self.branch.startswith("refs/"):
874 self.branch = "refs/heads/" + self.branch
876 if len(self.depotPath) != 0:
877 self.depotPath = self.depotPath[:-1]
879 if len(args) == 0 and len(self.depotPath) != 0:
881 print "Depot path: %s" % self.depotPath
885 if len(self.depotPath) != 0 and self.depotPath != args[0]:
886 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
888 self.depotPath = args[0]
893 if self.depotPath.find("@") != -1:
894 atIdx = self.depotPath.index("@")
895 self.changeRange = self.depotPath[atIdx:]
896 if self.changeRange == "@all":
897 self.changeRange = ""
898 elif self.changeRange.find(",") == -1:
899 self.revision = self.changeRange
900 self.changeRange = ""
901 self.depotPath = self.depotPath[0:atIdx]
902 elif self.depotPath.find("#") != -1:
903 hashIdx = self.depotPath.index("#")
904 self.revision = self.depotPath[hashIdx:]
905 self.depotPath = self.depotPath[0:hashIdx]
906 elif len(self.previousDepotPath) == 0:
907 self.revision = "#head"
909 if self.depotPath.endswith("..."):
910 self.depotPath = self.depotPath[:-3]
912 if not self.depotPath.endswith("/"):
913 self.depotPath += "/"
915 self.loadUserMapFromCache()
917 if self.detectLabels:
920 if self.detectBranches:
921 self.getBranchMapping();
923 print "p4-git branches: %s" % self.p4BranchesInGit
924 print "initial parents: %s" % self.initialParents
925 for b in self.p4BranchesInGit:
927 b = b[len(self.projectName):]
928 self.createdBranches.add(b)
930 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
932 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
933 self.gitOutput = importProcess.stdout
934 self.gitStream = importProcess.stdin
935 self.gitError = importProcess.stderr
937 if len(self.revision) > 0:
938 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
940 details = { "user" : "git perforce import user", "time" : int(time.time()) }
941 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
942 details["change"] = self.revision
946 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
947 change = int(info["change"])
948 if change > newestRevision:
949 newestRevision = change
951 if info["action"] == "delete":
952 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
953 #fileCnt = fileCnt + 1
956 for prop in [ "depotFile", "rev", "action", "type" ]:
957 details["%s%s" % (prop, fileCnt)] = info[prop]
959 fileCnt = fileCnt + 1
961 details["change"] = newestRevision
964 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
966 print "IO error with git fast-import. Is your git version recent enough?"
967 print self.gitError.read()
972 if len(self.changesFile) > 0:
973 output = open(self.changesFile).readlines()
976 changeSet.add(int(line))
978 for change in changeSet:
979 changes.append(change)
984 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
985 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
988 changeNum = line.split(" ")[1]
989 changes.append(changeNum)
993 if len(self.maxChanges) > 0:
994 changes = changes[0:min(int(self.maxChanges), len(changes))]
996 if len(changes) == 0:
998 print "No changes to import!"
1001 self.updatedBranches = set()
1004 for change in changes:
1005 description = p4Cmd("describe %s" % change)
1008 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1013 if self.detectBranches:
1014 branches = self.splitFilesIntoBranches(description)
1015 for branch in branches.keys():
1016 branchPrefix = self.depotPath + branch + "/"
1020 filesForCommit = branches[branch]
1023 print "branch is %s" % branch
1025 self.updatedBranches.add(branch)
1027 if branch not in self.createdBranches:
1028 self.createdBranches.add(branch)
1029 parent = self.knownBranches[branch]
1030 if parent == branch:
1033 print "parent determined through known branches: %s" % parent
1035 # main branch? use master
1036 if branch == "main":
1039 branch = self.projectName + branch
1041 if parent == "main":
1043 elif len(parent) > 0:
1044 parent = self.projectName + parent
1046 branch = self.refPrefix + branch
1048 parent = self.refPrefix + parent
1051 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1053 if len(parent) == 0 and branch in self.initialParents:
1054 parent = self.initialParents[branch]
1055 del self.initialParents[branch]
1057 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1059 files = self.extractFilesFromCommit(description)
1060 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1061 self.initialParent = ""
1063 print self.gitError.read()
1068 if len(self.updatedBranches) > 0:
1069 sys.stdout.write("Updated branches: ")
1070 for b in self.updatedBranches:
1071 sys.stdout.write("%s " % b)
1072 sys.stdout.write("\n")
1075 self.gitStream.close()
1076 if importProcess.wait() != 0:
1077 die("fast-import failed: %s" % self.gitError.read())
1078 self.gitOutput.close()
1079 self.gitError.close()
1082 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1086 class P4Rebase(Command):
1088 Command.__init__(self)
1089 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
1090 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1091 self.syncWithOrigin = False
1093 def run(self, args):
1095 sync.syncWithOrigin = self.syncWithOrigin
1097 print "Rebasing the current branch"
1098 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1099 system("git rebase p4")
1100 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1103 class P4Clone(P4Sync):
1105 P4Sync.__init__(self)
1106 self.description = "Creates a new git repository and imports from Perforce into it"
1107 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1108 self.needsGit = False
1110 def run(self, args):
1122 if not depotPath.startswith("//"):
1127 atPos = dir.rfind("@")
1130 hashPos = dir.rfind("#")
1132 dir = dir[0:hashPos]
1134 if dir.endswith("..."):
1137 if dir.endswith("/"):
1140 slashPos = dir.rfind("/")
1142 dir = dir[slashPos + 1:]
1144 print "Importing from %s into %s" % (depotPath, dir)
1148 gitdir = os.getcwd() + "/.git"
1149 if not P4Sync.run(self, [depotPath]):
1151 if self.branch != "master":
1152 if gitBranchExists("refs/remotes/p4/master"):
1153 system("git branch master refs/remotes/p4/master")
1154 system("git checkout -f")
1156 print "Could not detect main branch. No checkout/master branch created."
1159 class HelpFormatter(optparse.IndentedHelpFormatter):
1161 optparse.IndentedHelpFormatter.__init__(self)
1163 def format_description(self, description):
1165 return description + "\n"
1169 def printUsage(commands):
1170 print "usage: %s <command> [options]" % sys.argv[0]
1172 print "valid commands: %s" % ", ".join(commands)
1174 print "Try %s <command> --help for command specific help." % sys.argv[0]
1178 "debug" : P4Debug(),
1179 "submit" : P4Submit(),
1181 "rebase" : P4Rebase(),
1182 "clone" : P4Clone(),
1183 "rollback" : P4RollBack()
1186 if len(sys.argv[1:]) == 0:
1187 printUsage(commands.keys())
1191 cmdName = sys.argv[1]
1193 cmd = commands[cmdName]
1195 print "unknown command %s" % cmdName
1197 printUsage(commands.keys())
1200 options = cmd.options
1205 if len(options) > 0:
1206 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1208 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1210 description = cmd.description,
1211 formatter = HelpFormatter())
1213 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1217 if len(gitdir) == 0:
1219 if not isValidGitDir(gitdir):
1220 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1221 if os.path.exists(gitdir):
1222 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1226 if not isValidGitDir(gitdir):
1227 if isValidGitDir(gitdir + "/.git"):
1230 die("fatal: cannot locate git repository at %s" % gitdir)
1232 os.environ["GIT_DIR"] = gitdir
1234 if not cmd.run(args):