Code

Make rollback work with locally imported branches
[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: * Consider making --with-origin the default, assuming that the git
11 #         protocol is always more efficient. (needs manual testing first :)
12 #
14 import optparse, sys, os, marshal, popen2, subprocess, shelve
15 import tempfile, getopt, sha, os.path, time, platform
16 from sets import Set;
18 gitdir = os.environ.get("GIT_DIR", "")
20 def mypopen(command):
21     return os.popen(command, "rb");
23 def p4CmdList(cmd):
24     cmd = "p4 -G %s" % cmd
25     pipe = os.popen(cmd, "rb")
27     result = []
28     try:
29         while True:
30             entry = marshal.load(pipe)
31             result.append(entry)
32     except EOFError:
33         pass
34     pipe.close()
36     return result
38 def p4Cmd(cmd):
39     list = p4CmdList(cmd)
40     result = {}
41     for entry in list:
42         result.update(entry)
43     return result;
45 def p4Where(depotPath):
46     if not depotPath.endswith("/"):
47         depotPath += "/"
48     output = p4Cmd("where %s..." % depotPath)
49     if output["code"] == "error":
50         return ""
51     clientPath = ""
52     if "path" in output:
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]
61     return clientPath
63 def die(msg):
64     sys.stderr.write(msg + "\n")
65     sys.exit(1)
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"):
72         return True;
73     return False
75 def parseRevision(ref):
76     return mypopen("git rev-parse %s" % ref).read()[:-1]
78 def system(cmd):
79     if os.system(cmd) != 0:
80         die("command failed: %s" % cmd)
82 def extractLogMessageFromGitCommit(commit):
83     logMessage = ""
84     foundTitle = False
85     for log in mypopen("git cat-file commit %s" % commit).readlines():
86        if not foundTitle:
87            if len(log) == 1:
88                foundTitle = True
89            continue
91        logMessage += log
92     return logMessage
94 def extractDepotPathAndChangeFromGitLog(log):
95     values = {}
96     for line in log.split("\n"):
97         line = line.strip()
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()
102                 value = ""
103                 equalPos = assignment.find("=")
104                 if equalPos != -1:
105                     variable = assignment[:equalPos].strip()
106                     value = assignment[equalPos + 1:].strip()
107                     if value.startswith("\"") and value.endswith("\""):
108                         value = value[1:-1]
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;
117 class Command:
118     def __init__(self):
119         self.usage = "usage: %prog [options]"
120         self.needsGit = True
122 class P4Debug(Command):
123     def __init__(self):
124         Command.__init__(self)
125         self.options = [
126         ]
127         self.description = "A tool to debug the output of p4 -G."
128         self.needsGit = False
130     def run(self, args):
131         for output in p4CmdList(" ".join(args)):
132             print output
133         return True
135 class P4RollBack(Command):
136     def __init__(self):
137         Command.__init__(self)
138         self.options = [
139             optparse.make_option("--verbose", dest="verbose", action="store_true"),
140             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
141         ]
142         self.description = "A tool to debug the multi-branch import. Don't use :)"
143         self.verbose = False
144         self.rollbackLocalBranches = False
146     def run(self, args):
147         if len(args) != 1:
148             return False
149         maxChange = int(args[0])
151         if self.rollbackLocalBranches:
152             refPrefix = "refs/heads/"
153             lines = mypopen("git rev-parse --symbolic --branches").readlines()
154         else:
155             refPrefix = "refs/remotes/"
156             lines = mypopen("git rev-parse --symbolic --remotes").readlines()
158         for line in lines:
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)
163                 changed = False
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))
168                     continue
170                 while len(change) > 0 and int(change) > maxChange:
171                     changed = True
172                     if self.verbose:
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)
178                 if changed:
179                     print "%s rewound to %s" % (ref, change)
181         return True
183 class P4Submit(Command):
184     def __init__(self):
185         Command.__init__(self)
186         self.options = [
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"),
194         ]
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
198         self.reset = False
199         self.interactive = True
200         self.dryRun = False
201         self.substFile = ""
202         self.firstTime = True
203         self.origin = ""
204         self.directSubmit = False
206         self.logSubstitutions = {}
207         self.logSubstitutions["<enter description here>"] = "%log%"
208         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
210     def check(self):
211         if len(p4CmdList("opened ...")) > 0:
212             die("You have files opened with perforce! Close them before starting the sync.")
214     def start(self):
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)
218         commits = []
219         if self.directSubmit:
220             commits.append("0")
221         else:
222             for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
223                 commits.append(line[:-1])
224             commits.reverse()
226         self.config["commits"] = commits
228     def prepareLogMessage(self, template, message):
229         result = ""
231         for line in template.split("\n"):
232             if line.startswith("#"):
233                 result += line + "\n"
234                 continue
236             substituted = False
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"
243                     substituted = True
244                     break
246             if not substituted:
247                 result += line + "\n"
249         return result
251     def apply(self, id):
252         if self.directSubmit:
253             print "Applying local change in working directory/index"
254             diff = self.diffStatus
255         else:
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()
258         filesToAdd = set()
259         filesToDelete = set()
260         editedFiles = set()
261         for line in diff:
262             modifier = line[0]
263             path = line[1:].strip()
264             if modifier == "M":
265                 system("p4 edit \"%s\"" % path)
266                 editedFiles.add(path)
267             elif modifier == "A":
268                 filesToAdd.add(path)
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)
275             else:
276                 die("unknown modifier %s for %s" % (modifier, path))
278         if self.directSubmit:
279             diffcmd = "cat \"%s\"" % self.diffFile
280         else:
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?"
289             response = "x"
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) ")
292             if response == "s":
293                 print "Skipping! Good luck with the next patches..."
294                 return
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)
311         for f in filesToAdd:
312             system("p4 add %s" % f)
313         for f in filesToDelete:
314             system("p4 revert %s" % f)
315             system("p4 delete %s" % f)
317         logMessage = ""
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()
325         if self.interactive:
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():
335                     diff += "+" + line
336                 f.close()
338             separatorLine = "######## everything below this line is just the diff #######"
339             if platform.system() == "Windows":
340                 separatorLine += "\r"
341             separatorLine += "\n"
343             response = "e"
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
349                 if response == "e":
350                     [handle, fileName] = tempfile.mkstemp()
351                     tmpFile = os.fdopen(handle, "w+")
352                     tmpFile.write(submitTemplate + separatorLine + diff)
353                     tmpFile.close()
354                     defaultEditor = "vi"
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()
361                     tmpFile.close()
362                     os.remove(fileName)
363                     submitTemplate = message[:message.index(separatorLine)]
365             if response == "y" or response == "yes":
366                if self.dryRun:
367                    print submitTemplate
368                    raw_input("Press return to continue...")
369                else:
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)
375                        pipe.close()
376                        os.chdir(self.clientPath)
378                    pipe = os.popen("p4 submit -i", "wb")
379                    pipe.write(submitTemplate)
380                    pipe.close()
381             elif response == "s":
382                 for f in editedFiles:
383                     system("p4 revert \"%s\"" % f);
384                 for f in filesToAdd:
385                     system("p4 revert \"%s\"" % f);
386                     system("rm %s" %f)
387                 for f in filesToDelete:
388                     system("p4 delete \"%s\"" % f);
389                 return
390             else:
391                 print "Not submitting!"
392                 self.interactive = False
393         else:
394             fileName = "submit.txt"
395             file = open(fileName, "w+")
396             file.write(self.prepareLogMessage(template, logMessage))
397             file.close()
398             print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
400     def run(self, args):
401         global gitdir
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
406         if len(args) == 0:
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!")
410         elif len(args) == 1:
411             self.master = args[0]
412         else:
413             return False
415         depotPath = ""
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"
423             sys.exit(128)
425         self.clientPath = p4Where(depotPath)
427         if len(self.clientPath) == 0:
428             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
429             sys.exit(128)
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."
438                 return True
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")
442             f.write(patch)
443             f.close();
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"):
452                 self.origin = "p4"
453             else:
454                 self.origin = "origin"
456         if self.reset:
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]
464         self.check()
465         self.configFile = gitdir + "/p4-git-sync.cfg"
466         self.config = shelve.open(self.configFile, writeback=True)
468         if self.firstTime:
469             self.start()
471         commits = self.config.get("commits", [])
473         while len(commits) > 0:
474             self.firstTime = False
475             commit = commits[0]
476             commits = commits[1:]
477             self.config["commits"] = commits
478             self.apply(commit)
479             if not self.interactive:
480                 break
482         self.config.close()
484         if self.directSubmit:
485             os.remove(self.diffFile)
487         if len(commits) == 0:
488             if self.firstTime:
489                 print "No changes found to apply between %s and current HEAD" % self.origin
490             else:
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":
495                     rebase = P4Rebase()
496                     rebase.run([])
497             os.remove(self.configFile)
499         return True
501 class P4Sync(Command):
502     def __init__(self):
503         Command.__init__(self)
504         self.options = [
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")
514         ]
515         self.description = """Imports from Perforce into a git repository.\n
516     example:
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]"
525         self.silent = False
526         self.createdBranches = Set()
527         self.committedChanges = Set()
528         self.branch = ""
529         self.detectBranches = False
530         self.detectLabels = False
531         self.changesFile = ""
532         self.syncWithOrigin = False
533         self.verbose = False
534         self.importIntoRemotes = True
535         self.maxChanges = ""
537     def p4File(self, depotPath):
538         return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
540     def extractFilesFromCommit(self, commit):
541         files = []
542         fnum = 0
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)
548                 fnum = fnum + 1
549                 continue
551             file = {}
552             file["path"] = path
553             file["rev"] = commit["rev%s" % fnum]
554             file["action"] = commit["action%s" % fnum]
555             file["type"] = commit["type%s" % fnum]
556             files.append(file)
557             fnum = fnum + 1
558         return files
560     def splitFilesIntoBranches(self, commit):
561         branches = {}
563         fnum = 0
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)
569                 fnum = fnum + 1
570                 continue
572             file = {}
573             file["path"] = path
574             file["rev"] = commit["rev%s" % fnum]
575             file["action"] = commit["action%s" % fnum]
576             file["type"] = commit["type%s" % fnum]
577             fnum = fnum + 1
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)
587         return branches
589     def commit(self, details, files, branch, branchPrefix, parent = ""):
590         epoch = details["time"]
591         author = details["user"]
593         if self.verbose:
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"]))
599         committer = ""
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)
604         else:
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")
614         if len(parent) > 0:
615             if self.verbose:
616                 print "parent %s" % parent
617             self.gitStream.write("from %s\n" % parent)
619         for file in files:
620             path = file["path"]
621             if not path.startswith(branchPrefix):
622     #            if not silent:
623     #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
624                 continue
625             rev = file["rev"]
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
632                 continue
634             if action == "delete":
635                 self.gitStream.write("D %s\n" % relPath)
636             else:
637                 mode = 644
638                 if file["type"].startswith("x"):
639                     mode = 755
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]
656             if self.verbose:
657                 print "Change %s is labelled %s" % (change, labelDetails)
659             files = p4CmdList("files %s...@%s" % (branchPrefix, change))
661             if len(files) == len(labelRevisions):
663                 cleanedFiles = {}
664                 for info in files:
665                     if info["action"] == "delete":
666                         continue
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"]
674                     tagger = ""
675                     if author in self.users:
676                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
677                     else:
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")
684                 else:
685                     if not self.silent:
686                         print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
688             else:
689                 if not self.silent:
690                     print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
692     def getUserMapFromPerforceServer(self):
693         self.users = {}
695         for output in p4CmdList("users"):
696             if not output.has_key("User"):
697                 continue
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]))
703         cache.close();
705     def loadUserMapFromCache(self):
706         self.users = {}
707         try:
708             cache = open(gitdir + "/p4-usercache.txt", "rb")
709             lines = cache.readlines()
710             cache.close()
711             for line in lines:
712                 entry = line[:-1].split("\t")
713                 self.users[entry[0]] = entry[1]
714         except IOError:
715             self.getUserMapFromPerforceServer()
717     def getLabels(self):
718         self.labels = {}
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
724         for output in l:
725             label = output["label"]
726             revisions = {}
727             newestChange = 0
728             if self.verbose:
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]
738         if self.verbose:
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"])
746             viewIdx = 0
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("/..."):
752                     continue
753                 source = paths[0]
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"
769         else:
770             cmdline += " --branches"
772         for line in mypopen(cmdline).readlines():
773             if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
774                 continue
775             if self.importIntoRemotes:
776                 # strip off p4
777                 branch = line[3:-1]
778             else:
779                 branch = line[:-1]
780             self.p4BranchesInGit.append(branch)
781             self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
783     def run(self, args):
784         self.depotPath = ""
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/"
794         else:
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");
813                 else:
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
831         if len(args) == 0:
832             if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
833                 ### needs to be ported to multi branch import
834                 if not self.silent:
835                     print "Creating %s branch in git repository based on origin" % self.branch
836                 branch = self.branch
837                 if not branch.startswith("refs"):
838                     branch = "refs/heads/" + branch
839                 system("git update-ref %s origin" % branch)
841             if self.verbose:
842                 print "branches: %s" % self.p4BranchesInGit
844             p4Change = 0
845             for branch in self.p4BranchesInGit:
846                 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.refPrefix + branch))
848                 if self.verbose:
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
857                     else:
858                         i = 0
859                         l = min(len(self.previousDepotPath), len(depotPath))
860                         while i < l and self.previousDepotPath[i] == depotPath[i]:
861                             i = i + 1
862                         self.previousDepotPath = self.previousDepotPath[:i]
864             if p4Change > 0:
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:
878             if not self.silent:
879                 print "Depot path: %s" % self.depotPath
880         elif len(args) != 1:
881             return False
882         else:
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])
885                 sys.exit(1)
886             self.depotPath = args[0]
888         self.revision = ""
889         self.users = {}
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()
914         self.labels = {}
915         if self.detectLabels:
916             self.getLabels();
918         if self.detectBranches:
919             self.getBranchMapping();
920             if self.verbose:
921                 print "p4-git branches: %s" % self.p4BranchesInGit
922                 print "initial parents: %s" % self.initialParents
923             for b in self.p4BranchesInGit:
924                 if b != "master":
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
941             newestRevision = 0
943             fileCnt = 0
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
952                     continue
954                 for prop in [ "depotFile", "rev", "action", "type" ]:
955                     details["%s%s" % (prop, fileCnt)] = info[prop]
957                 fileCnt = fileCnt + 1
959             details["change"] = newestRevision
961             try:
962                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
963             except IOError:
964                 print "IO error with git fast-import. Is your git version recent enough?"
965                 print self.gitError.read()
967         else:
968             changes = []
970             if len(self.changesFile) > 0:
971                 output = open(self.changesFile).readlines()
972                 changeSet = Set()
973                 for line in output:
974                     changeSet.add(int(line))
976                 for change in changeSet:
977                     changes.append(change)
979                 changes.sort()
980             else:
981                 if self.verbose:
982                     print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
983                 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
985                 for line in output:
986                     changeNum = line.split(" ")[1]
987                     changes.append(changeNum)
989                 changes.reverse()
991                 if len(self.maxChanges) > 0:
992                     changes = changes[0:min(int(self.maxChanges), len(changes))]
994             if len(changes) == 0:
995                 if not self.silent:
996                     print "No changes to import!"
997                 return True
999             self.updatedBranches = set()
1001             cnt = 1
1002             for change in changes:
1003                 description = p4Cmd("describe %s" % change)
1005                 if not self.silent:
1006                     sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1007                     sys.stdout.flush()
1008                 cnt = cnt + 1
1010                 try:
1011                     if self.detectBranches:
1012                         branches = self.splitFilesIntoBranches(description)
1013                         for branch in branches.keys():
1014                             branchPrefix = self.depotPath + branch + "/"
1016                             parent = ""
1018                             filesForCommit = branches[branch]
1020                             if self.verbose:
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:
1029                                     parent = ""
1030                                 elif self.verbose:
1031                                     print "parent determined through known branches: %s" % parent
1033                             # main branch? use master
1034                             if branch == "main":
1035                                 branch = "master"
1036                             else:
1037                                 branch = self.projectName + branch
1039                             if parent == "main":
1040                                 parent = "master"
1041                             elif len(parent) > 0:
1042                                 parent = self.projectName + parent
1044                             branch = self.refPrefix + branch
1045                             if len(parent) > 0:
1046                                 parent = self.refPrefix + parent
1048                             if self.verbose:
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)
1056                     else:
1057                         files = self.extractFilesFromCommit(description)
1058                         self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1059                         self.initialParent = ""
1060                 except IOError:
1061                     print self.gitError.read()
1062                     sys.exit(1)
1064             if not self.silent:
1065                 print ""
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()
1079         if createP4HeadRef:
1080             system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1082         return True
1084 class P4Rebase(Command):
1085     def __init__(self):
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):
1092         sync = P4Sync()
1093         sync.syncWithOrigin = self.syncWithOrigin
1094         sync.run([])
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)
1099         return True
1101 class P4Clone(P4Sync):
1102     def __init__(self):
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):
1109         global gitdir
1111         if len(args) < 1:
1112             return False
1113         depotPath = args[0]
1114         dir = ""
1115         if len(args) == 2:
1116             dir = args[1]
1117         elif len(args) > 2:
1118             return False
1120         if not depotPath.startswith("//"):
1121             return False
1123         if len(dir) == 0:
1124             dir = depotPath
1125             atPos = dir.rfind("@")
1126             if atPos != -1:
1127                 dir = dir[0:atPos]
1128             hashPos = dir.rfind("#")
1129             if hashPos != -1:
1130                 dir = dir[0:hashPos]
1132             if dir.endswith("..."):
1133                 dir = dir[:-3]
1135             if dir.endswith("/"):
1136                dir = dir[:-1]
1138             slashPos = dir.rfind("/")
1139             if slashPos != -1:
1140                 dir = dir[slashPos + 1:]
1142         print "Importing from %s into %s" % (depotPath, dir)
1143         os.makedirs(dir)
1144         os.chdir(dir)
1145         system("git init")
1146         gitdir = os.getcwd() + "/.git"
1147         if not P4Sync.run(self, [depotPath]):
1148             return False
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")
1153             else:
1154                 print "Could not detect main branch. No checkout/master branch created."
1155         return True
1157 class HelpFormatter(optparse.IndentedHelpFormatter):
1158     def __init__(self):
1159         optparse.IndentedHelpFormatter.__init__(self)
1161     def format_description(self, description):
1162         if description:
1163             return description + "\n"
1164         else:
1165             return ""
1167 def printUsage(commands):
1168     print "usage: %s <command> [options]" % sys.argv[0]
1169     print ""
1170     print "valid commands: %s" % ", ".join(commands)
1171     print ""
1172     print "Try %s <command> --help for command specific help." % sys.argv[0]
1173     print ""
1175 commands = {
1176     "debug" : P4Debug(),
1177     "submit" : P4Submit(),
1178     "sync" : P4Sync(),
1179     "rebase" : P4Rebase(),
1180     "clone" : P4Clone(),
1181     "rollback" : P4RollBack()
1184 if len(sys.argv[1:]) == 0:
1185     printUsage(commands.keys())
1186     sys.exit(2)
1188 cmd = ""
1189 cmdName = sys.argv[1]
1190 try:
1191     cmd = commands[cmdName]
1192 except KeyError:
1193     print "unknown command %s" % cmdName
1194     print ""
1195     printUsage(commands.keys())
1196     sys.exit(2)
1198 options = cmd.options
1199 cmd.gitdir = gitdir
1201 args = sys.argv[2:]
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),
1207                                    options,
1208                                    description = cmd.description,
1209                                    formatter = HelpFormatter())
1211     (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1213 if cmd.needsGit:
1214     gitdir = cmd.gitdir
1215     if len(gitdir) == 0:
1216         gitdir = ".git"
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];
1221                 if len(cdup) > 0:
1222                     os.chdir(cdup);
1224     if not isValidGitDir(gitdir):
1225         if isValidGitDir(gitdir + "/.git"):
1226             gitdir += "/.git"
1227         else:
1228             die("fatal: cannot locate git repository at %s" % gitdir)
1230     os.environ["GIT_DIR"] = gitdir
1232 if not cmd.run(args):
1233     parser.print_help()