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: * implement git-p4 rollback <perforce change number> for debugging
11 # to roll back all p4 remote branches to a commit older or equal to
12 # the specified change.
15 import optparse, sys, os, marshal, popen2, subprocess, shelve
16 import tempfile, getopt, sha, os.path, time, platform
19 gitdir = os.environ.get("GIT_DIR", "")
22 return os.popen(command, "rb");
25 cmd = "p4 -G %s" % cmd
26 pipe = os.popen(cmd, "rb")
31 entry = marshal.load(pipe)
46 def p4Where(depotPath):
47 if not depotPath.endswith("/"):
49 output = p4Cmd("where %s..." % depotPath)
52 clientPath = output.get("path")
53 elif "data" in output:
54 data = output.get("data")
55 lastSpace = data.rfind(" ")
56 clientPath = data[lastSpace + 1:]
58 if clientPath.endswith("..."):
59 clientPath = clientPath[:-3]
63 sys.stderr.write(msg + "\n")
66 def currentGitBranch():
67 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
69 def isValidGitDir(path):
70 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
74 def parseRevision(ref):
75 return mypopen("git rev-parse %s" % ref).read()[:-1]
78 if os.system(cmd) != 0:
79 die("command failed: %s" % cmd)
81 def extractLogMessageFromGitCommit(commit):
84 for log in mypopen("git cat-file commit %s" % commit).readlines():
93 def extractDepotPathAndChangeFromGitLog(log):
95 for line in log.split("\n"):
97 if line.startswith("[git-p4:") and line.endswith("]"):
98 line = line[8:-1].strip()
99 for assignment in line.split(":"):
100 variable = assignment.strip()
102 equalPos = assignment.find("=")
104 variable = assignment[:equalPos].strip()
105 value = assignment[equalPos + 1:].strip()
106 if value.startswith("\"") and value.endswith("\""):
108 values[variable] = value
110 return values.get("depot-path"), values.get("change")
112 def gitBranchExists(branch):
113 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
114 return proc.wait() == 0;
118 self.usage = "usage: %prog [options]"
121 class P4Debug(Command):
123 Command.__init__(self)
126 self.description = "A tool to debug the output of p4 -G."
127 self.needsGit = False
130 for output in p4CmdList(" ".join(args)):
134 class P4Submit(Command):
136 Command.__init__(self)
138 optparse.make_option("--continue", action="store_false", dest="firstTime"),
139 optparse.make_option("--origin", dest="origin"),
140 optparse.make_option("--reset", action="store_true", dest="reset"),
141 optparse.make_option("--log-substitutions", dest="substFile"),
142 optparse.make_option("--noninteractive", action="store_false"),
143 optparse.make_option("--dry-run", action="store_true"),
144 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
146 self.description = "Submit changes from git to the perforce depot."
147 self.usage += " [name of git branch to submit into perforce depot]"
148 self.firstTime = True
150 self.interactive = True
153 self.firstTime = True
155 self.directSubmit = False
157 self.logSubstitutions = {}
158 self.logSubstitutions["<enter description here>"] = "%log%"
159 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
162 if len(p4CmdList("opened ...")) > 0:
163 die("You have files opened with perforce! Close them before starting the sync.")
166 if len(self.config) > 0 and not self.reset:
167 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)
170 if self.directSubmit:
173 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
174 commits.append(line[:-1])
177 self.config["commits"] = commits
179 def prepareLogMessage(self, template, message):
182 for line in template.split("\n"):
183 if line.startswith("#"):
184 result += line + "\n"
188 for key in self.logSubstitutions.keys():
189 if line.find(key) != -1:
190 value = self.logSubstitutions[key]
191 value = value.replace("%log%", message)
192 if value != "@remove@":
193 result += line.replace(key, value) + "\n"
198 result += line + "\n"
203 if self.directSubmit:
204 print "Applying local change in working directory/index"
205 diff = self.diffStatus
207 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
208 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
210 filesToDelete = set()
214 path = line[1:].strip()
216 system("p4 edit \"%s\"" % path)
217 editedFiles.add(path)
218 elif modifier == "A":
220 if path in filesToDelete:
221 filesToDelete.remove(path)
222 elif modifier == "D":
223 filesToDelete.add(path)
224 if path in filesToAdd:
225 filesToAdd.remove(path)
227 die("unknown modifier %s for %s" % (modifier, path))
229 if self.directSubmit:
230 diffcmd = "cat \"%s\"" % self.diffFile
232 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
233 patchcmd = diffcmd + " | git apply "
234 tryPatchCmd = patchcmd + "--check -"
235 applyPatchCmd = patchcmd + "--check --apply -"
237 if os.system(tryPatchCmd) != 0:
238 print "Unfortunately applying the change failed!"
239 print "What do you want to do?"
241 while response != "s" and response != "a" and response != "w":
242 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) ")
244 print "Skipping! Good luck with the next patches..."
246 elif response == "a":
247 os.system(applyPatchCmd)
248 if len(filesToAdd) > 0:
249 print "You may also want to call p4 add on the following files:"
250 print " ".join(filesToAdd)
251 if len(filesToDelete):
252 print "The following files should be scheduled for deletion with p4 delete:"
253 print " ".join(filesToDelete)
254 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
255 elif response == "w":
256 system(diffcmd + " > patch.txt")
257 print "Patch saved to patch.txt in %s !" % self.clientPath
258 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
260 system(applyPatchCmd)
263 system("p4 add %s" % f)
264 for f in filesToDelete:
265 system("p4 revert %s" % f)
266 system("p4 delete %s" % f)
269 if not self.directSubmit:
270 logMessage = extractLogMessageFromGitCommit(id)
271 logMessage = logMessage.replace("\n", "\n\t")
272 logMessage = logMessage[:-1]
274 template = mypopen("p4 change -o").read()
277 submitTemplate = self.prepareLogMessage(template, logMessage)
278 diff = mypopen("p4 diff -du ...").read()
280 for newFile in filesToAdd:
281 diff += "==== new file ====\n"
282 diff += "--- /dev/null\n"
283 diff += "+++ %s\n" % newFile
284 f = open(newFile, "r")
285 for line in f.readlines():
289 separatorLine = "######## everything below this line is just the diff #######"
290 if platform.system() == "Windows":
291 separatorLine += "\r"
292 separatorLine += "\n"
295 firstIteration = True
296 while response == "e":
297 if not firstIteration:
298 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
299 firstIteration = False
301 [handle, fileName] = tempfile.mkstemp()
302 tmpFile = os.fdopen(handle, "w+")
303 tmpFile.write(submitTemplate + separatorLine + diff)
306 if platform.system() == "Windows":
307 defaultEditor = "notepad"
308 editor = os.environ.get("EDITOR", defaultEditor);
309 system(editor + " " + fileName)
310 tmpFile = open(fileName, "rb")
311 message = tmpFile.read()
314 submitTemplate = message[:message.index(separatorLine)]
316 if response == "y" or response == "yes":
319 raw_input("Press return to continue...")
321 pipe = os.popen("p4 submit -i", "wb")
322 pipe.write(submitTemplate)
324 elif response == "s":
325 for f in editedFiles:
326 system("p4 revert \"%s\"" % f);
328 system("p4 revert \"%s\"" % f);
330 for f in filesToDelete:
331 system("p4 delete \"%s\"" % f);
334 print "Not submitting!"
335 self.interactive = False
337 fileName = "submit.txt"
338 file = open(fileName, "w+")
339 file.write(self.prepareLogMessage(template, logMessage))
341 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
345 # make gitdir absolute so we can cd out into the perforce checkout
346 gitdir = os.path.abspath(gitdir)
347 os.environ["GIT_DIR"] = gitdir
350 self.master = currentGitBranch()
351 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
352 die("Detecting current git branch failed!")
354 self.master = args[0]
359 if gitBranchExists("p4"):
360 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
361 if len(depotPath) == 0 and gitBranchExists("origin"):
362 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
364 if len(depotPath) == 0:
365 print "Internal error: cannot locate perforce depot path from existing branches"
368 self.clientPath = p4Where(depotPath)
370 if len(self.clientPath) == 0:
371 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
374 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
375 oldWorkingDirectory = os.getcwd()
377 if self.directSubmit:
378 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
379 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
380 self.diffFile = gitdir + "/p4-git-diff"
381 f = open(self.diffFile, "wb")
385 os.chdir(self.clientPath)
386 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
387 if response == "y" or response == "yes":
388 system("p4 sync ...")
390 if len(self.origin) == 0:
391 if gitBranchExists("p4"):
394 self.origin = "origin"
397 self.firstTime = True
399 if len(self.substFile) > 0:
400 for line in open(self.substFile, "r").readlines():
401 tokens = line[:-1].split("=")
402 self.logSubstitutions[tokens[0]] = tokens[1]
405 self.configFile = gitdir + "/p4-git-sync.cfg"
406 self.config = shelve.open(self.configFile, writeback=True)
411 commits = self.config.get("commits", [])
413 while len(commits) > 0:
414 self.firstTime = False
416 commits = commits[1:]
417 self.config["commits"] = commits
419 if not self.interactive:
424 if self.directSubmit:
425 os.remove(self.diffFile)
427 if len(commits) == 0:
429 print "No changes found to apply between %s and current HEAD" % self.origin
431 print "All changes applied!"
433 os.chdir(oldWorkingDirectory)
435 if self.directSubmit:
436 response = raw_input("Do you want to DISCARD your git WORKING DIRECTORY CHANGES and sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
437 if response == "y" or response == "yes":
438 system("git reset --hard")
440 if len(response) == 0:
441 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
442 if response == "y" or response == "yes":
445 os.remove(self.configFile)
449 class P4Sync(Command):
451 Command.__init__(self)
453 optparse.make_option("--branch", dest="branch"),
454 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
455 optparse.make_option("--changesfile", dest="changesFile"),
456 optparse.make_option("--silent", dest="silent", action="store_true"),
457 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
458 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
459 optparse.make_option("--verbose", dest="verbose", action="store_true")
461 self.description = """Imports from Perforce into a git repository.\n
463 //depot/my/project/ -- to import the current head
464 //depot/my/project/@all -- to import everything
465 //depot/my/project/@1,6 -- to import only from revision 1 to 6
467 (a ... is not needed in the path p4 specification, it's added implicitly)"""
469 self.usage += " //depot/path[@revRange]"
472 self.createdBranches = Set()
473 self.committedChanges = Set()
475 self.detectBranches = False
476 self.detectLabels = False
477 self.changesFile = ""
478 self.syncWithOrigin = False
481 def p4File(self, depotPath):
482 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
484 def extractFilesFromCommit(self, commit):
487 while commit.has_key("depotFile%s" % fnum):
488 path = commit["depotFile%s" % fnum]
489 if not path.startswith(self.depotPath):
490 # if not self.silent:
491 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
497 file["rev"] = commit["rev%s" % fnum]
498 file["action"] = commit["action%s" % fnum]
499 file["type"] = commit["type%s" % fnum]
504 def splitFilesIntoBranches(self, commit):
508 while commit.has_key("depotFile%s" % fnum):
509 path = commit["depotFile%s" % fnum]
510 if not path.startswith(self.depotPath):
511 # if not self.silent:
512 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
518 file["rev"] = commit["rev%s" % fnum]
519 file["action"] = commit["action%s" % fnum]
520 file["type"] = commit["type%s" % fnum]
523 relPath = path[len(self.depotPath):]
525 for branch in self.knownBranches.keys():
526 if relPath.startswith(branch):
527 if branch not in branches:
528 branches[branch] = []
529 branches[branch].append(file)
533 def commit(self, details, files, branch, branchPrefix, parent = ""):
534 epoch = details["time"]
535 author = details["user"]
538 print "commit into %s" % branch
540 self.gitStream.write("commit %s\n" % branch)
541 # gitStream.write("mark :%s\n" % details["change"])
542 self.committedChanges.add(int(details["change"]))
544 if author not in self.users:
545 self.getUserMapFromPerforceServer()
546 if author in self.users:
547 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
549 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
551 self.gitStream.write("committer %s\n" % committer)
553 self.gitStream.write("data <<EOT\n")
554 self.gitStream.write(details["desc"])
555 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
556 self.gitStream.write("EOT\n\n")
560 print "parent %s" % parent
561 self.gitStream.write("from %s\n" % parent)
565 if not path.startswith(branchPrefix):
567 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
570 depotPath = path + "#" + rev
571 relPath = path[len(branchPrefix):]
572 action = file["action"]
574 if file["type"] == "apple":
575 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
578 if action == "delete":
579 self.gitStream.write("D %s\n" % relPath)
582 if file["type"].startswith("x"):
585 data = self.p4File(depotPath)
587 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
588 self.gitStream.write("data %s\n" % len(data))
589 self.gitStream.write(data)
590 self.gitStream.write("\n")
592 self.gitStream.write("\n")
594 change = int(details["change"])
596 if self.labels.has_key(change):
597 label = self.labels[change]
598 labelDetails = label[0]
599 labelRevisions = label[1]
601 print "Change %s is labelled %s" % (change, labelDetails)
603 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
605 if len(files) == len(labelRevisions):
609 if info["action"] == "delete":
611 cleanedFiles[info["depotFile"]] = info["rev"]
613 if cleanedFiles == labelRevisions:
614 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
615 self.gitStream.write("from %s\n" % branch)
617 owner = labelDetails["Owner"]
619 if author in self.users:
620 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
622 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
623 self.gitStream.write("tagger %s\n" % tagger)
624 self.gitStream.write("data <<EOT\n")
625 self.gitStream.write(labelDetails["Description"])
626 self.gitStream.write("EOT\n\n")
630 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
634 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
636 def getUserMapFromPerforceServer(self):
639 for output in p4CmdList("users"):
640 if not output.has_key("User"):
642 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
644 cache = open(gitdir + "/p4-usercache.txt", "wb")
645 for user in self.users.keys():
646 cache.write("%s\t%s\n" % (user, self.users[user]))
649 def loadUserMapFromCache(self):
652 cache = open(gitdir + "/p4-usercache.txt", "rb")
653 lines = cache.readlines()
656 entry = line[:-1].split("\t")
657 self.users[entry[0]] = entry[1]
659 self.getUserMapFromPerforceServer()
664 l = p4CmdList("labels %s..." % self.depotPath)
665 if len(l) > 0 and not self.silent:
666 print "Finding files belonging to labels in %s" % self.depotPath
669 label = output["label"]
673 print "Querying files for label %s" % label
674 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
675 revisions[file["depotFile"]] = file["rev"]
676 change = int(file["change"])
677 if change > newestChange:
678 newestChange = change
680 self.labels[newestChange] = [output, revisions]
683 print "Label changes: %s" % self.labels.keys()
685 def getBranchMapping(self):
686 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
688 for info in p4CmdList("branches"):
689 details = p4Cmd("branch -o %s" % info["branch"])
691 while details.has_key("View%s" % viewIdx):
692 paths = details["View%s" % viewIdx].split(" ")
693 viewIdx = viewIdx + 1
694 # require standard //depot/foo/... //depot/bar/... mapping
695 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
698 destination = paths[1]
699 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
700 source = source[len(self.depotPath):-4]
701 destination = destination[len(self.depotPath):-4]
702 if destination not in self.knownBranches:
703 self.knownBranches[destination] = source
704 if source not in self.knownBranches:
705 self.knownBranches[source] = source
707 def listExistingP4GitBranches(self):
708 self.p4BranchesInGit = []
710 for line in mypopen("git rev-parse --symbolic --remotes").readlines():
711 if line.startswith("p4/") and line != "p4/HEAD\n":
713 self.p4BranchesInGit.append(branch)
714 self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1])
718 self.changeRange = ""
719 self.initialParent = ""
720 self.previousDepotPath = ""
721 # map from branch depot path to parent branch
722 self.knownBranches = {}
723 self.initialParents = {}
725 self.listExistingP4GitBranches()
726 if len(self.p4BranchesInGit) > 1:
727 print "Importing from/into multiple branches"
728 self.detectBranches = True
730 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
731 ### needs to be ported to multi branch import
733 print "Syncing with origin first as requested by calling git fetch origin"
734 system("git fetch origin")
735 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
736 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
737 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
738 if originPreviousDepotPath == p4PreviousDepotPath:
739 originP4Change = int(originP4Change)
740 p4Change = int(p4Change)
741 if originP4Change > p4Change:
742 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
743 system("git update-ref refs/remotes/p4/master origin");
745 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
747 if len(self.branch) == 0:
748 self.branch = "refs/remotes/p4/master"
749 if gitBranchExists("refs/heads/p4"):
750 system("git update-ref %s refs/heads/p4" % self.branch)
751 system("git branch -D p4");
752 if not gitBranchExists("refs/remotes/p4/HEAD"):
753 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
756 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
757 ### needs to be ported to multi branch import
759 print "Creating %s branch in git repository based on origin" % self.branch
761 if not branch.startswith("refs"):
762 branch = "refs/heads/" + branch
763 system("git update-ref %s origin" % branch)
766 print "branches: %s" % self.p4BranchesInGit
769 for branch in self.p4BranchesInGit:
770 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
773 print "path %s change %s" % (depotPath, change)
775 if len(depotPath) > 0 and len(change) > 0:
776 change = int(change) + 1
777 p4Change = max(p4Change, change)
779 if len(self.previousDepotPath) == 0:
780 self.previousDepotPath = depotPath
783 l = min(len(self.previousDepotPath), len(depotPath))
784 while i < l and self.previousDepotPath[i] == depotPath[i]:
786 self.previousDepotPath = self.previousDepotPath[:i]
789 self.depotPath = self.previousDepotPath
790 self.changeRange = "@%s,#head" % p4Change
791 self.initialParent = parseRevision(self.branch)
793 print "Performing incremental import into %s git branch" % self.branch
795 if not self.branch.startswith("refs/"):
796 self.branch = "refs/heads/" + self.branch
798 if len(self.depotPath) != 0:
799 self.depotPath = self.depotPath[:-1]
801 if len(args) == 0 and len(self.depotPath) != 0:
803 print "Depot path: %s" % self.depotPath
807 if len(self.depotPath) != 0 and self.depotPath != args[0]:
808 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
810 self.depotPath = args[0]
815 if self.depotPath.find("@") != -1:
816 atIdx = self.depotPath.index("@")
817 self.changeRange = self.depotPath[atIdx:]
818 if self.changeRange == "@all":
819 self.changeRange = ""
820 elif self.changeRange.find(",") == -1:
821 self.revision = self.changeRange
822 self.changeRange = ""
823 self.depotPath = self.depotPath[0:atIdx]
824 elif self.depotPath.find("#") != -1:
825 hashIdx = self.depotPath.index("#")
826 self.revision = self.depotPath[hashIdx:]
827 self.depotPath = self.depotPath[0:hashIdx]
828 elif len(self.previousDepotPath) == 0:
829 self.revision = "#head"
831 if self.depotPath.endswith("..."):
832 self.depotPath = self.depotPath[:-3]
834 if not self.depotPath.endswith("/"):
835 self.depotPath += "/"
837 self.loadUserMapFromCache()
839 if self.detectLabels:
842 if self.detectBranches:
843 self.getBranchMapping();
845 print "p4-git branches: %s" % self.p4BranchesInGit
846 print "initial parents: %s" % self.initialParents
847 for b in self.p4BranchesInGit:
849 b = b[len(self.projectName):]
850 self.createdBranches.add(b)
852 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
854 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
855 self.gitOutput = importProcess.stdout
856 self.gitStream = importProcess.stdin
857 self.gitError = importProcess.stderr
859 if len(self.revision) > 0:
860 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
862 details = { "user" : "git perforce import user", "time" : int(time.time()) }
863 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
864 details["change"] = self.revision
868 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
869 change = int(info["change"])
870 if change > newestRevision:
871 newestRevision = change
873 if info["action"] == "delete":
874 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
875 #fileCnt = fileCnt + 1
878 for prop in [ "depotFile", "rev", "action", "type" ]:
879 details["%s%s" % (prop, fileCnt)] = info[prop]
881 fileCnt = fileCnt + 1
883 details["change"] = newestRevision
886 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
888 print "IO error with git fast-import. Is your git version recent enough?"
889 print self.gitError.read()
894 if len(self.changesFile) > 0:
895 output = open(self.changesFile).readlines()
898 changeSet.add(int(line))
900 for change in changeSet:
901 changes.append(change)
906 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
907 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
910 changeNum = line.split(" ")[1]
911 changes.append(changeNum)
915 if len(changes) == 0:
917 print "no changes to import!"
921 for change in changes:
922 description = p4Cmd("describe %s" % change)
925 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
930 if self.detectBranches:
931 branches = self.splitFilesIntoBranches(description)
932 for branch in branches.keys():
933 branchPrefix = self.depotPath + branch + "/"
937 filesForCommit = branches[branch]
940 print "branch is %s" % branch
942 if branch not in self.createdBranches:
943 self.createdBranches.add(branch)
944 parent = self.knownBranches[branch]
948 print "parent determined through known branches: %s" % parent
950 # main branch? use master
954 branch = self.projectName + branch
958 elif len(parent) > 0:
959 parent = self.projectName + parent
961 branch = "refs/remotes/p4/" + branch
963 parent = "refs/remotes/p4/" + parent
966 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
968 if len(parent) == 0 and branch in self.initialParents:
969 parent = self.initialParents[branch]
970 del self.initialParents[branch]
972 self.commit(description, filesForCommit, branch, branchPrefix, parent)
974 files = self.extractFilesFromCommit(description)
975 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
976 self.initialParent = ""
978 print self.gitError.read()
985 self.gitStream.close()
986 if importProcess.wait() != 0:
987 die("fast-import failed: %s" % self.gitError.read())
988 self.gitOutput.close()
989 self.gitError.close()
993 class P4Rebase(Command):
995 Command.__init__(self)
996 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
997 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
998 self.syncWithOrigin = False
1000 def run(self, args):
1002 sync.syncWithOrigin = self.syncWithOrigin
1004 print "Rebasing the current branch"
1005 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1006 system("git rebase p4")
1007 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1010 class P4Clone(P4Sync):
1012 P4Sync.__init__(self)
1013 self.description = "Creates a new git repository and imports from Perforce into it"
1014 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1015 self.needsGit = False
1017 def run(self, args):
1029 if not depotPath.startswith("//"):
1034 atPos = dir.rfind("@")
1037 hashPos = dir.rfind("#")
1039 dir = dir[0:hashPos]
1041 if dir.endswith("..."):
1044 if dir.endswith("/"):
1047 slashPos = dir.rfind("/")
1049 dir = dir[slashPos + 1:]
1051 print "Importing from %s into %s" % (depotPath, dir)
1055 gitdir = os.getcwd() + "/.git"
1056 if not P4Sync.run(self, [depotPath]):
1058 if self.branch != "master":
1059 if gitBranchExists("refs/remotes/p4/master"):
1060 system("git branch master refs/remotes/p4/master")
1061 system("git checkout -f")
1063 print "Could not detect main branch. No checkout/master branch created."
1066 class HelpFormatter(optparse.IndentedHelpFormatter):
1068 optparse.IndentedHelpFormatter.__init__(self)
1070 def format_description(self, description):
1072 return description + "\n"
1076 def printUsage(commands):
1077 print "usage: %s <command> [options]" % sys.argv[0]
1079 print "valid commands: %s" % ", ".join(commands)
1081 print "Try %s <command> --help for command specific help." % sys.argv[0]
1085 "debug" : P4Debug(),
1086 "submit" : P4Submit(),
1088 "rebase" : P4Rebase(),
1092 if len(sys.argv[1:]) == 0:
1093 printUsage(commands.keys())
1097 cmdName = sys.argv[1]
1099 cmd = commands[cmdName]
1101 print "unknown command %s" % cmdName
1103 printUsage(commands.keys())
1106 options = cmd.options
1111 if len(options) > 0:
1112 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1114 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1116 description = cmd.description,
1117 formatter = HelpFormatter())
1119 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1123 if len(gitdir) == 0:
1125 if not isValidGitDir(gitdir):
1126 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1127 if os.path.exists(gitdir):
1128 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1132 if not isValidGitDir(gitdir):
1133 if isValidGitDir(gitdir + "/.git"):
1136 die("fatal: cannot locate git repository at %s" % gitdir)
1138 os.environ["GIT_DIR"] = gitdir
1140 if not cmd.run(args):