Code

5055f3214039666f926cb2f3e3b9324f01fb8c2f
[git.git] / contrib / fast-import / git-p4
1 #!/usr/bin/env python
2 #
3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
4 #
5 # Author: Simon Hausmann <hausmann@kde.org>
6 # Copyright: 2007 Simon Hausmann <hausmann@kde.org>
7 #            2007 Trolltech ASA
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
9 #
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.
13 #       * for git-p4 submit --direct it would be nice to still create a
14 #         git commit without updating HEAD before submitting to perforce.
15 #         With the commit sha1 printed (or recoded in a .git/foo file?)
16 #         it's possible to recover if anything goes wrong instead of potentially
17 #         loosing a change entirely because it was never comitted to git and
18 #         the p4 submit failed (or resulted in lots of conflicts, etc.)
19 #
21 import optparse, sys, os, marshal, popen2, subprocess, shelve
22 import tempfile, getopt, sha, os.path, time, platform
23 from sets import Set;
25 gitdir = os.environ.get("GIT_DIR", "")
27 def mypopen(command):
28     return os.popen(command, "rb");
30 def p4CmdList(cmd):
31     cmd = "p4 -G %s" % cmd
32     pipe = os.popen(cmd, "rb")
34     result = []
35     try:
36         while True:
37             entry = marshal.load(pipe)
38             result.append(entry)
39     except EOFError:
40         pass
41     pipe.close()
43     return result
45 def p4Cmd(cmd):
46     list = p4CmdList(cmd)
47     result = {}
48     for entry in list:
49         result.update(entry)
50     return result;
52 def p4Where(depotPath):
53     if not depotPath.endswith("/"):
54         depotPath += "/"
55     output = p4Cmd("where %s..." % depotPath)
56     clientPath = ""
57     if "path" in output:
58         clientPath = output.get("path")
59     elif "data" in output:
60         data = output.get("data")
61         lastSpace = data.rfind(" ")
62         clientPath = data[lastSpace + 1:]
64     if clientPath.endswith("..."):
65         clientPath = clientPath[:-3]
66     return clientPath
68 def die(msg):
69     sys.stderr.write(msg + "\n")
70     sys.exit(1)
72 def currentGitBranch():
73     return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
75 def isValidGitDir(path):
76     if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
77         return True;
78     return False
80 def parseRevision(ref):
81     return mypopen("git rev-parse %s" % ref).read()[:-1]
83 def system(cmd):
84     if os.system(cmd) != 0:
85         die("command failed: %s" % cmd)
87 def extractLogMessageFromGitCommit(commit):
88     logMessage = ""
89     foundTitle = False
90     for log in mypopen("git cat-file commit %s" % commit).readlines():
91        if not foundTitle:
92            if len(log) == 1:
93                foundTitle = True
94            continue
96        logMessage += log
97     return logMessage
99 def extractDepotPathAndChangeFromGitLog(log):
100     values = {}
101     for line in log.split("\n"):
102         line = line.strip()
103         if line.startswith("[git-p4:") and line.endswith("]"):
104             line = line[8:-1].strip()
105             for assignment in line.split(":"):
106                 variable = assignment.strip()
107                 value = ""
108                 equalPos = assignment.find("=")
109                 if equalPos != -1:
110                     variable = assignment[:equalPos].strip()
111                     value = assignment[equalPos + 1:].strip()
112                     if value.startswith("\"") and value.endswith("\""):
113                         value = value[1:-1]
114                 values[variable] = value
116     return values.get("depot-path"), values.get("change")
118 def gitBranchExists(branch):
119     proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
120     return proc.wait() == 0;
122 class Command:
123     def __init__(self):
124         self.usage = "usage: %prog [options]"
125         self.needsGit = True
127 class P4Debug(Command):
128     def __init__(self):
129         Command.__init__(self)
130         self.options = [
131         ]
132         self.description = "A tool to debug the output of p4 -G."
133         self.needsGit = False
135     def run(self, args):
136         for output in p4CmdList(" ".join(args)):
137             print output
138         return True
140 class P4Submit(Command):
141     def __init__(self):
142         Command.__init__(self)
143         self.options = [
144                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
145                 optparse.make_option("--origin", dest="origin"),
146                 optparse.make_option("--reset", action="store_true", dest="reset"),
147                 optparse.make_option("--log-substitutions", dest="substFile"),
148                 optparse.make_option("--noninteractive", action="store_false"),
149                 optparse.make_option("--dry-run", action="store_true"),
150                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
151         ]
152         self.description = "Submit changes from git to the perforce depot."
153         self.usage += " [name of git branch to submit into perforce depot]"
154         self.firstTime = True
155         self.reset = False
156         self.interactive = True
157         self.dryRun = False
158         self.substFile = ""
159         self.firstTime = True
160         self.origin = ""
161         self.directSubmit = False
163         self.logSubstitutions = {}
164         self.logSubstitutions["<enter description here>"] = "%log%"
165         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
167     def check(self):
168         if len(p4CmdList("opened ...")) > 0:
169             die("You have files opened with perforce! Close them before starting the sync.")
171     def start(self):
172         if len(self.config) > 0 and not self.reset:
173             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)
175         commits = []
176         if self.directSubmit:
177             commits.append("0")
178         else:
179             for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
180                 commits.append(line[:-1])
181             commits.reverse()
183         self.config["commits"] = commits
185     def prepareLogMessage(self, template, message):
186         result = ""
188         for line in template.split("\n"):
189             if line.startswith("#"):
190                 result += line + "\n"
191                 continue
193             substituted = False
194             for key in self.logSubstitutions.keys():
195                 if line.find(key) != -1:
196                     value = self.logSubstitutions[key]
197                     value = value.replace("%log%", message)
198                     if value != "@remove@":
199                         result += line.replace(key, value) + "\n"
200                     substituted = True
201                     break
203             if not substituted:
204                 result += line + "\n"
206         return result
208     def apply(self, id):
209         if self.directSubmit:
210             print "Applying local change in working directory/index"
211             diff = self.diffStatus
212         else:
213             print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
214             diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
215         filesToAdd = set()
216         filesToDelete = set()
217         editedFiles = set()
218         for line in diff:
219             modifier = line[0]
220             path = line[1:].strip()
221             if modifier == "M":
222                 system("p4 edit \"%s\"" % path)
223                 editedFiles.add(path)
224             elif modifier == "A":
225                 filesToAdd.add(path)
226                 if path in filesToDelete:
227                     filesToDelete.remove(path)
228             elif modifier == "D":
229                 filesToDelete.add(path)
230                 if path in filesToAdd:
231                     filesToAdd.remove(path)
232             else:
233                 die("unknown modifier %s for %s" % (modifier, path))
235         if self.directSubmit:
236             diffcmd = "cat \"%s\"" % self.diffFile
237         else:
238             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
239         patchcmd = diffcmd + " | git apply "
240         tryPatchCmd = patchcmd + "--check -"
241         applyPatchCmd = patchcmd + "--check --apply -"
243         if os.system(tryPatchCmd) != 0:
244             print "Unfortunately applying the change failed!"
245             print "What do you want to do?"
246             response = "x"
247             while response != "s" and response != "a" and response != "w":
248                 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) ")
249             if response == "s":
250                 print "Skipping! Good luck with the next patches..."
251                 return
252             elif response == "a":
253                 os.system(applyPatchCmd)
254                 if len(filesToAdd) > 0:
255                     print "You may also want to call p4 add on the following files:"
256                     print " ".join(filesToAdd)
257                 if len(filesToDelete):
258                     print "The following files should be scheduled for deletion with p4 delete:"
259                     print " ".join(filesToDelete)
260                 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
261             elif response == "w":
262                 system(diffcmd + " > patch.txt")
263                 print "Patch saved to patch.txt in %s !" % self.clientPath
264                 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
266         system(applyPatchCmd)
268         for f in filesToAdd:
269             system("p4 add %s" % f)
270         for f in filesToDelete:
271             system("p4 revert %s" % f)
272             system("p4 delete %s" % f)
274         logMessage = ""
275         if not self.directSubmit:
276             logMessage = extractLogMessageFromGitCommit(id)
277             logMessage = logMessage.replace("\n", "\n\t")
278             logMessage = logMessage[:-1]
280         template = mypopen("p4 change -o").read()
282         if self.interactive:
283             submitTemplate = self.prepareLogMessage(template, logMessage)
284             diff = mypopen("p4 diff -du ...").read()
286             for newFile in filesToAdd:
287                 diff += "==== new file ====\n"
288                 diff += "--- /dev/null\n"
289                 diff += "+++ %s\n" % newFile
290                 f = open(newFile, "r")
291                 for line in f.readlines():
292                     diff += "+" + line
293                 f.close()
295             separatorLine = "######## everything below this line is just the diff #######"
296             if platform.system() == "Windows":
297                 separatorLine += "\r"
298             separatorLine += "\n"
300             response = "e"
301             firstIteration = True
302             while response == "e":
303                 if not firstIteration:
304                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
305                 firstIteration = False
306                 if response == "e":
307                     [handle, fileName] = tempfile.mkstemp()
308                     tmpFile = os.fdopen(handle, "w+")
309                     tmpFile.write(submitTemplate + separatorLine + diff)
310                     tmpFile.close()
311                     defaultEditor = "vi"
312                     if platform.system() == "Windows":
313                         defaultEditor = "notepad"
314                     editor = os.environ.get("EDITOR", defaultEditor);
315                     system(editor + " " + fileName)
316                     tmpFile = open(fileName, "rb")
317                     message = tmpFile.read()
318                     tmpFile.close()
319                     os.remove(fileName)
320                     submitTemplate = message[:message.index(separatorLine)]
322             if response == "y" or response == "yes":
323                if self.dryRun:
324                    print submitTemplate
325                    raw_input("Press return to continue...")
326                else:
327                     pipe = os.popen("p4 submit -i", "wb")
328                     pipe.write(submitTemplate)
329                     pipe.close()
330             elif response == "s":
331                 for f in editedFiles:
332                     system("p4 revert \"%s\"" % f);
333                 for f in filesToAdd:
334                     system("p4 revert \"%s\"" % f);
335                     system("rm %s" %f)
336                 for f in filesToDelete:
337                     system("p4 delete \"%s\"" % f);
338                 return
339             else:
340                 print "Not submitting!"
341                 self.interactive = False
342         else:
343             fileName = "submit.txt"
344             file = open(fileName, "w+")
345             file.write(self.prepareLogMessage(template, logMessage))
346             file.close()
347             print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
349     def run(self, args):
350         global gitdir
351         # make gitdir absolute so we can cd out into the perforce checkout
352         gitdir = os.path.abspath(gitdir)
353         os.environ["GIT_DIR"] = gitdir
355         if len(args) == 0:
356             self.master = currentGitBranch()
357             if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
358                 die("Detecting current git branch failed!")
359         elif len(args) == 1:
360             self.master = args[0]
361         else:
362             return False
364         depotPath = ""
365         if gitBranchExists("p4"):
366             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
367         if len(depotPath) == 0 and gitBranchExists("origin"):
368             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
370         if len(depotPath) == 0:
371             print "Internal error: cannot locate perforce depot path from existing branches"
372             sys.exit(128)
374         self.clientPath = p4Where(depotPath)
376         if len(self.clientPath) == 0:
377             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
378             sys.exit(128)
380         print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
381         oldWorkingDirectory = os.getcwd()
383         if self.directSubmit:
384             self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
385             patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
386             self.diffFile = gitdir + "/p4-git-diff"
387             f = open(self.diffFile, "wb")
388             f.write(patch)
389             f.close();
391         os.chdir(self.clientPath)
392         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
393         if response == "y" or response == "yes":
394             system("p4 sync ...")
396         if len(self.origin) == 0:
397             if gitBranchExists("p4"):
398                 self.origin = "p4"
399             else:
400                 self.origin = "origin"
402         if self.reset:
403             self.firstTime = True
405         if len(self.substFile) > 0:
406             for line in open(self.substFile, "r").readlines():
407                 tokens = line[:-1].split("=")
408                 self.logSubstitutions[tokens[0]] = tokens[1]
410         self.check()
411         self.configFile = gitdir + "/p4-git-sync.cfg"
412         self.config = shelve.open(self.configFile, writeback=True)
414         if self.firstTime:
415             self.start()
417         commits = self.config.get("commits", [])
419         while len(commits) > 0:
420             self.firstTime = False
421             commit = commits[0]
422             commits = commits[1:]
423             self.config["commits"] = commits
424             self.apply(commit)
425             if not self.interactive:
426                 break
428         self.config.close()
430         if self.directSubmit:
431             os.remove(self.diffFile)
433         if len(commits) == 0:
434             if self.firstTime:
435                 print "No changes found to apply between %s and current HEAD" % self.origin
436             else:
437                 print "All changes applied!"
438                 response = ""
439                 os.chdir(oldWorkingDirectory)
441                 if self.directSubmit:
442                     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 ")
443                     if response == "y" or response == "yes":
444                         system("git reset --hard")
446                 if len(response) == 0:
447                     response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
448                 if response == "y" or response == "yes":
449                     rebase = P4Rebase()
450                     rebase.run([])
451             os.remove(self.configFile)
453         return True
455 class P4Sync(Command):
456     def __init__(self):
457         Command.__init__(self)
458         self.options = [
459                 optparse.make_option("--branch", dest="branch"),
460                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
461                 optparse.make_option("--changesfile", dest="changesFile"),
462                 optparse.make_option("--silent", dest="silent", action="store_true"),
463                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
464                 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
465                 optparse.make_option("--verbose", dest="verbose", action="store_true")
466         ]
467         self.description = """Imports from Perforce into a git repository.\n
468     example:
469     //depot/my/project/ -- to import the current head
470     //depot/my/project/@all -- to import everything
471     //depot/my/project/@1,6 -- to import only from revision 1 to 6
473     (a ... is not needed in the path p4 specification, it's added implicitly)"""
475         self.usage += " //depot/path[@revRange]"
477         self.silent = False
478         self.createdBranches = Set()
479         self.committedChanges = Set()
480         self.branch = ""
481         self.detectBranches = False
482         self.detectLabels = False
483         self.changesFile = ""
484         self.syncWithOrigin = False
485         self.verbose = False
487     def p4File(self, depotPath):
488         return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
490     def extractFilesFromCommit(self, commit):
491         files = []
492         fnum = 0
493         while commit.has_key("depotFile%s" % fnum):
494             path =  commit["depotFile%s" % fnum]
495             if not path.startswith(self.depotPath):
496     #            if not self.silent:
497     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
498                 fnum = fnum + 1
499                 continue
501             file = {}
502             file["path"] = path
503             file["rev"] = commit["rev%s" % fnum]
504             file["action"] = commit["action%s" % fnum]
505             file["type"] = commit["type%s" % fnum]
506             files.append(file)
507             fnum = fnum + 1
508         return files
510     def splitFilesIntoBranches(self, commit):
511         branches = {}
513         fnum = 0
514         while commit.has_key("depotFile%s" % fnum):
515             path =  commit["depotFile%s" % fnum]
516             if not path.startswith(self.depotPath):
517     #            if not self.silent:
518     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
519                 fnum = fnum + 1
520                 continue
522             file = {}
523             file["path"] = path
524             file["rev"] = commit["rev%s" % fnum]
525             file["action"] = commit["action%s" % fnum]
526             file["type"] = commit["type%s" % fnum]
527             fnum = fnum + 1
529             relPath = path[len(self.depotPath):]
531             for branch in self.knownBranches.keys():
532                 if relPath.startswith(branch):
533                     if branch not in branches:
534                         branches[branch] = []
535                     branches[branch].append(file)
537         return branches
539     def commit(self, details, files, branch, branchPrefix, parent = ""):
540         epoch = details["time"]
541         author = details["user"]
543         if self.verbose:
544             print "commit into %s" % branch
546         self.gitStream.write("commit %s\n" % branch)
547     #    gitStream.write("mark :%s\n" % details["change"])
548         self.committedChanges.add(int(details["change"]))
549         committer = ""
550         if author not in self.users:
551             self.getUserMapFromPerforceServer()
552         if author in self.users:
553             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
554         else:
555             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
557         self.gitStream.write("committer %s\n" % committer)
559         self.gitStream.write("data <<EOT\n")
560         self.gitStream.write(details["desc"])
561         self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
562         self.gitStream.write("EOT\n\n")
564         if len(parent) > 0:
565             if self.verbose:
566                 print "parent %s" % parent
567             self.gitStream.write("from %s\n" % parent)
569         for file in files:
570             path = file["path"]
571             if not path.startswith(branchPrefix):
572     #            if not silent:
573     #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
574                 continue
575             rev = file["rev"]
576             depotPath = path + "#" + rev
577             relPath = path[len(branchPrefix):]
578             action = file["action"]
580             if file["type"] == "apple":
581                 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
582                 continue
584             if action == "delete":
585                 self.gitStream.write("D %s\n" % relPath)
586             else:
587                 mode = 644
588                 if file["type"].startswith("x"):
589                     mode = 755
591                 data = self.p4File(depotPath)
593                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
594                 self.gitStream.write("data %s\n" % len(data))
595                 self.gitStream.write(data)
596                 self.gitStream.write("\n")
598         self.gitStream.write("\n")
600         change = int(details["change"])
602         if self.labels.has_key(change):
603             label = self.labels[change]
604             labelDetails = label[0]
605             labelRevisions = label[1]
606             if self.verbose:
607                 print "Change %s is labelled %s" % (change, labelDetails)
609             files = p4CmdList("files %s...@%s" % (branchPrefix, change))
611             if len(files) == len(labelRevisions):
613                 cleanedFiles = {}
614                 for info in files:
615                     if info["action"] == "delete":
616                         continue
617                     cleanedFiles[info["depotFile"]] = info["rev"]
619                 if cleanedFiles == labelRevisions:
620                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
621                     self.gitStream.write("from %s\n" % branch)
623                     owner = labelDetails["Owner"]
624                     tagger = ""
625                     if author in self.users:
626                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
627                     else:
628                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
629                     self.gitStream.write("tagger %s\n" % tagger)
630                     self.gitStream.write("data <<EOT\n")
631                     self.gitStream.write(labelDetails["Description"])
632                     self.gitStream.write("EOT\n\n")
634                 else:
635                     if not self.silent:
636                         print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
638             else:
639                 if not self.silent:
640                     print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
642     def getUserMapFromPerforceServer(self):
643         self.users = {}
645         for output in p4CmdList("users"):
646             if not output.has_key("User"):
647                 continue
648             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
650         cache = open(gitdir + "/p4-usercache.txt", "wb")
651         for user in self.users.keys():
652             cache.write("%s\t%s\n" % (user, self.users[user]))
653         cache.close();
655     def loadUserMapFromCache(self):
656         self.users = {}
657         try:
658             cache = open(gitdir + "/p4-usercache.txt", "rb")
659             lines = cache.readlines()
660             cache.close()
661             for line in lines:
662                 entry = line[:-1].split("\t")
663                 self.users[entry[0]] = entry[1]
664         except IOError:
665             self.getUserMapFromPerforceServer()
667     def getLabels(self):
668         self.labels = {}
670         l = p4CmdList("labels %s..." % self.depotPath)
671         if len(l) > 0 and not self.silent:
672             print "Finding files belonging to labels in %s" % self.depotPath
674         for output in l:
675             label = output["label"]
676             revisions = {}
677             newestChange = 0
678             if self.verbose:
679                 print "Querying files for label %s" % label
680             for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
681                 revisions[file["depotFile"]] = file["rev"]
682                 change = int(file["change"])
683                 if change > newestChange:
684                     newestChange = change
686             self.labels[newestChange] = [output, revisions]
688         if self.verbose:
689             print "Label changes: %s" % self.labels.keys()
691     def getBranchMapping(self):
692         self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
694         for info in p4CmdList("branches"):
695             details = p4Cmd("branch -o %s" % info["branch"])
696             viewIdx = 0
697             while details.has_key("View%s" % viewIdx):
698                 paths = details["View%s" % viewIdx].split(" ")
699                 viewIdx = viewIdx + 1
700                 # require standard //depot/foo/... //depot/bar/... mapping
701                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
702                     continue
703                 source = paths[0]
704                 destination = paths[1]
705                 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
706                     source = source[len(self.depotPath):-4]
707                     destination = destination[len(self.depotPath):-4]
708                     if destination not in self.knownBranches:
709                         self.knownBranches[destination] = source
710                     if source not in self.knownBranches:
711                         self.knownBranches[source] = source
713     def listExistingP4GitBranches(self):
714         self.p4BranchesInGit = []
716         for line in mypopen("git rev-parse --symbolic --remotes").readlines():
717             if line.startswith("p4/") and line != "p4/HEAD\n":
718                 branch = line[3:-1]
719                 self.p4BranchesInGit.append(branch)
720                 self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1])
722     def run(self, args):
723         self.depotPath = ""
724         self.changeRange = ""
725         self.initialParent = ""
726         self.previousDepotPath = ""
727         # map from branch depot path to parent branch
728         self.knownBranches = {}
729         self.initialParents = {}
731         self.listExistingP4GitBranches()
732         if len(self.p4BranchesInGit) > 1:
733             print "Importing from/into multiple branches"
734             self.detectBranches = True
736         if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
737             ### needs to be ported to multi branch import
739             print "Syncing with origin first as requested by calling git fetch origin"
740             system("git fetch origin")
741             [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
742             [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
743             if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
744                 if originPreviousDepotPath == p4PreviousDepotPath:
745                     originP4Change = int(originP4Change)
746                     p4Change = int(p4Change)
747                     if originP4Change > p4Change:
748                         print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
749                         system("git update-ref refs/remotes/p4/master origin");
750                 else:
751                     print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
753         if len(self.branch) == 0:
754             self.branch = "refs/remotes/p4/master"
755             if gitBranchExists("refs/heads/p4"):
756                 system("git update-ref %s refs/heads/p4" % self.branch)
757                 system("git branch -D p4");
758             if not gitBranchExists("refs/remotes/p4/HEAD"):
759                 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
761         if len(args) == 0:
762             if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
763                 ### needs to be ported to multi branch import
764                 if not self.silent:
765                     print "Creating %s branch in git repository based on origin" % self.branch
766                 branch = self.branch
767                 if not branch.startswith("refs"):
768                     branch = "refs/heads/" + branch
769                 system("git update-ref %s origin" % branch)
771             if self.verbose:
772                 print "branches: %s" % self.p4BranchesInGit
774             p4Change = 0
775             for branch in self.p4BranchesInGit:
776                 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
778                 if self.verbose:
779                     print "path %s change %s" % (depotPath, change)
781                 if len(depotPath) > 0 and len(change) > 0:
782                     change = int(change) + 1
783                     p4Change = max(p4Change, change)
785                     if len(self.previousDepotPath) == 0:
786                         self.previousDepotPath = depotPath
787                     else:
788                         i = 0
789                         l = min(len(self.previousDepotPath), len(depotPath))
790                         while i < l and self.previousDepotPath[i] == depotPath[i]:
791                             i = i + 1
792                         self.previousDepotPath = self.previousDepotPath[:i]
794             if p4Change > 0:
795                 self.depotPath = self.previousDepotPath
796                 self.changeRange = "@%s,#head" % p4Change
797                 self.initialParent = parseRevision(self.branch)
798                 if not self.silent:
799                     print "Performing incremental import into %s git branch" % self.branch
801         if not self.branch.startswith("refs/"):
802             self.branch = "refs/heads/" + self.branch
804         if len(self.depotPath) != 0:
805             self.depotPath = self.depotPath[:-1]
807         if len(args) == 0 and len(self.depotPath) != 0:
808             if not self.silent:
809                 print "Depot path: %s" % self.depotPath
810         elif len(args) != 1:
811             return False
812         else:
813             if len(self.depotPath) != 0 and self.depotPath != args[0]:
814                 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
815                 sys.exit(1)
816             self.depotPath = args[0]
818         self.revision = ""
819         self.users = {}
821         if self.depotPath.find("@") != -1:
822             atIdx = self.depotPath.index("@")
823             self.changeRange = self.depotPath[atIdx:]
824             if self.changeRange == "@all":
825                 self.changeRange = ""
826             elif self.changeRange.find(",") == -1:
827                 self.revision = self.changeRange
828                 self.changeRange = ""
829             self.depotPath = self.depotPath[0:atIdx]
830         elif self.depotPath.find("#") != -1:
831             hashIdx = self.depotPath.index("#")
832             self.revision = self.depotPath[hashIdx:]
833             self.depotPath = self.depotPath[0:hashIdx]
834         elif len(self.previousDepotPath) == 0:
835             self.revision = "#head"
837         if self.depotPath.endswith("..."):
838             self.depotPath = self.depotPath[:-3]
840         if not self.depotPath.endswith("/"):
841             self.depotPath += "/"
843         self.loadUserMapFromCache()
844         self.labels = {}
845         if self.detectLabels:
846             self.getLabels();
848         if self.detectBranches:
849             self.getBranchMapping();
850             if self.verbose:
851                 print "p4-git branches: %s" % self.p4BranchesInGit
852                 print "initial parents: %s" % self.initialParents
853             for b in self.p4BranchesInGit:
854                 if b != "master":
855                     b = b[len(self.projectName):]
856                 self.createdBranches.add(b)
858         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
860         importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
861         self.gitOutput = importProcess.stdout
862         self.gitStream = importProcess.stdin
863         self.gitError = importProcess.stderr
865         if len(self.revision) > 0:
866             print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
868             details = { "user" : "git perforce import user", "time" : int(time.time()) }
869             details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
870             details["change"] = self.revision
871             newestRevision = 0
873             fileCnt = 0
874             for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
875                 change = int(info["change"])
876                 if change > newestRevision:
877                     newestRevision = change
879                 if info["action"] == "delete":
880                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
881                     #fileCnt = fileCnt + 1
882                     continue
884                 for prop in [ "depotFile", "rev", "action", "type" ]:
885                     details["%s%s" % (prop, fileCnt)] = info[prop]
887                 fileCnt = fileCnt + 1
889             details["change"] = newestRevision
891             try:
892                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
893             except IOError:
894                 print "IO error with git fast-import. Is your git version recent enough?"
895                 print self.gitError.read()
897         else:
898             changes = []
900             if len(self.changesFile) > 0:
901                 output = open(self.changesFile).readlines()
902                 changeSet = Set()
903                 for line in output:
904                     changeSet.add(int(line))
906                 for change in changeSet:
907                     changes.append(change)
909                 changes.sort()
910             else:
911                 if self.verbose:
912                     print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
913                 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
915                 for line in output:
916                     changeNum = line.split(" ")[1]
917                     changes.append(changeNum)
919                 changes.reverse()
921             if len(changes) == 0:
922                 if not self.silent:
923                     print "no changes to import!"
924                 return True
926             cnt = 1
927             for change in changes:
928                 description = p4Cmd("describe %s" % change)
930                 if not self.silent:
931                     sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
932                     sys.stdout.flush()
933                 cnt = cnt + 1
935                 try:
936                     if self.detectBranches:
937                         branches = self.splitFilesIntoBranches(description)
938                         for branch in branches.keys():
939                             branchPrefix = self.depotPath + branch + "/"
941                             parent = ""
943                             filesForCommit = branches[branch]
945                             if self.verbose:
946                                 print "branch is %s" % branch
948                             if branch not in self.createdBranches:
949                                 self.createdBranches.add(branch)
950                                 parent = self.knownBranches[branch]
951                                 if parent == branch:
952                                     parent = ""
953                                 elif self.verbose:
954                                     print "parent determined through known branches: %s" % parent
956                             # main branch? use master
957                             if branch == "main":
958                                 branch = "master"
959                             else:
960                                 branch = self.projectName + branch
962                             if parent == "main":
963                                 parent = "master"
964                             elif len(parent) > 0:
965                                 parent = self.projectName + parent
967                             branch = "refs/remotes/p4/" + branch
968                             if len(parent) > 0:
969                                 parent = "refs/remotes/p4/" + parent
971                             if self.verbose:
972                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
974                             if len(parent) == 0 and branch in self.initialParents:
975                                 parent = self.initialParents[branch]
976                                 del self.initialParents[branch]
978                             self.commit(description, filesForCommit, branch, branchPrefix, parent)
979                     else:
980                         files = self.extractFilesFromCommit(description)
981                         self.commit(description, files, self.branch, self.depotPath, self.initialParent)
982                         self.initialParent = ""
983                 except IOError:
984                     print self.gitError.read()
985                     sys.exit(1)
987         if not self.silent:
988             print ""
991         self.gitStream.close()
992         if importProcess.wait() != 0:
993             die("fast-import failed: %s" % self.gitError.read())
994         self.gitOutput.close()
995         self.gitError.close()
997         return True
999 class P4Rebase(Command):
1000     def __init__(self):
1001         Command.__init__(self)
1002         self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
1003         self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1004         self.syncWithOrigin = False
1006     def run(self, args):
1007         sync = P4Sync()
1008         sync.syncWithOrigin = self.syncWithOrigin
1009         sync.run([])
1010         print "Rebasing the current branch"
1011         oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1012         system("git rebase p4")
1013         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1014         return True
1016 class P4Clone(P4Sync):
1017     def __init__(self):
1018         P4Sync.__init__(self)
1019         self.description = "Creates a new git repository and imports from Perforce into it"
1020         self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1021         self.needsGit = False
1023     def run(self, args):
1024         global gitdir
1026         if len(args) < 1:
1027             return False
1028         depotPath = args[0]
1029         dir = ""
1030         if len(args) == 2:
1031             dir = args[1]
1032         elif len(args) > 2:
1033             return False
1035         if not depotPath.startswith("//"):
1036             return False
1038         if len(dir) == 0:
1039             dir = depotPath
1040             atPos = dir.rfind("@")
1041             if atPos != -1:
1042                 dir = dir[0:atPos]
1043             hashPos = dir.rfind("#")
1044             if hashPos != -1:
1045                 dir = dir[0:hashPos]
1047             if dir.endswith("..."):
1048                 dir = dir[:-3]
1050             if dir.endswith("/"):
1051                dir = dir[:-1]
1053             slashPos = dir.rfind("/")
1054             if slashPos != -1:
1055                 dir = dir[slashPos + 1:]
1057         print "Importing from %s into %s" % (depotPath, dir)
1058         os.makedirs(dir)
1059         os.chdir(dir)
1060         system("git init")
1061         gitdir = os.getcwd() + "/.git"
1062         if not P4Sync.run(self, [depotPath]):
1063             return False
1064         if self.branch != "master":
1065             if gitBranchExists("refs/remotes/p4/master"):
1066                 system("git branch master refs/remotes/p4/master")
1067                 system("git checkout -f")
1068             else:
1069                 print "Could not detect main branch. No checkout/master branch created."
1070         return True
1072 class HelpFormatter(optparse.IndentedHelpFormatter):
1073     def __init__(self):
1074         optparse.IndentedHelpFormatter.__init__(self)
1076     def format_description(self, description):
1077         if description:
1078             return description + "\n"
1079         else:
1080             return ""
1082 def printUsage(commands):
1083     print "usage: %s <command> [options]" % sys.argv[0]
1084     print ""
1085     print "valid commands: %s" % ", ".join(commands)
1086     print ""
1087     print "Try %s <command> --help for command specific help." % sys.argv[0]
1088     print ""
1090 commands = {
1091     "debug" : P4Debug(),
1092     "submit" : P4Submit(),
1093     "sync" : P4Sync(),
1094     "rebase" : P4Rebase(),
1095     "clone" : P4Clone()
1098 if len(sys.argv[1:]) == 0:
1099     printUsage(commands.keys())
1100     sys.exit(2)
1102 cmd = ""
1103 cmdName = sys.argv[1]
1104 try:
1105     cmd = commands[cmdName]
1106 except KeyError:
1107     print "unknown command %s" % cmdName
1108     print ""
1109     printUsage(commands.keys())
1110     sys.exit(2)
1112 options = cmd.options
1113 cmd.gitdir = gitdir
1115 args = sys.argv[2:]
1117 if len(options) > 0:
1118     options.append(optparse.make_option("--git-dir", dest="gitdir"))
1120     parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1121                                    options,
1122                                    description = cmd.description,
1123                                    formatter = HelpFormatter())
1125     (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1127 if cmd.needsGit:
1128     gitdir = cmd.gitdir
1129     if len(gitdir) == 0:
1130         gitdir = ".git"
1131         if not isValidGitDir(gitdir):
1132             gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1133             if os.path.exists(gitdir):
1134                 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1135                 if len(cdup) > 0:
1136                     os.chdir(cdup);
1138     if not isValidGitDir(gitdir):
1139         if isValidGitDir(gitdir + "/.git"):
1140             gitdir += "/.git"
1141         else:
1142             die("fatal: cannot locate git repository at %s" % gitdir)
1144     os.environ["GIT_DIR"] = gitdir
1146 if not cmd.run(args):
1147     parser.print_help()