Code

minor cleanups
[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 <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
7 #            2007 Trolltech ASA
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
9 #
11 import optparse, sys, os, marshal, popen2, subprocess, shelve
12 import tempfile, getopt, sha, os.path, time, platform
13 import re
14 from sets import Set;
16 gitdir = os.environ.get("GIT_DIR", "")
17 silent = False
19 def write_pipe(c, str):
20     if not silent:
21         sys.stderr.write('writing pipe: %s\n' % c)
23     ## todo: check return status
24     pipe = os.popen(c, 'w')
25     val = pipe.write(str)
26     if pipe.close():
27         sys.stderr.write('Command failed')
28         sys.exit(1)
30     return val
32 def read_pipe(c):
33     if not silent:
34         sys.stderr.write('reading pipe: %s\n' % c)
35     ## todo: check return status
36     pipe = os.popen(c, 'rb')
37     val = pipe.read()
38     if pipe.close():
39         sys.stderr.write('Command failed')
40         sys.exit(1)
42     return val
45 def read_pipe_lines(c):
46     if not silent:
47         sys.stderr.write('reading pipe: %s\n' % c)
48     ## todo: check return status
49     pipe = os.popen(c, 'rb')
50     val = pipe.readlines()
51     if pipe.close():
52         sys.stderr.write('Command failed')
53         sys.exit(1)
55     return val
57 def system(cmd):
58     if not silent:
59         sys.stderr.write("executing %s" % cmd)
60     if os.system(cmd) != 0:
61         die("command failed: %s" % cmd)
65 def p4CmdList(cmd):
66     cmd = "p4 -G %s" % cmd
67     pipe = os.popen(cmd, "rb")
69     result = []
70     try:
71         while True:
72             entry = marshal.load(pipe)
73             result.append(entry)
74     except EOFError:
75         pass
76     exitCode = pipe.close()
77     if exitCode != None:
78         entry = {}
79         entry["p4ExitCode"] = exitCode
80         result.append(entry)
82     return result
84 def p4Cmd(cmd):
85     list = p4CmdList(cmd)
86     result = {}
87     for entry in list:
88         result.update(entry)
89     return result;
91 def p4Where(depotPath):
92     if not depotPath.endswith("/"):
93         depotPath += "/"
94     output = p4Cmd("where %s..." % depotPath)
95     if output["code"] == "error":
96         return ""
97     clientPath = ""
98     if "path" in output:
99         clientPath = output.get("path")
100     elif "data" in output:
101         data = output.get("data")
102         lastSpace = data.rfind(" ")
103         clientPath = data[lastSpace + 1:]
105     if clientPath.endswith("..."):
106         clientPath = clientPath[:-3]
107     return clientPath
109 def die(msg):
110     sys.stderr.write(msg + "\n")
111     sys.exit(1)
113 def currentGitBranch():
114     return read_pipe("git name-rev HEAD").split(" ")[1][:-1]
116 def isValidGitDir(path):
117     if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
118         return True;
119     return False
121 def parseRevision(ref):
122     return read_pipe("git rev-parse %s" % ref)[:-1]
124 def extractLogMessageFromGitCommit(commit):
125     logMessage = ""
127     ## fixme: title is first line of commit, not 1st paragraph.
128     foundTitle = False
129     for log in read_pipe_lines("git cat-file commit %s" % commit):
130        if not foundTitle:
131            if len(log) == 1:
132                foundTitle = True
133            continue
135        logMessage += log
136     return logMessage
138 def extractDepotPathAndChangeFromGitLog(log):
139     values = {}
140     for line in log.split("\n"):
141         line = line.strip()
142         if line.startswith("[git-p4:") and line.endswith("]"):
143             line = line[8:-1].strip()
144             for assignment in line.split(":"):
145                 variable = assignment.strip()
146                 value = ""
147                 equalPos = assignment.find("=")
148                 if equalPos != -1:
149                     variable = assignment[:equalPos].strip()
150                     value = assignment[equalPos + 1:].strip()
151                     if value.startswith("\"") and value.endswith("\""):
152                         value = value[1:-1]
153                 values[variable] = value
155     return values.get("depot-path"), values.get("change")
157 def gitBranchExists(branch):
158     proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
159     return proc.wait() == 0;
161 def gitConfig(key):
162     return mypopen("git config %s" % key).read()[:-1]
164 class Command:
165     def __init__(self):
166         self.usage = "usage: %prog [options]"
167         self.needsGit = True
169 class P4Debug(Command):
170     def __init__(self):
171         Command.__init__(self)
172         self.options = [
173         ]
174         self.description = "A tool to debug the output of p4 -G."
175         self.needsGit = False
177     def run(self, args):
178         for output in p4CmdList(" ".join(args)):
179             print output
180         return True
182 class P4RollBack(Command):
183     def __init__(self):
184         Command.__init__(self)
185         self.options = [
186             optparse.make_option("--verbose", dest="verbose", action="store_true"),
187             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
188         ]
189         self.description = "A tool to debug the multi-branch import. Don't use :)"
190         self.verbose = False
191         self.rollbackLocalBranches = False
193     def run(self, args):
194         if len(args) != 1:
195             return False
196         maxChange = int(args[0])
198         if "p4ExitCode" in p4Cmd("changes -m 1"):
199             die("Problems executing p4");
201         if self.rollbackLocalBranches:
202             refPrefix = "refs/heads/"
203             lines = read_pipe_lines("git rev-parse --symbolic --branches")
204         else:
205             refPrefix = "refs/remotes/"
206             lines = read_pipe_lines("git rev-parse --symbolic --remotes")
208         for line in lines:
209             if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
210                 ref = refPrefix + line[:-1]
211                 log = extractLogMessageFromGitCommit(ref)
212                 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
213                 changed = False
215                 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
216                     print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
217                     system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
218                     continue
220                 while len(change) > 0 and int(change) > maxChange:
221                     changed = True
222                     if self.verbose:
223                         print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
224                     system("git update-ref %s \"%s^\"" % (ref, ref))
225                     log = extractLogMessageFromGitCommit(ref)
226                     depotPath, change = extractDepotPathAndChangeFromGitLog(log)
228                 if changed:
229                     print "%s rewound to %s" % (ref, change)
231         return True
233 class P4Submit(Command):
234     def __init__(self):
235         Command.__init__(self)
236         self.options = [
237                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
238                 optparse.make_option("--origin", dest="origin"),
239                 optparse.make_option("--reset", action="store_true", dest="reset"),
240                 optparse.make_option("--log-substitutions", dest="substFile"),
241                 optparse.make_option("--dry-run", action="store_true"),
242                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
243                 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
244         ]
245         self.description = "Submit changes from git to the perforce depot."
246         self.usage += " [name of git branch to submit into perforce depot]"
247         self.firstTime = True
248         self.reset = False
249         self.interactive = True
250         self.dryRun = False
251         self.substFile = ""
252         self.firstTime = True
253         self.origin = ""
254         self.directSubmit = False
255         self.trustMeLikeAFool = False
257         self.logSubstitutions = {}
258         self.logSubstitutions["<enter description here>"] = "%log%"
259         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
261     def check(self):
262         if len(p4CmdList("opened ...")) > 0:
263             die("You have files opened with perforce! Close them before starting the sync.")
265     def start(self):
266         if len(self.config) > 0 and not self.reset:
267             die("Cannot start sync. Previous sync config found at %s\n"
268                 "If you want to start submitting again from scratch "
269                 "maybe you want to call git-p4 submit --reset" % self.configFile)
271         commits = []
272         if self.directSubmit:
273             commits.append("0")
274         else:
275             for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
276                 commits.append(line[:-1])
277             commits.reverse()
279         self.config["commits"] = commits
281     def prepareLogMessage(self, template, message):
282         result = ""
284         for line in template.split("\n"):
285             if line.startswith("#"):
286                 result += line + "\n"
287                 continue
289             substituted = False
290             for key in self.logSubstitutions.keys():
291                 if line.find(key) != -1:
292                     value = self.logSubstitutions[key]
293                     value = value.replace("%log%", message)
294                     if value != "@remove@":
295                         result += line.replace(key, value) + "\n"
296                     substituted = True
297                     break
299             if not substituted:
300                 result += line + "\n"
302         return result
304     def applyCommit(self, id):
305         if self.directSubmit:
306             print "Applying local change in working directory/index"
307             diff = self.diffStatus
308         else:
309             print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
310             diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
311         filesToAdd = set()
312         filesToDelete = set()
313         editedFiles = set()
314         for line in diff:
315             modifier = line[0]
316             path = line[1:].strip()
317             if modifier == "M":
318                 system("p4 edit \"%s\"" % path)
319                 editedFiles.add(path)
320             elif modifier == "A":
321                 filesToAdd.add(path)
322                 if path in filesToDelete:
323                     filesToDelete.remove(path)
324             elif modifier == "D":
325                 filesToDelete.add(path)
326                 if path in filesToAdd:
327                     filesToAdd.remove(path)
328             else:
329                 die("unknown modifier %s for %s" % (modifier, path))
331         if self.directSubmit:
332             diffcmd = "cat \"%s\"" % self.diffFile
333         else:
334             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
335         patchcmd = diffcmd + " | git apply "
336         tryPatchCmd = patchcmd + "--check -"
337         applyPatchCmd = patchcmd + "--check --apply -"
339         if os.system(tryPatchCmd) != 0:
340             print "Unfortunately applying the change failed!"
341             print "What do you want to do?"
342             response = "x"
343             while response != "s" and response != "a" and response != "w":
344                 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
345                                      "and with .rej files / [w]rite the patch to a file (patch.txt) ")
346             if response == "s":
347                 print "Skipping! Good luck with the next patches..."
348                 return
349             elif response == "a":
350                 os.system(applyPatchCmd)
351                 if len(filesToAdd) > 0:
352                     print "You may also want to call p4 add on the following files:"
353                     print " ".join(filesToAdd)
354                 if len(filesToDelete):
355                     print "The following files should be scheduled for deletion with p4 delete:"
356                     print " ".join(filesToDelete)
357                 die("Please resolve and submit the conflict manually and "
358                     + "continue afterwards with git-p4 submit --continue")
359             elif response == "w":
360                 system(diffcmd + " > patch.txt")
361                 print "Patch saved to patch.txt in %s !" % self.clientPath
362                 die("Please resolve and submit the conflict manually and "
363                     "continue afterwards with git-p4 submit --continue")
365         system(applyPatchCmd)
367         for f in filesToAdd:
368             system("p4 add %s" % f)
369         for f in filesToDelete:
370             system("p4 revert %s" % f)
371             system("p4 delete %s" % f)
373         logMessage = ""
374         if not self.directSubmit:
375             logMessage = extractLogMessageFromGitCommit(id)
376             logMessage = logMessage.replace("\n", "\n\t")
377             logMessage = logMessage[:-1]
379         template = read_pipe("p4 change -o")
381         if self.interactive:
382             submitTemplate = self.prepareLogMessage(template, logMessage)
383             diff = read_pipe("p4 diff -du ...")
385             for newFile in filesToAdd:
386                 diff += "==== new file ====\n"
387                 diff += "--- /dev/null\n"
388                 diff += "+++ %s\n" % newFile
389                 f = open(newFile, "r")
390                 for line in f.readlines():
391                     diff += "+" + line
392                 f.close()
394             separatorLine = "######## everything below this line is just the diff #######"
395             if platform.system() == "Windows":
396                 separatorLine += "\r"
397             separatorLine += "\n"
399             response = "e"
400             if self.trustMeLikeAFool:
401                 response = "y"
403             firstIteration = True
404             while response == "e":
405                 if not firstIteration:
406                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
407                 firstIteration = False
408                 if response == "e":
409                     [handle, fileName] = tempfile.mkstemp()
410                     tmpFile = os.fdopen(handle, "w+")
411                     tmpFile.write(submitTemplate + separatorLine + diff)
412                     tmpFile.close()
413                     defaultEditor = "vi"
414                     if platform.system() == "Windows":
415                         defaultEditor = "notepad"
416                     editor = os.environ.get("EDITOR", defaultEditor);
417                     system(editor + " " + fileName)
418                     tmpFile = open(fileName, "rb")
419                     message = tmpFile.read()
420                     tmpFile.close()
421                     os.remove(fileName)
422                     submitTemplate = message[:message.index(separatorLine)]
424             if response == "y" or response == "yes":
425                if self.dryRun:
426                    print submitTemplate
427                    raw_input("Press return to continue...")
428                else:
429                    if self.directSubmit:
430                        print "Submitting to git first"
431                        os.chdir(self.oldWorkingDirectory)
432                        write_pipe("git commit -a -F -", submitTemplate)
433                        os.chdir(self.clientPath)
435                    write_pipe("p4 submit -i", submitTemplate)
436             elif response == "s":
437                 for f in editedFiles:
438                     system("p4 revert \"%s\"" % f);
439                 for f in filesToAdd:
440                     system("p4 revert \"%s\"" % f);
441                     system("rm %s" %f)
442                 for f in filesToDelete:
443                     system("p4 delete \"%s\"" % f);
444                 return
445             else:
446                 print "Not submitting!"
447                 self.interactive = False
448         else:
449             fileName = "submit.txt"
450             file = open(fileName, "w+")
451             file.write(self.prepareLogMessage(template, logMessage))
452             file.close()
453             print ("Perforce submit template written as %s. "
454                    + "Please review/edit and then use p4 submit -i < %s to submit directly!"
455                    % (fileName, fileName))
457     def run(self, args):
458         global gitdir
459         # make gitdir absolute so we can cd out into the perforce checkout
460         gitdir = os.path.abspath(gitdir)
461         os.environ["GIT_DIR"] = gitdir
463         if len(args) == 0:
464             self.master = currentGitBranch()
465             if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
466                 die("Detecting current git branch failed!")
467         elif len(args) == 1:
468             self.master = args[0]
469         else:
470             return False
472         depotPath = ""
473         if gitBranchExists("p4"):
474             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
475         if len(depotPath) == 0 and gitBranchExists("origin"):
476             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
478         if len(depotPath) == 0:
479             print "Internal error: cannot locate perforce depot path from existing branches"
480             sys.exit(128)
482         self.clientPath = p4Where(depotPath)
484         if len(self.clientPath) == 0:
485             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
486             sys.exit(128)
488         print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
489         self.oldWorkingDirectory = os.getcwd()
491         if self.directSubmit:
492             self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
493             if len(self.diffStatus) == 0:
494                 print "No changes in working directory to submit."
495                 return True
496             patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
497             self.diffFile = gitdir + "/p4-git-diff"
498             f = open(self.diffFile, "wb")
499             f.write(patch)
500             f.close();
502         os.chdir(self.clientPath)
503         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
504         if response == "y" or response == "yes":
505             system("p4 sync ...")
507         if len(self.origin) == 0:
508             if gitBranchExists("p4"):
509                 self.origin = "p4"
510             else:
511                 self.origin = "origin"
513         if self.reset:
514             self.firstTime = True
516         if len(self.substFile) > 0:
517             for line in open(self.substFile, "r").readlines():
518                 tokens = line[:-1].split("=")
519                 self.logSubstitutions[tokens[0]] = tokens[1]
521         self.check()
522         self.configFile = gitdir + "/p4-git-sync.cfg"
523         self.config = shelve.open(self.configFile, writeback=True)
525         if self.firstTime:
526             self.start()
528         commits = self.config.get("commits", [])
530         while len(commits) > 0:
531             self.firstTime = False
532             commit = commits[0]
533             commits = commits[1:]
534             self.config["commits"] = commits
535             self.applyCommit(commit)
536             if not self.interactive:
537                 break
539         self.config.close()
541         if self.directSubmit:
542             os.remove(self.diffFile)
544         if len(commits) == 0:
545             if self.firstTime:
546                 print "No changes found to apply between %s and current HEAD" % self.origin
547             else:
548                 print "All changes applied!"
549                 os.chdir(self.oldWorkingDirectory)
550                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
551                 if response == "y" or response == "yes":
552                     rebase = P4Rebase()
553                     rebase.run([])
554             os.remove(self.configFile)
556         return True
558 class P4Sync(Command):
559     def __init__(self):
560         Command.__init__(self)
561         self.options = [
562                 optparse.make_option("--branch", dest="branch"),
563                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
564                 optparse.make_option("--changesfile", dest="changesFile"),
565                 optparse.make_option("--silent", dest="silent", action="store_true"),
566                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
567                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
568                 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
569                 optparse.make_option("--max-changes", dest="maxChanges")
570         ]
571         self.description = """Imports from Perforce into a git repository.\n
572     example:
573     //depot/my/project/ -- to import the current head
574     //depot/my/project/@all -- to import everything
575     //depot/my/project/@1,6 -- to import only from revision 1 to 6
577     (a ... is not needed in the path p4 specification, it's added implicitly)"""
579         self.usage += " //depot/path[@revRange]"
580         self.silent = False
581         self.createdBranches = Set()
582         self.committedChanges = Set()
583         self.branch = ""
584         self.detectBranches = False
585         self.detectLabels = False
586         self.changesFile = ""
587         self.syncWithOrigin = True
588         self.verbose = False
589         self.importIntoRemotes = True
590         self.maxChanges = ""
591         self.isWindows = (platform.system() == "Windows")
592         self.depotPath = None
594         if gitConfig("git-p4.syncFromOrigin") == "false":
595             self.syncWithOrigin = False
597     def p4File(self, depotPath):
598         return read_pipe("p4 print -q \"%s\"" % depotPath)
600     def extractFilesFromCommit(self, commit):
601         files = []
602         fnum = 0
603         while commit.has_key("depotFile%s" % fnum):
604             path =  commit["depotFile%s" % fnum]
605             if not path.startswith(self.depotPath):
606     #            if not self.silent:
607     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
608                 fnum = fnum + 1
609                 continue
611             file = {}
612             file["path"] = path
613             file["rev"] = commit["rev%s" % fnum]
614             file["action"] = commit["action%s" % fnum]
615             file["type"] = commit["type%s" % fnum]
616             files.append(file)
617             fnum = fnum + 1
618         return files
620     def stripRepoPath(self, path):
621         return path[len(self.depotPath):]
623     def splitFilesIntoBranches(self, commit):
624         branches = {}
625         fnum = 0
626         while commit.has_key("depotFile%s" % fnum):
627             path =  commit["depotFile%s" % fnum]
628             if not path.startswith(self.depotPath):
629     #            if not self.silent:
630     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
631                 fnum = fnum + 1
632                 continue
634             file = {}
635             file["path"] = path
636             file["rev"] = commit["rev%s" % fnum]
637             file["action"] = commit["action%s" % fnum]
638             file["type"] = commit["type%s" % fnum]
639             fnum = fnum + 1
641             relPath = self.stripRepoPath(path)
643             for branch in self.knownBranches.keys():
645                 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
646                 if relPath.startswith(branch + "/"):
647                     if branch not in branches:
648                         branches[branch] = []
649                     branches[branch].append(file)
651         return branches
653     def commit(self, details, files, branch, branchPrefix, parent = ""):
654         epoch = details["time"]
655         author = details["user"]
657         if self.verbose:
658             print "commit into %s" % branch
660         self.gitStream.write("commit %s\n" % branch)
661     #    gitStream.write("mark :%s\n" % details["change"])
662         self.committedChanges.add(int(details["change"]))
663         committer = ""
664         if author not in self.users:
665             self.getUserMapFromPerforceServer()
666         if author in self.users:
667             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
668         else:
669             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
671         self.gitStream.write("committer %s\n" % committer)
673         self.gitStream.write("data <<EOT\n")
674         self.gitStream.write(details["desc"])
675         self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
676         self.gitStream.write("EOT\n\n")
678         if len(parent) > 0:
679             if self.verbose:
680                 print "parent %s" % parent
681             self.gitStream.write("from %s\n" % parent)
683         for file in files:
684             path = file["path"]
685             if not path.startswith(branchPrefix):
686     #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
687                 continue
688             rev = file["rev"]
689             depotPath = path + "#" + rev
690             relPath = path[len(branchPrefix):]
691             action = file["action"]
693             if file["type"] == "apple":
694                 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
695                 continue
697             if action == "delete":
698                 self.gitStream.write("D %s\n" % relPath)
699             else:
700                 mode = 644
701                 if file["type"].startswith("x"):
702                     mode = 755
704                 data = self.p4File(depotPath)
706                 if self.isWindows and file["type"].endswith("text"):
707                     data = data.replace("\r\n", "\n")
709                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
710                 self.gitStream.write("data %s\n" % len(data))
711                 self.gitStream.write(data)
712                 self.gitStream.write("\n")
714         self.gitStream.write("\n")
716         change = int(details["change"])
718         if self.labels.has_key(change):
719             label = self.labels[change]
720             labelDetails = label[0]
721             labelRevisions = label[1]
722             if self.verbose:
723                 print "Change %s is labelled %s" % (change, labelDetails)
725             files = p4CmdList("files %s...@%s" % (branchPrefix, change))
727             if len(files) == len(labelRevisions):
729                 cleanedFiles = {}
730                 for info in files:
731                     if info["action"] == "delete":
732                         continue
733                     cleanedFiles[info["depotFile"]] = info["rev"]
735                 if cleanedFiles == labelRevisions:
736                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
737                     self.gitStream.write("from %s\n" % branch)
739                     owner = labelDetails["Owner"]
740                     tagger = ""
741                     if author in self.users:
742                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
743                     else:
744                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
745                     self.gitStream.write("tagger %s\n" % tagger)
746                     self.gitStream.write("data <<EOT\n")
747                     self.gitStream.write(labelDetails["Description"])
748                     self.gitStream.write("EOT\n\n")
750                 else:
751                     if not self.silent:
752                         print ("Tag %s does not match with change %s: files do not match."
753                                % (labelDetails["label"], change))
755             else:
756                 if not self.silent:
757                     print ("Tag %s does not match with change %s: file count is different."
758                            % (labelDetails["label"], change))
760     def getUserMapFromPerforceServer(self):
761         if self.userMapFromPerforceServer:
762             return
763         self.users = {}
765         for output in p4CmdList("users"):
766             if not output.has_key("User"):
767                 continue
768             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
770         cache = open(gitdir + "/p4-usercache.txt", "wb")
771         for user in self.users.keys():
772             cache.write("%s\t%s\n" % (user, self.users[user]))
773         cache.close();
774         self.userMapFromPerforceServer = True
776     def loadUserMapFromCache(self):
777         self.users = {}
778         self.userMapFromPerforceServer = False
779         try:
780             cache = open(gitdir + "/p4-usercache.txt", "rb")
781             lines = cache.readlines()
782             cache.close()
783             for line in lines:
784                 entry = line[:-1].split("\t")
785                 self.users[entry[0]] = entry[1]
786         except IOError:
787             self.getUserMapFromPerforceServer()
789     def getLabels(self):
790         self.labels = {}
792         l = p4CmdList("labels %s..." % self.depotPath)
793         if len(l) > 0 and not self.silent:
794             print "Finding files belonging to labels in %s" % self.depotPath
796         for output in l:
797             label = output["label"]
798             revisions = {}
799             newestChange = 0
800             if self.verbose:
801                 print "Querying files for label %s" % label
802             for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
803                 revisions[file["depotFile"]] = file["rev"]
804                 change = int(file["change"])
805                 if change > newestChange:
806                     newestChange = change
808             self.labels[newestChange] = [output, revisions]
810         if self.verbose:
811             print "Label changes: %s" % self.labels.keys()
813     def getBranchMapping(self):
814         self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
816         for info in p4CmdList("branches"):
817             details = p4Cmd("branch -o %s" % info["branch"])
818             viewIdx = 0
819             while details.has_key("View%s" % viewIdx):
820                 paths = details["View%s" % viewIdx].split(" ")
821                 viewIdx = viewIdx + 1
822                 # require standard //depot/foo/... //depot/bar/... mapping
823                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
824                     continue
825                 source = paths[0]
826                 destination = paths[1]
827                 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
828                     source = source[len(self.depotPath):-4]
829                     destination = destination[len(self.depotPath):-4]
830                     if destination not in self.knownBranches:
831                         self.knownBranches[destination] = source
832                     if source not in self.knownBranches:
833                         self.knownBranches[source] = source
835     def listExistingP4GitBranches(self):
836         self.p4BranchesInGit = []
838         cmdline = "git rev-parse --symbolic "
839         if self.importIntoRemotes:
840             cmdline += " --remotes"
841         else:
842             cmdline += " --branches"
844         for line in read_pipe_lines(cmdline):
845             if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
846                 continue
847             if self.importIntoRemotes:
848                 # strip off p4
849                 branch = line[3:-1]
850             else:
851                 branch = line[:-1]
852             self.p4BranchesInGit.append(branch)
853             self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
855     def createOrUpdateBranchesFromOrigin(self):
856         if not self.silent:
857             print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
859         for line in mypopen("git rev-parse --symbolic --remotes"):
860             if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
861                 continue
863             headName = line[len("origin/"):-1]
864             remoteHead = self.refPrefix + headName
865             originHead = "origin/" + headName
867             [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead))
868             if len(originPreviousDepotPath) == 0 or len(originP4Change) == 0:
869                 continue
871             update = False
872             if not gitBranchExists(remoteHead):
873                 if self.verbose:
874                     print "creating %s" % remoteHead
875                 update = True
876             else:
877                 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead))
878                 if len(p4Change) > 0:
879                     if originPreviousDepotPath == p4PreviousDepotPath:
880                         originP4Change = int(originP4Change)
881                         p4Change = int(p4Change)
882                         if originP4Change > p4Change:
883                             print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead, originP4Change, remoteHead, p4Change)
884                             update = True
885                     else:
886                         print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead, originPreviousDepotPath, remoteHead, p4PreviousDepotPath)
888             if update:
889                 system("git update-ref %s %s" % (remoteHead, originHead))
891     def run(self, args):
892         self.depotPath = ""
893         self.changeRange = ""
894         self.initialParent = ""
895         self.previousDepotPath = ""
897         # map from branch depot path to parent branch
898         self.knownBranches = {}
899         self.initialParents = {}
900         self.hasOrigin = gitBranchExists("origin")
902         if self.importIntoRemotes:
903             self.refPrefix = "refs/remotes/p4/"
904         else:
905             self.refPrefix = "refs/heads/"
907         if self.syncWithOrigin and self.hasOrigin:
908             if not self.silent:
909                 print "Syncing with origin first by calling git fetch origin"
910             system("git fetch origin")
912         if len(self.branch) == 0:
913             self.branch = self.refPrefix + "master"
914             if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
915                 system("git update-ref %s refs/heads/p4" % self.branch)
916                 system("git branch -D p4");
917             # create it /after/ importing, when master exists
918             if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
919                 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
921         if len(args) == 0:
922             if self.hasOrigin:
923                 self.createOrUpdateBranchesFromOrigin()
924             self.listExistingP4GitBranches()
926             if len(self.p4BranchesInGit) > 1:
927                 if not self.silent:
928                     print "Importing from/into multiple branches"
929                 self.detectBranches = True
931             if self.verbose:
932                 print "branches: %s" % self.p4BranchesInGit
934             p4Change = 0
935             for branch in self.p4BranchesInGit:
936                 logMsg =  extractLogMessageFromGitCommit(self.refPrefix + branch)
937                 (depotPath, change) = extractDepotPathAndChangeFromGitLog(logMsg)
939                 if self.verbose:
940                     print "path %s change %s" % (depotPath, change)
942                 if len(depotPath) > 0 and len(change) > 0:
943                     change = int(change) + 1
944                     p4Change = max(p4Change, change)
946                     if len(self.previousDepotPath) == 0:
947                         self.previousDepotPath = depotPath
948                     else:
949                         i = 0
950                         l = min(len(self.previousDepotPath), len(depotPath))
951                         while i < l and self.previousDepotPath[i] == depotPath[i]:
952                             i = i + 1
953                         self.previousDepotPath = self.previousDepotPath[:i]
955             if p4Change > 0:
956                 self.depotPath = self.previousDepotPath
957                 self.changeRange = "@%s,#head" % p4Change
958                 self.initialParent = parseRevision(self.branch)
959                 if not self.silent and not self.detectBranches:
960                     print "Performing incremental import into %s git branch" % self.branch
962         if not self.branch.startswith("refs/"):
963             self.branch = "refs/heads/" + self.branch
965         if len(self.depotPath) != 0:
966             self.depotPath = self.depotPath[:-1]
968         if len(args) == 0 and len(self.depotPath) != 0:
969             if not self.silent:
970                 print "Depot path: %s" % self.depotPath
971         elif len(args) != 1:
972             return False
973         else:
974             if len(self.depotPath) != 0 and self.depotPath != args[0]:
975                 print ("previous import used depot path %s and now %s was specified. "
976                        "This doesn't work!" % (self.depotPath, args[0]))
977                 sys.exit(1)
978             self.depotPath = args[0]
980         self.revision = ""
981         self.users = {}
983         if self.depotPath.find("@") != -1:
984             atIdx = self.depotPath.index("@")
985             self.changeRange = self.depotPath[atIdx:]
986             if self.changeRange == "@all":
987                 self.changeRange = ""
988             elif self.changeRange.find(",") == -1:
989                 self.revision = self.changeRange
990                 self.changeRange = ""
991             self.depotPath = self.depotPath[0:atIdx]
992         elif self.depotPath.find("#") != -1:
993             hashIdx = self.depotPath.index("#")
994             self.revision = self.depotPath[hashIdx:]
995             self.depotPath = self.depotPath[0:hashIdx]
996         elif len(self.previousDepotPath) == 0:
997             self.revision = "#head"
999         self.depotPath = re.sub ("\.\.\.$", "", self.depotPath)
1000         if not self.depotPath.endswith("/"):
1001             self.depotPath += "/"
1003         self.loadUserMapFromCache()
1004         self.labels = {}
1005         if self.detectLabels:
1006             self.getLabels();
1008         if self.detectBranches:
1009             self.getBranchMapping();
1010             if self.verbose:
1011                 print "p4-git branches: %s" % self.p4BranchesInGit
1012                 print "initial parents: %s" % self.initialParents
1013             for b in self.p4BranchesInGit:
1014                 if b != "master":
1015                     b = b[len(self.projectName):]
1016                 self.createdBranches.add(b)
1018         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1020         importProcess = subprocess.Popen(["git", "fast-import"],
1021                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
1022         self.gitOutput = importProcess.stdout
1023         self.gitStream = importProcess.stdin
1024         self.gitError = importProcess.stderr
1026         if len(self.revision) > 0:
1027             print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
1029             details = { "user" : "git perforce import user", "time" : int(time.time()) }
1030             details["desc"] = ("Initial import of %s from the state at revision %s"
1031                                % (self.depotPath, self.revision))
1032             details["change"] = self.revision
1033             newestRevision = 0
1035             fileCnt = 0
1036             for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
1037                 change = int(info["change"])
1038                 if change > newestRevision:
1039                     newestRevision = change
1041                 if info["action"] == "delete":
1042                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1043                     #fileCnt = fileCnt + 1
1044                     continue
1046                 for prop in [ "depotFile", "rev", "action", "type" ]:
1047                     details["%s%s" % (prop, fileCnt)] = info[prop]
1049                 fileCnt = fileCnt + 1
1051             details["change"] = newestRevision
1053             try:
1054                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
1055             except IOError:
1056                 print "IO error with git fast-import. Is your git version recent enough?"
1057                 print self.gitError.read()
1059         else:
1060             changes = []
1062             if len(self.changesFile) > 0:
1063                 output = open(self.changesFile).readlines()
1064                 changeSet = Set()
1065                 for line in output:
1066                     changeSet.add(int(line))
1068                 for change in changeSet:
1069                     changes.append(change)
1071                 changes.sort()
1072             else:
1073                 if self.verbose:
1074                     print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
1075                 output = read_pipe_lines("p4 changes %s...%s" % (self.depotPath, self.changeRange))
1077                 for line in output:
1078                     changeNum = line.split(" ")[1]
1079                     changes.append(changeNum)
1081                 changes.reverse()
1083                 if len(self.maxChanges) > 0:
1084                     changes = changes[0:min(int(self.maxChanges), len(changes))]
1086             if len(changes) == 0:
1087                 if not self.silent:
1088                     print "No changes to import!"
1089                 return True
1091             self.updatedBranches = set()
1093             cnt = 1
1094             for change in changes:
1095                 description = p4Cmd("describe %s" % change)
1097                 if not self.silent:
1098                     sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1099                     sys.stdout.flush()
1100                 cnt = cnt + 1
1102                 try:
1103                     if self.detectBranches:
1104                         branches = self.splitFilesIntoBranches(description)
1105                         for branch in branches.keys():
1106                             branchPrefix = self.depotPath + branch + "/"
1108                             parent = ""
1110                             filesForCommit = branches[branch]
1112                             if self.verbose:
1113                                 print "branch is %s" % branch
1115                             self.updatedBranches.add(branch)
1117                             if branch not in self.createdBranches:
1118                                 self.createdBranches.add(branch)
1119                                 parent = self.knownBranches[branch]
1120                                 if parent == branch:
1121                                     parent = ""
1122                                 elif self.verbose:
1123                                     print "parent determined through known branches: %s" % parent
1125                             # main branch? use master
1126                             if branch == "main":
1127                                 branch = "master"
1128                             else:
1129                                 branch = self.projectName + branch
1131                             if parent == "main":
1132                                 parent = "master"
1133                             elif len(parent) > 0:
1134                                 parent = self.projectName + parent
1136                             branch = self.refPrefix + branch
1137                             if len(parent) > 0:
1138                                 parent = self.refPrefix + parent
1140                             if self.verbose:
1141                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1143                             if len(parent) == 0 and branch in self.initialParents:
1144                                 parent = self.initialParents[branch]
1145                                 del self.initialParents[branch]
1147                             self.commit(description, filesForCommit, branch, branchPrefix, parent)
1148                     else:
1149                         files = self.extractFilesFromCommit(description)
1150                         self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1151                         self.initialParent = ""
1152                 except IOError:
1153                     print self.gitError.read()
1154                     sys.exit(1)
1156             if not self.silent:
1157                 print ""
1158                 if len(self.updatedBranches) > 0:
1159                     sys.stdout.write("Updated branches: ")
1160                     for b in self.updatedBranches:
1161                         sys.stdout.write("%s " % b)
1162                     sys.stdout.write("\n")
1165         self.gitStream.close()
1166         if importProcess.wait() != 0:
1167             die("fast-import failed: %s" % self.gitError.read())
1168         self.gitOutput.close()
1169         self.gitError.close()
1171         return True
1173 class P4Rebase(Command):
1174     def __init__(self):
1175         Command.__init__(self)
1176         self.options = [ ]
1177         self.description = ("Fetches the latest revision from perforce and "
1178                             + "rebases the current work (branch) against it")
1180     def run(self, args):
1181         sync = P4Sync()
1182         sync.run([])
1183         print "Rebasing the current branch"
1184         oldHead = read_pipe("git rev-parse HEAD")[:-1]
1185         system("git rebase p4")
1186         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1187         return True
1189 class P4Clone(P4Sync):
1190     def __init__(self):
1191         P4Sync.__init__(self)
1192         self.description = "Creates a new git repository and imports from Perforce into it"
1193         self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1194         self.needsGit = False
1196     def run(self, args):
1197         global gitdir
1199         if len(args) < 1:
1200             return False
1201         depotPath = args[0]
1202         destination = ""
1203         if len(args) == 2:
1204             destination = args[1]
1205         elif len(args) > 2:
1206             return False
1208         if not depotPath.startswith("//"):
1209             return False
1211         depotDir = re.sub("(@[^@]*)$", "", depotPath)
1212         depotDir = re.sub("(#[^#]*)$", "", depotDir)
1213         depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1214         depotDir = re.sub(r"/$", "", depotDir)
1216         if not destination:
1217             destination = os.path.split(depotDir)[-1]
1219         print "Importing from %s into %s" % (depotPath, destination)
1220         os.makedirs(destination)
1221         os.chdir(destination)
1222         system("git init")
1223         gitdir = os.getcwd() + "/.git"
1224         if not P4Sync.run(self, [depotPath]):
1225             return False
1226         if self.branch != "master":
1227             if gitBranchExists("refs/remotes/p4/master"):
1228                 system("git branch master refs/remotes/p4/master")
1229                 system("git checkout -f")
1230             else:
1231                 print "Could not detect main branch. No checkout/master branch created."
1232         return True
1234 class HelpFormatter(optparse.IndentedHelpFormatter):
1235     def __init__(self):
1236         optparse.IndentedHelpFormatter.__init__(self)
1238     def format_description(self, description):
1239         if description:
1240             return description + "\n"
1241         else:
1242             return ""
1244 def printUsage(commands):
1245     print "usage: %s <command> [options]" % sys.argv[0]
1246     print ""
1247     print "valid commands: %s" % ", ".join(commands)
1248     print ""
1249     print "Try %s <command> --help for command specific help." % sys.argv[0]
1250     print ""
1252 commands = {
1253     "debug" : P4Debug(),
1254     "submit" : P4Submit(),
1255     "sync" : P4Sync(),
1256     "rebase" : P4Rebase(),
1257     "clone" : P4Clone(),
1258     "rollback" : P4RollBack()
1261 if len(sys.argv[1:]) == 0:
1262     printUsage(commands.keys())
1263     sys.exit(2)
1265 cmd = ""
1266 cmdName = sys.argv[1]
1267 try:
1268     cmd = commands[cmdName]
1269 except KeyError:
1270     print "unknown command %s" % cmdName
1271     print ""
1272     printUsage(commands.keys())
1273     sys.exit(2)
1275 options = cmd.options
1276 cmd.gitdir = gitdir
1278 args = sys.argv[2:]
1280 if len(options) > 0:
1281     options.append(optparse.make_option("--git-dir", dest="gitdir"))
1283     parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1284                                    options,
1285                                    description = cmd.description,
1286                                    formatter = HelpFormatter())
1288     (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1290 if cmd.needsGit:
1291     gitdir = cmd.gitdir
1292     if len(gitdir) == 0:
1293         gitdir = ".git"
1294         if not isValidGitDir(gitdir):
1295             gitdir = read_pipe("git rev-parse --git-dir")[:-1]
1296             if os.path.exists(gitdir):
1297                 cdup = read_pipe("git rev-parse --show-cdup")[:-1];
1298                 if len(cdup) > 0:
1299                     os.chdir(cdup);
1301     if not isValidGitDir(gitdir):
1302         if isValidGitDir(gitdir + "/.git"):
1303             gitdir += "/.git"
1304         else:
1305             die("fatal: cannot locate git repository at %s" % gitdir)
1307     os.environ["GIT_DIR"] = gitdir
1309 if not cmd.run(args):
1310     parser.print_help()