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)
45 def p4Where(depotPath):
46 if not depotPath.endswith("/"):
48 output = p4Cmd("where %s..." % depotPath)
49 if output["code"] == "error":
53 clientPath = output.get("path")
54 elif "data" in output:
55 data = output.get("data")
56 lastSpace = data.rfind(" ")
57 clientPath = data[lastSpace + 1:]
59 if clientPath.endswith("..."):
60 clientPath = clientPath[:-3]
64 sys.stderr.write(msg + "\n")
67 def currentGitBranch():
68 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
70 def isValidGitDir(path):
71 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
75 def parseRevision(ref):
76 return mypopen("git rev-parse %s" % ref).read()[:-1]
79 if os.system(cmd) != 0:
80 die("command failed: %s" % cmd)
82 def extractLogMessageFromGitCommit(commit):
85 for log in mypopen("git cat-file commit %s" % commit).readlines():
94 def extractDepotPathAndChangeFromGitLog(log):
96 for line in log.split("\n"):
98 if line.startswith("[git-p4:") and line.endswith("]"):
99 line = line[8:-1].strip()
100 for assignment in line.split(":"):
101 variable = assignment.strip()
103 equalPos = assignment.find("=")
105 variable = assignment[:equalPos].strip()
106 value = assignment[equalPos + 1:].strip()
107 if value.startswith("\"") and value.endswith("\""):
109 values[variable] = value
111 return values.get("depot-path"), values.get("change")
113 def gitBranchExists(branch):
114 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
115 return proc.wait() == 0;
119 self.usage = "usage: %prog [options]"
122 class P4Debug(Command):
124 Command.__init__(self)
127 self.description = "A tool to debug the output of p4 -G."
128 self.needsGit = False
131 for output in p4CmdList(" ".join(args)):
135 class P4RollBack(Command):
137 Command.__init__(self)
139 optparse.make_option("--verbose", dest="verbose", action="store_true"),
140 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
142 self.description = "A tool to debug the multi-branch import. Don't use :)"
144 self.rollbackLocalBranches = False
149 maxChange = int(args[0])
151 if self.rollbackLocalBranches:
152 refPrefix = "refs/heads/"
153 lines = mypopen("git rev-parse --symbolic --branches").readlines()
155 refPrefix = "refs/remotes/"
156 lines = mypopen("git rev-parse --symbolic --remotes").readlines()
159 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
160 ref = refPrefix + line[:-1]
161 log = extractLogMessageFromGitCommit(ref)
162 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
165 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
166 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
167 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
170 while len(change) > 0 and int(change) > maxChange:
173 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
174 system("git update-ref %s \"%s^\"" % (ref, ref))
175 log = extractLogMessageFromGitCommit(ref)
176 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
179 print "%s rewound to %s" % (ref, change)
183 class P4Submit(Command):
185 Command.__init__(self)
187 optparse.make_option("--continue", action="store_false", dest="firstTime"),
188 optparse.make_option("--origin", dest="origin"),
189 optparse.make_option("--reset", action="store_true", dest="reset"),
190 optparse.make_option("--log-substitutions", dest="substFile"),
191 optparse.make_option("--noninteractive", action="store_false"),
192 optparse.make_option("--dry-run", action="store_true"),
193 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
195 self.description = "Submit changes from git to the perforce depot."
196 self.usage += " [name of git branch to submit into perforce depot]"
197 self.firstTime = True
199 self.interactive = True
202 self.firstTime = True
204 self.directSubmit = False
206 self.logSubstitutions = {}
207 self.logSubstitutions["<enter description here>"] = "%log%"
208 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
211 if len(p4CmdList("opened ...")) > 0:
212 die("You have files opened with perforce! Close them before starting the sync.")
215 if len(self.config) > 0 and not self.reset:
216 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)
219 if self.directSubmit:
222 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
223 commits.append(line[:-1])
226 self.config["commits"] = commits
228 def prepareLogMessage(self, template, message):
231 for line in template.split("\n"):
232 if line.startswith("#"):
233 result += line + "\n"
237 for key in self.logSubstitutions.keys():
238 if line.find(key) != -1:
239 value = self.logSubstitutions[key]
240 value = value.replace("%log%", message)
241 if value != "@remove@":
242 result += line.replace(key, value) + "\n"
247 result += line + "\n"
252 if self.directSubmit:
253 print "Applying local change in working directory/index"
254 diff = self.diffStatus
256 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
257 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
259 filesToDelete = set()
263 path = line[1:].strip()
265 system("p4 edit \"%s\"" % path)
266 editedFiles.add(path)
267 elif modifier == "A":
269 if path in filesToDelete:
270 filesToDelete.remove(path)
271 elif modifier == "D":
272 filesToDelete.add(path)
273 if path in filesToAdd:
274 filesToAdd.remove(path)
276 die("unknown modifier %s for %s" % (modifier, path))
278 if self.directSubmit:
279 diffcmd = "cat \"%s\"" % self.diffFile
281 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
282 patchcmd = diffcmd + " | git apply "
283 tryPatchCmd = patchcmd + "--check -"
284 applyPatchCmd = patchcmd + "--check --apply -"
286 if os.system(tryPatchCmd) != 0:
287 print "Unfortunately applying the change failed!"
288 print "What do you want to do?"
290 while response != "s" and response != "a" and response != "w":
291 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) ")
293 print "Skipping! Good luck with the next patches..."
295 elif response == "a":
296 os.system(applyPatchCmd)
297 if len(filesToAdd) > 0:
298 print "You may also want to call p4 add on the following files:"
299 print " ".join(filesToAdd)
300 if len(filesToDelete):
301 print "The following files should be scheduled for deletion with p4 delete:"
302 print " ".join(filesToDelete)
303 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
304 elif response == "w":
305 system(diffcmd + " > patch.txt")
306 print "Patch saved to patch.txt in %s !" % self.clientPath
307 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
309 system(applyPatchCmd)
312 system("p4 add %s" % f)
313 for f in filesToDelete:
314 system("p4 revert %s" % f)
315 system("p4 delete %s" % f)
318 if not self.directSubmit:
319 logMessage = extractLogMessageFromGitCommit(id)
320 logMessage = logMessage.replace("\n", "\n\t")
321 logMessage = logMessage[:-1]
323 template = mypopen("p4 change -o").read()
326 submitTemplate = self.prepareLogMessage(template, logMessage)
327 diff = mypopen("p4 diff -du ...").read()
329 for newFile in filesToAdd:
330 diff += "==== new file ====\n"
331 diff += "--- /dev/null\n"
332 diff += "+++ %s\n" % newFile
333 f = open(newFile, "r")
334 for line in f.readlines():
338 separatorLine = "######## everything below this line is just the diff #######"
339 if platform.system() == "Windows":
340 separatorLine += "\r"
341 separatorLine += "\n"
344 firstIteration = True
345 while response == "e":
346 if not firstIteration:
347 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
348 firstIteration = False
350 [handle, fileName] = tempfile.mkstemp()
351 tmpFile = os.fdopen(handle, "w+")
352 tmpFile.write(submitTemplate + separatorLine + diff)
355 if platform.system() == "Windows":
356 defaultEditor = "notepad"
357 editor = os.environ.get("EDITOR", defaultEditor);
358 system(editor + " " + fileName)
359 tmpFile = open(fileName, "rb")
360 message = tmpFile.read()
363 submitTemplate = message[:message.index(separatorLine)]
365 if response == "y" or response == "yes":
368 raw_input("Press return to continue...")
370 if self.directSubmit:
371 print "Submitting to git first"
372 os.chdir(self.oldWorkingDirectory)
373 pipe = os.popen("git commit -a -F -", "wb")
374 pipe.write(submitTemplate)
376 os.chdir(self.clientPath)
378 pipe = os.popen("p4 submit -i", "wb")
379 pipe.write(submitTemplate)
381 elif response == "s":
382 for f in editedFiles:
383 system("p4 revert \"%s\"" % f);
385 system("p4 revert \"%s\"" % f);
387 for f in filesToDelete:
388 system("p4 delete \"%s\"" % f);
391 print "Not submitting!"
392 self.interactive = False
394 fileName = "submit.txt"
395 file = open(fileName, "w+")
396 file.write(self.prepareLogMessage(template, logMessage))
398 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
402 # make gitdir absolute so we can cd out into the perforce checkout
403 gitdir = os.path.abspath(gitdir)
404 os.environ["GIT_DIR"] = gitdir
407 self.master = currentGitBranch()
408 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
409 die("Detecting current git branch failed!")
411 self.master = args[0]
416 if gitBranchExists("p4"):
417 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
418 if len(depotPath) == 0 and gitBranchExists("origin"):
419 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
421 if len(depotPath) == 0:
422 print "Internal error: cannot locate perforce depot path from existing branches"
425 self.clientPath = p4Where(depotPath)
427 if len(self.clientPath) == 0:
428 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
431 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
432 self.oldWorkingDirectory = os.getcwd()
434 if self.directSubmit:
435 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
436 if len(self.diffStatus) == 0:
437 print "No changes in working directory to submit."
439 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
440 self.diffFile = gitdir + "/p4-git-diff"
441 f = open(self.diffFile, "wb")
445 os.chdir(self.clientPath)
446 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
447 if response == "y" or response == "yes":
448 system("p4 sync ...")
450 if len(self.origin) == 0:
451 if gitBranchExists("p4"):
454 self.origin = "origin"
457 self.firstTime = True
459 if len(self.substFile) > 0:
460 for line in open(self.substFile, "r").readlines():
461 tokens = line[:-1].split("=")
462 self.logSubstitutions[tokens[0]] = tokens[1]
465 self.configFile = gitdir + "/p4-git-sync.cfg"
466 self.config = shelve.open(self.configFile, writeback=True)
471 commits = self.config.get("commits", [])
473 while len(commits) > 0:
474 self.firstTime = False
476 commits = commits[1:]
477 self.config["commits"] = commits
479 if not self.interactive:
484 if self.directSubmit:
485 os.remove(self.diffFile)
487 if len(commits) == 0:
489 print "No changes found to apply between %s and current HEAD" % self.origin
491 print "All changes applied!"
492 os.chdir(self.oldWorkingDirectory)
493 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
494 if response == "y" or response == "yes":
497 os.remove(self.configFile)
501 class P4Sync(Command):
503 Command.__init__(self)
505 optparse.make_option("--branch", dest="branch"),
506 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
507 optparse.make_option("--changesfile", dest="changesFile"),
508 optparse.make_option("--silent", dest="silent", action="store_true"),
509 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
510 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
511 optparse.make_option("--verbose", dest="verbose", action="store_true"),
512 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
513 optparse.make_option("--max-changes", dest="maxChanges")
515 self.description = """Imports from Perforce into a git repository.\n
517 //depot/my/project/ -- to import the current head
518 //depot/my/project/@all -- to import everything
519 //depot/my/project/@1,6 -- to import only from revision 1 to 6
521 (a ... is not needed in the path p4 specification, it's added implicitly)"""
523 self.usage += " //depot/path[@revRange]"
526 self.createdBranches = Set()
527 self.committedChanges = Set()
529 self.detectBranches = False
530 self.detectLabels = False
531 self.changesFile = ""
532 self.syncWithOrigin = False
534 self.importIntoRemotes = True
537 def p4File(self, depotPath):
538 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
540 def extractFilesFromCommit(self, commit):
543 while commit.has_key("depotFile%s" % fnum):
544 path = commit["depotFile%s" % fnum]
545 if not path.startswith(self.depotPath):
546 # if not self.silent:
547 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
553 file["rev"] = commit["rev%s" % fnum]
554 file["action"] = commit["action%s" % fnum]
555 file["type"] = commit["type%s" % fnum]
560 def splitFilesIntoBranches(self, commit):
564 while commit.has_key("depotFile%s" % fnum):
565 path = commit["depotFile%s" % fnum]
566 if not path.startswith(self.depotPath):
567 # if not self.silent:
568 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
574 file["rev"] = commit["rev%s" % fnum]
575 file["action"] = commit["action%s" % fnum]
576 file["type"] = commit["type%s" % fnum]
579 relPath = path[len(self.depotPath):]
581 for branch in self.knownBranches.keys():
582 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
583 if branch not in branches:
584 branches[branch] = []
585 branches[branch].append(file)
589 def commit(self, details, files, branch, branchPrefix, parent = ""):
590 epoch = details["time"]
591 author = details["user"]
594 print "commit into %s" % branch
596 self.gitStream.write("commit %s\n" % branch)
597 # gitStream.write("mark :%s\n" % details["change"])
598 self.committedChanges.add(int(details["change"]))
600 if author not in self.users:
601 self.getUserMapFromPerforceServer()
602 if author in self.users:
603 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
605 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
607 self.gitStream.write("committer %s\n" % committer)
609 self.gitStream.write("data <<EOT\n")
610 self.gitStream.write(details["desc"])
611 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
612 self.gitStream.write("EOT\n\n")
616 print "parent %s" % parent
617 self.gitStream.write("from %s\n" % parent)
621 if not path.startswith(branchPrefix):
623 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
626 depotPath = path + "#" + rev
627 relPath = path[len(branchPrefix):]
628 action = file["action"]
630 if file["type"] == "apple":
631 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
634 if action == "delete":
635 self.gitStream.write("D %s\n" % relPath)
638 if file["type"].startswith("x"):
641 data = self.p4File(depotPath)
643 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
644 self.gitStream.write("data %s\n" % len(data))
645 self.gitStream.write(data)
646 self.gitStream.write("\n")
648 self.gitStream.write("\n")
650 change = int(details["change"])
652 if self.labels.has_key(change):
653 label = self.labels[change]
654 labelDetails = label[0]
655 labelRevisions = label[1]
657 print "Change %s is labelled %s" % (change, labelDetails)
659 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
661 if len(files) == len(labelRevisions):
665 if info["action"] == "delete":
667 cleanedFiles[info["depotFile"]] = info["rev"]
669 if cleanedFiles == labelRevisions:
670 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
671 self.gitStream.write("from %s\n" % branch)
673 owner = labelDetails["Owner"]
675 if author in self.users:
676 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
678 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
679 self.gitStream.write("tagger %s\n" % tagger)
680 self.gitStream.write("data <<EOT\n")
681 self.gitStream.write(labelDetails["Description"])
682 self.gitStream.write("EOT\n\n")
686 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
690 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
692 def getUserMapFromPerforceServer(self):
695 for output in p4CmdList("users"):
696 if not output.has_key("User"):
698 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
700 cache = open(gitdir + "/p4-usercache.txt", "wb")
701 for user in self.users.keys():
702 cache.write("%s\t%s\n" % (user, self.users[user]))
705 def loadUserMapFromCache(self):
708 cache = open(gitdir + "/p4-usercache.txt", "rb")
709 lines = cache.readlines()
712 entry = line[:-1].split("\t")
713 self.users[entry[0]] = entry[1]
715 self.getUserMapFromPerforceServer()
720 l = p4CmdList("labels %s..." % self.depotPath)
721 if len(l) > 0 and not self.silent:
722 print "Finding files belonging to labels in %s" % self.depotPath
725 label = output["label"]
729 print "Querying files for label %s" % label
730 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
731 revisions[file["depotFile"]] = file["rev"]
732 change = int(file["change"])
733 if change > newestChange:
734 newestChange = change
736 self.labels[newestChange] = [output, revisions]
739 print "Label changes: %s" % self.labels.keys()
741 def getBranchMapping(self):
742 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
744 for info in p4CmdList("branches"):
745 details = p4Cmd("branch -o %s" % info["branch"])
747 while details.has_key("View%s" % viewIdx):
748 paths = details["View%s" % viewIdx].split(" ")
749 viewIdx = viewIdx + 1
750 # require standard //depot/foo/... //depot/bar/... mapping
751 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
754 destination = paths[1]
755 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
756 source = source[len(self.depotPath):-4]
757 destination = destination[len(self.depotPath):-4]
758 if destination not in self.knownBranches:
759 self.knownBranches[destination] = source
760 if source not in self.knownBranches:
761 self.knownBranches[source] = source
763 def listExistingP4GitBranches(self):
764 self.p4BranchesInGit = []
766 cmdline = "git rev-parse --symbolic "
767 if self.importIntoRemotes:
768 cmdline += " --remotes"
770 cmdline += " --branches"
772 for line in mypopen(cmdline).readlines():
773 if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
775 if self.importIntoRemotes:
780 self.p4BranchesInGit.append(branch)
781 self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
785 self.changeRange = ""
786 self.initialParent = ""
787 self.previousDepotPath = ""
788 # map from branch depot path to parent branch
789 self.knownBranches = {}
790 self.initialParents = {}
792 if self.importIntoRemotes:
793 self.refPrefix = "refs/remotes/p4/"
795 self.refPrefix = "refs/heads/"
797 createP4HeadRef = False;
799 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists(self.refPrefix + "master") and not self.detectBranches and self.importIntoRemotes:
800 ### needs to be ported to multi branch import
802 print "Syncing with origin first as requested by calling git fetch origin"
803 system("git fetch origin")
804 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
805 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
806 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
807 if originPreviousDepotPath == p4PreviousDepotPath:
808 originP4Change = int(originP4Change)
809 p4Change = int(p4Change)
810 if originP4Change > p4Change:
811 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
812 system("git update-ref " + self.refPrefix + "master origin");
814 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
816 if len(self.branch) == 0:
817 self.branch = self.refPrefix + "master"
818 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
819 system("git update-ref %s refs/heads/p4" % self.branch)
820 system("git branch -D p4");
821 # create it /after/ importing, when master exists
822 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
823 createP4HeadRef = True
825 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
826 self.listExistingP4GitBranches()
827 if len(self.p4BranchesInGit) > 1 and not self.silent:
828 print "Importing from/into multiple branches"
829 self.detectBranches = True
832 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
833 ### needs to be ported to multi branch import
835 print "Creating %s branch in git repository based on origin" % self.branch
837 if not branch.startswith("refs"):
838 branch = "refs/heads/" + branch
839 system("git update-ref %s origin" % branch)
842 print "branches: %s" % self.p4BranchesInGit
845 for branch in self.p4BranchesInGit:
846 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.refPrefix + branch))
849 print "path %s change %s" % (depotPath, change)
851 if len(depotPath) > 0 and len(change) > 0:
852 change = int(change) + 1
853 p4Change = max(p4Change, change)
855 if len(self.previousDepotPath) == 0:
856 self.previousDepotPath = depotPath
859 l = min(len(self.previousDepotPath), len(depotPath))
860 while i < l and self.previousDepotPath[i] == depotPath[i]:
862 self.previousDepotPath = self.previousDepotPath[:i]
865 self.depotPath = self.previousDepotPath
866 self.changeRange = "@%s,#head" % p4Change
867 self.initialParent = parseRevision(self.branch)
868 if not self.silent and not self.detectBranches:
869 print "Performing incremental import into %s git branch" % self.branch
871 if not self.branch.startswith("refs/"):
872 self.branch = "refs/heads/" + self.branch
874 if len(self.depotPath) != 0:
875 self.depotPath = self.depotPath[:-1]
877 if len(args) == 0 and len(self.depotPath) != 0:
879 print "Depot path: %s" % self.depotPath
883 if len(self.depotPath) != 0 and self.depotPath != args[0]:
884 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
886 self.depotPath = args[0]
891 if self.depotPath.find("@") != -1:
892 atIdx = self.depotPath.index("@")
893 self.changeRange = self.depotPath[atIdx:]
894 if self.changeRange == "@all":
895 self.changeRange = ""
896 elif self.changeRange.find(",") == -1:
897 self.revision = self.changeRange
898 self.changeRange = ""
899 self.depotPath = self.depotPath[0:atIdx]
900 elif self.depotPath.find("#") != -1:
901 hashIdx = self.depotPath.index("#")
902 self.revision = self.depotPath[hashIdx:]
903 self.depotPath = self.depotPath[0:hashIdx]
904 elif len(self.previousDepotPath) == 0:
905 self.revision = "#head"
907 if self.depotPath.endswith("..."):
908 self.depotPath = self.depotPath[:-3]
910 if not self.depotPath.endswith("/"):
911 self.depotPath += "/"
913 self.loadUserMapFromCache()
915 if self.detectLabels:
918 if self.detectBranches:
919 self.getBranchMapping();
921 print "p4-git branches: %s" % self.p4BranchesInGit
922 print "initial parents: %s" % self.initialParents
923 for b in self.p4BranchesInGit:
925 b = b[len(self.projectName):]
926 self.createdBranches.add(b)
928 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
930 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
931 self.gitOutput = importProcess.stdout
932 self.gitStream = importProcess.stdin
933 self.gitError = importProcess.stderr
935 if len(self.revision) > 0:
936 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
938 details = { "user" : "git perforce import user", "time" : int(time.time()) }
939 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
940 details["change"] = self.revision
944 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
945 change = int(info["change"])
946 if change > newestRevision:
947 newestRevision = change
949 if info["action"] == "delete":
950 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
951 #fileCnt = fileCnt + 1
954 for prop in [ "depotFile", "rev", "action", "type" ]:
955 details["%s%s" % (prop, fileCnt)] = info[prop]
957 fileCnt = fileCnt + 1
959 details["change"] = newestRevision
962 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
964 print "IO error with git fast-import. Is your git version recent enough?"
965 print self.gitError.read()
970 if len(self.changesFile) > 0:
971 output = open(self.changesFile).readlines()
974 changeSet.add(int(line))
976 for change in changeSet:
977 changes.append(change)
982 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
983 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
986 changeNum = line.split(" ")[1]
987 changes.append(changeNum)
991 if len(self.maxChanges) > 0:
992 changes = changes[0:min(int(self.maxChanges), len(changes))]
994 if len(changes) == 0:
996 print "No changes to import!"
999 self.updatedBranches = set()
1002 for change in changes:
1003 description = p4Cmd("describe %s" % change)
1006 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1011 if self.detectBranches:
1012 branches = self.splitFilesIntoBranches(description)
1013 for branch in branches.keys():
1014 branchPrefix = self.depotPath + branch + "/"
1018 filesForCommit = branches[branch]
1021 print "branch is %s" % branch
1023 self.updatedBranches.add(branch)
1025 if branch not in self.createdBranches:
1026 self.createdBranches.add(branch)
1027 parent = self.knownBranches[branch]
1028 if parent == branch:
1031 print "parent determined through known branches: %s" % parent
1033 # main branch? use master
1034 if branch == "main":
1037 branch = self.projectName + branch
1039 if parent == "main":
1041 elif len(parent) > 0:
1042 parent = self.projectName + parent
1044 branch = self.refPrefix + branch
1046 parent = self.refPrefix + parent
1049 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1051 if len(parent) == 0 and branch in self.initialParents:
1052 parent = self.initialParents[branch]
1053 del self.initialParents[branch]
1055 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1057 files = self.extractFilesFromCommit(description)
1058 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1059 self.initialParent = ""
1061 print self.gitError.read()
1066 if len(self.updatedBranches) > 0:
1067 sys.stdout.write("Updated branches: ")
1068 for b in self.updatedBranches:
1069 sys.stdout.write("%s " % b)
1070 sys.stdout.write("\n")
1073 self.gitStream.close()
1074 if importProcess.wait() != 0:
1075 die("fast-import failed: %s" % self.gitError.read())
1076 self.gitOutput.close()
1077 self.gitError.close()
1080 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1084 class P4Rebase(Command):
1086 Command.__init__(self)
1087 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
1088 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1089 self.syncWithOrigin = False
1091 def run(self, args):
1093 sync.syncWithOrigin = self.syncWithOrigin
1095 print "Rebasing the current branch"
1096 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1097 system("git rebase p4")
1098 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1101 class P4Clone(P4Sync):
1103 P4Sync.__init__(self)
1104 self.description = "Creates a new git repository and imports from Perforce into it"
1105 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1106 self.needsGit = False
1108 def run(self, args):
1120 if not depotPath.startswith("//"):
1125 atPos = dir.rfind("@")
1128 hashPos = dir.rfind("#")
1130 dir = dir[0:hashPos]
1132 if dir.endswith("..."):
1135 if dir.endswith("/"):
1138 slashPos = dir.rfind("/")
1140 dir = dir[slashPos + 1:]
1142 print "Importing from %s into %s" % (depotPath, dir)
1146 gitdir = os.getcwd() + "/.git"
1147 if not P4Sync.run(self, [depotPath]):
1149 if self.branch != "master":
1150 if gitBranchExists("refs/remotes/p4/master"):
1151 system("git branch master refs/remotes/p4/master")
1152 system("git checkout -f")
1154 print "Could not detect main branch. No checkout/master branch created."
1157 class HelpFormatter(optparse.IndentedHelpFormatter):
1159 optparse.IndentedHelpFormatter.__init__(self)
1161 def format_description(self, description):
1163 return description + "\n"
1167 def printUsage(commands):
1168 print "usage: %s <command> [options]" % sys.argv[0]
1170 print "valid commands: %s" % ", ".join(commands)
1172 print "Try %s <command> --help for command specific help." % sys.argv[0]
1176 "debug" : P4Debug(),
1177 "submit" : P4Submit(),
1179 "rebase" : P4Rebase(),
1180 "clone" : P4Clone(),
1181 "rollback" : P4RollBack()
1184 if len(sys.argv[1:]) == 0:
1185 printUsage(commands.keys())
1189 cmdName = sys.argv[1]
1191 cmd = commands[cmdName]
1193 print "unknown command %s" % cmdName
1195 printUsage(commands.keys())
1198 options = cmd.options
1203 if len(options) > 0:
1204 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1206 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1208 description = cmd.description,
1209 formatter = HelpFormatter())
1211 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1215 if len(gitdir) == 0:
1217 if not isValidGitDir(gitdir):
1218 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1219 if os.path.exists(gitdir):
1220 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1224 if not isValidGitDir(gitdir):
1225 if isValidGitDir(gitdir + "/.git"):
1228 die("fatal: cannot locate git repository at %s" % gitdir)
1230 os.environ["GIT_DIR"] = gitdir
1232 if not cmd.run(args):