Code

8d649dd7628fd9c8079549a9bb73548255512481
[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     sys.stderr.write('reading pipe: %s\n' % c)
34     ## todo: check return status
35     pipe = os.popen(c, 'rb')
36     val = pipe.read()
37     if pipe.close():
38         sys.stderr.write('Command failed')
39         sys.exit(1)
41     return val
44 def read_pipe_lines(c):
45     sys.stderr.write('reading pipe: %s\n' % c)
46     ## todo: check return status
47     pipe = os.popen(c, 'rb')
48     val = pipe.readlines()
49     if pipe.close():
50         sys.stderr.write('Command failed')
51         sys.exit(1)
53     return val
55 def p4CmdList(cmd):
56     cmd = "p4 -G %s" % cmd
57     pipe = os.popen(cmd, "rb")
59     result = []
60     try:
61         while True:
62             entry = marshal.load(pipe)
63             result.append(entry)
64     except EOFError:
65         pass
66     exitCode = pipe.close()
67     if exitCode != None:
68         entry = {}
69         entry["p4ExitCode"] = exitCode
70         result.append(entry)
72     return result
74 def p4Cmd(cmd):
75     list = p4CmdList(cmd)
76     result = {}
77     for entry in list:
78         result.update(entry)
79     return result;
81 def p4Where(depotPath):
82     if not depotPath.endswith("/"):
83         depotPath += "/"
84     output = p4Cmd("where %s..." % depotPath)
85     if output["code"] == "error":
86         return ""
87     clientPath = ""
88     if "path" in output:
89         clientPath = output.get("path")
90     elif "data" in output:
91         data = output.get("data")
92         lastSpace = data.rfind(" ")
93         clientPath = data[lastSpace + 1:]
95     if clientPath.endswith("..."):
96         clientPath = clientPath[:-3]
97     return clientPath
99 def die(msg):
100     sys.stderr.write(msg + "\n")
101     sys.exit(1)
103 def currentGitBranch():
104     return read_pipe("git name-rev HEAD").split(" ")[1][:-1]
106 def isValidGitDir(path):
107     if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
108         return True;
109     return False
111 def parseRevision(ref):
112     return read_pipe("git rev-parse %s" % ref)[:-1]
114 def system(cmd):
115     if os.system(cmd) != 0:
116         die("command failed: %s" % cmd)
118 def extractLogMessageFromGitCommit(commit):
119     logMessage = ""
121     ## fixme: title is first line of commit, not 1st paragraph.
122     foundTitle = False
123     for log in read_pipe_lines("git cat-file commit %s" % commit):
124        if not foundTitle:
125            if len(log) == 1:
126                foundTitle = True
127            continue
129        logMessage += log
130     return logMessage
132 def extractDepotPathAndChangeFromGitLog(log):
133     values = {}
134     for line in log.split("\n"):
135         line = line.strip()
136         if line.startswith("[git-p4:") and line.endswith("]"):
137             line = line[8:-1].strip()
138             for assignment in line.split(":"):
139                 variable = assignment.strip()
140                 value = ""
141                 equalPos = assignment.find("=")
142                 if equalPos != -1:
143                     variable = assignment[:equalPos].strip()
144                     value = assignment[equalPos + 1:].strip()
145                     if value.startswith("\"") and value.endswith("\""):
146                         value = value[1:-1]
147                 values[variable] = value
149     return values.get("depot-path"), values.get("change")
151 def gitBranchExists(branch):
152     proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
153     return proc.wait() == 0;
155 def gitConfig(key):
156     return mypopen("git config %s" % key).read()[:-1]
158 class Command:
159     def __init__(self):
160         self.usage = "usage: %prog [options]"
161         self.needsGit = True
163 class P4Debug(Command):
164     def __init__(self):
165         Command.__init__(self)
166         self.options = [
167         ]
168         self.description = "A tool to debug the output of p4 -G."
169         self.needsGit = False
171     def run(self, args):
172         for output in p4CmdList(" ".join(args)):
173             print output
174         return True
176 class P4RollBack(Command):
177     def __init__(self):
178         Command.__init__(self)
179         self.options = [
180             optparse.make_option("--verbose", dest="verbose", action="store_true"),
181             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
182         ]
183         self.description = "A tool to debug the multi-branch import. Don't use :)"
184         self.verbose = False
185         self.rollbackLocalBranches = False
187     def run(self, args):
188         if len(args) != 1:
189             return False
190         maxChange = int(args[0])
192         if "p4ExitCode" in p4Cmd("changes -m 1"):
193             die("Problems executing p4");
195         if self.rollbackLocalBranches:
196             refPrefix = "refs/heads/"
197             lines = read_pipe_lines("git rev-parse --symbolic --branches")
198         else:
199             refPrefix = "refs/remotes/"
200             lines = read_pipe_lines("git rev-parse --symbolic --remotes")
202         for line in lines:
203             if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
204                 ref = refPrefix + line[:-1]
205                 log = extractLogMessageFromGitCommit(ref)
206                 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
207                 changed = False
209                 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
210                     print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
211                     system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
212                     continue
214                 while len(change) > 0 and int(change) > maxChange:
215                     changed = True
216                     if self.verbose:
217                         print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
218                     system("git update-ref %s \"%s^\"" % (ref, ref))
219                     log = extractLogMessageFromGitCommit(ref)
220                     depotPath, change = extractDepotPathAndChangeFromGitLog(log)
222                 if changed:
223                     print "%s rewound to %s" % (ref, change)
225         return True
227 class P4Submit(Command):
228     def __init__(self):
229         Command.__init__(self)
230         self.options = [
231                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
232                 optparse.make_option("--origin", dest="origin"),
233                 optparse.make_option("--reset", action="store_true", dest="reset"),
234                 optparse.make_option("--log-substitutions", dest="substFile"),
235                 optparse.make_option("--dry-run", action="store_true"),
236                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
237                 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
238         ]
239         self.description = "Submit changes from git to the perforce depot."
240         self.usage += " [name of git branch to submit into perforce depot]"
241         self.firstTime = True
242         self.reset = False
243         self.interactive = True
244         self.dryRun = False
245         self.substFile = ""
246         self.firstTime = True
247         self.origin = ""
248         self.directSubmit = False
249         self.trustMeLikeAFool = False
251         self.logSubstitutions = {}
252         self.logSubstitutions["<enter description here>"] = "%log%"
253         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
255     def check(self):
256         if len(p4CmdList("opened ...")) > 0:
257             die("You have files opened with perforce! Close them before starting the sync.")
259     def start(self):
260         if len(self.config) > 0 and not self.reset:
261             die("Cannot start sync. Previous sync config found at %s\n"
262                 "If you want to start submitting again from scratch "
263                 "maybe you want to call git-p4 submit --reset" % self.configFile)
265         commits = []
266         if self.directSubmit:
267             commits.append("0")
268         else:
269             for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
270                 commits.append(line[:-1])
271             commits.reverse()
273         self.config["commits"] = commits
275     def prepareLogMessage(self, template, message):
276         result = ""
278         for line in template.split("\n"):
279             if line.startswith("#"):
280                 result += line + "\n"
281                 continue
283             substituted = False
284             for key in self.logSubstitutions.keys():
285                 if line.find(key) != -1:
286                     value = self.logSubstitutions[key]
287                     value = value.replace("%log%", message)
288                     if value != "@remove@":
289                         result += line.replace(key, value) + "\n"
290                     substituted = True
291                     break
293             if not substituted:
294                 result += line + "\n"
296         return result
298     def applyCommit(self, id):
299         if self.directSubmit:
300             print "Applying local change in working directory/index"
301             diff = self.diffStatus
302         else:
303             print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
304             diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
305         filesToAdd = set()
306         filesToDelete = set()
307         editedFiles = set()
308         for line in diff:
309             modifier = line[0]
310             path = line[1:].strip()
311             if modifier == "M":
312                 system("p4 edit \"%s\"" % path)
313                 editedFiles.add(path)
314             elif modifier == "A":
315                 filesToAdd.add(path)
316                 if path in filesToDelete:
317                     filesToDelete.remove(path)
318             elif modifier == "D":
319                 filesToDelete.add(path)
320                 if path in filesToAdd:
321                     filesToAdd.remove(path)
322             else:
323                 die("unknown modifier %s for %s" % (modifier, path))
325         if self.directSubmit:
326             diffcmd = "cat \"%s\"" % self.diffFile
327         else:
328             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
329         patchcmd = diffcmd + " | git apply "
330         tryPatchCmd = patchcmd + "--check -"
331         applyPatchCmd = patchcmd + "--check --apply -"
333         if os.system(tryPatchCmd) != 0:
334             print "Unfortunately applying the change failed!"
335             print "What do you want to do?"
336             response = "x"
337             while response != "s" and response != "a" and response != "w":
338                 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
339                                      "and with .rej files / [w]rite the patch to a file (patch.txt) ")
340             if response == "s":
341                 print "Skipping! Good luck with the next patches..."
342                 return
343             elif response == "a":
344                 os.system(applyPatchCmd)
345                 if len(filesToAdd) > 0:
346                     print "You may also want to call p4 add on the following files:"
347                     print " ".join(filesToAdd)
348                 if len(filesToDelete):
349                     print "The following files should be scheduled for deletion with p4 delete:"
350                     print " ".join(filesToDelete)
351                 die("Please resolve and submit the conflict manually and "
352                     + "continue afterwards with git-p4 submit --continue")
353             elif response == "w":
354                 system(diffcmd + " > patch.txt")
355                 print "Patch saved to patch.txt in %s !" % self.clientPath
356                 die("Please resolve and submit the conflict manually and "
357                     "continue afterwards with git-p4 submit --continue")
359         system(applyPatchCmd)
361         for f in filesToAdd:
362             system("p4 add %s" % f)
363         for f in filesToDelete:
364             system("p4 revert %s" % f)
365             system("p4 delete %s" % f)
367         logMessage = ""
368         if not self.directSubmit:
369             logMessage = extractLogMessageFromGitCommit(id)
370             logMessage = logMessage.replace("\n", "\n\t")
371             logMessage = logMessage[:-1]
373         template = read_pipe("p4 change -o")
375         if self.interactive:
376             submitTemplate = self.prepareLogMessage(template, logMessage)
377             diff = read_pipe("p4 diff -du ...")
379             for newFile in filesToAdd:
380                 diff += "==== new file ====\n"
381                 diff += "--- /dev/null\n"
382                 diff += "+++ %s\n" % newFile
383                 f = open(newFile, "r")
384                 for line in f.readlines():
385                     diff += "+" + line
386                 f.close()
388             separatorLine = "######## everything below this line is just the diff #######"
389             if platform.system() == "Windows":
390                 separatorLine += "\r"
391             separatorLine += "\n"
393             response = "e"
394             if self.trustMeLikeAFool:
395                 response = "y"
397             firstIteration = True
398             while response == "e":
399                 if not firstIteration:
400                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
401                 firstIteration = False
402                 if response == "e":
403                     [handle, fileName] = tempfile.mkstemp()
404                     tmpFile = os.fdopen(handle, "w+")
405                     tmpFile.write(submitTemplate + separatorLine + diff)
406                     tmpFile.close()
407                     defaultEditor = "vi"
408                     if platform.system() == "Windows":
409                         defaultEditor = "notepad"
410                     editor = os.environ.get("EDITOR", defaultEditor);
411                     system(editor + " " + fileName)
412                     tmpFile = open(fileName, "rb")
413                     message = tmpFile.read()
414                     tmpFile.close()
415                     os.remove(fileName)
416                     submitTemplate = message[:message.index(separatorLine)]
418             if response == "y" or response == "yes":
419                if self.dryRun:
420                    print submitTemplate
421                    raw_input("Press return to continue...")
422                else:
423                    if self.directSubmit:
424                        print "Submitting to git first"
425                        os.chdir(self.oldWorkingDirectory)
426                        write_pipe("git commit -a -F -", submitTemplate)
427                        os.chdir(self.clientPath)
429                    write_pipe("p4 submit -i", submitTemplate)
430             elif response == "s":
431                 for f in editedFiles:
432                     system("p4 revert \"%s\"" % f);
433                 for f in filesToAdd:
434                     system("p4 revert \"%s\"" % f);
435                     system("rm %s" %f)
436                 for f in filesToDelete:
437                     system("p4 delete \"%s\"" % f);
438                 return
439             else:
440                 print "Not submitting!"
441                 self.interactive = False
442         else:
443             fileName = "submit.txt"
444             file = open(fileName, "w+")
445             file.write(self.prepareLogMessage(template, logMessage))
446             file.close()
447             print ("Perforce submit template written as %s. "
448                    + "Please review/edit and then use p4 submit -i < %s to submit directly!"
449                    % (fileName, fileName))
451     def run(self, args):
452         global gitdir
453         # make gitdir absolute so we can cd out into the perforce checkout
454         gitdir = os.path.abspath(gitdir)
455         os.environ["GIT_DIR"] = gitdir
457         if len(args) == 0:
458             self.master = currentGitBranch()
459             if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
460                 die("Detecting current git branch failed!")
461         elif len(args) == 1:
462             self.master = args[0]
463         else:
464             return False
466         depotPath = ""
467         if gitBranchExists("p4"):
468             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
469         if len(depotPath) == 0 and gitBranchExists("origin"):
470             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
472         if len(depotPath) == 0:
473             print "Internal error: cannot locate perforce depot path from existing branches"
474             sys.exit(128)
476         self.clientPath = p4Where(depotPath)
478         if len(self.clientPath) == 0:
479             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
480             sys.exit(128)
482         print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
483         self.oldWorkingDirectory = os.getcwd()
485         if self.directSubmit:
486             self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
487             if len(self.diffStatus) == 0:
488                 print "No changes in working directory to submit."
489                 return True
490             patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
491             self.diffFile = gitdir + "/p4-git-diff"
492             f = open(self.diffFile, "wb")
493             f.write(patch)
494             f.close();
496         os.chdir(self.clientPath)
497         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
498         if response == "y" or response == "yes":
499             system("p4 sync ...")
501         if len(self.origin) == 0:
502             if gitBranchExists("p4"):
503                 self.origin = "p4"
504             else:
505                 self.origin = "origin"
507         if self.reset:
508             self.firstTime = True
510         if len(self.substFile) > 0:
511             for line in open(self.substFile, "r").readlines():
512                 tokens = line[:-1].split("=")
513                 self.logSubstitutions[tokens[0]] = tokens[1]
515         self.check()
516         self.configFile = gitdir + "/p4-git-sync.cfg"
517         self.config = shelve.open(self.configFile, writeback=True)
519         if self.firstTime:
520             self.start()
522         commits = self.config.get("commits", [])
524         while len(commits) > 0:
525             self.firstTime = False
526             commit = commits[0]
527             commits = commits[1:]
528             self.config["commits"] = commits
529             self.applyCommit(commit)
530             if not self.interactive:
531                 break
533         self.config.close()
535         if self.directSubmit:
536             os.remove(self.diffFile)
538         if len(commits) == 0:
539             if self.firstTime:
540                 print "No changes found to apply between %s and current HEAD" % self.origin
541             else:
542                 print "All changes applied!"
543                 os.chdir(self.oldWorkingDirectory)
544                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
545                 if response == "y" or response == "yes":
546                     rebase = P4Rebase()
547                     rebase.run([])
548             os.remove(self.configFile)
550         return True
552 class P4Sync(Command):
553     def __init__(self):
554         Command.__init__(self)
555         self.options = [
556                 optparse.make_option("--branch", dest="branch"),
557                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
558                 optparse.make_option("--changesfile", dest="changesFile"),
559                 optparse.make_option("--silent", dest="silent", action="store_true"),
560                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
561                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
562                 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
563                 optparse.make_option("--max-changes", dest="maxChanges")
564         ]
565         self.description = """Imports from Perforce into a git repository.\n
566     example:
567     //depot/my/project/ -- to import the current head
568     //depot/my/project/@all -- to import everything
569     //depot/my/project/@1,6 -- to import only from revision 1 to 6
571     (a ... is not needed in the path p4 specification, it's added implicitly)"""
573         self.usage += " //depot/path[@revRange]"
575         self.silent = False
576         self.createdBranches = Set()
577         self.committedChanges = Set()
578         self.branch = ""
579         self.detectBranches = False
580         self.detectLabels = False
581         self.changesFile = ""
582         self.syncWithOrigin = True
583         self.verbose = False
584         self.importIntoRemotes = True
585         self.maxChanges = ""
586         self.isWindows = (platform.system() == "Windows")
588         if gitConfig("git-p4.syncFromOrigin") == "false":
589             self.syncWithOrigin = False
591     def p4File(self, depotPath):
592         return read_pipe("p4 print -q \"%s\"" % depotPath)
594     def extractFilesFromCommit(self, commit):
595         files = []
596         fnum = 0
597         while commit.has_key("depotFile%s" % fnum):
598             path =  commit["depotFile%s" % fnum]
599             if not path.startswith(self.depotPath):
600     #            if not self.silent:
601     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
602                 fnum = fnum + 1
603                 continue
605             file = {}
606             file["path"] = path
607             file["rev"] = commit["rev%s" % fnum]
608             file["action"] = commit["action%s" % fnum]
609             file["type"] = commit["type%s" % fnum]
610             files.append(file)
611             fnum = fnum + 1
612         return files
614     def splitFilesIntoBranches(self, commit):
615         branches = {}
617         fnum = 0
618         while commit.has_key("depotFile%s" % fnum):
619             path =  commit["depotFile%s" % fnum]
620             if not path.startswith(self.depotPath):
621     #            if not self.silent:
622     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
623                 fnum = fnum + 1
624                 continue
626             file = {}
627             file["path"] = path
628             file["rev"] = commit["rev%s" % fnum]
629             file["action"] = commit["action%s" % fnum]
630             file["type"] = commit["type%s" % fnum]
631             fnum = fnum + 1
633             relPath = path[len(self.depotPath):]
635             for branch in self.knownBranches.keys():
636                 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
637                     if branch not in branches:
638                         branches[branch] = []
639                     branches[branch].append(file)
641         return branches
643     def commit(self, details, files, branch, branchPrefix, parent = ""):
644         epoch = details["time"]
645         author = details["user"]
647         if self.verbose:
648             print "commit into %s" % branch
650         self.gitStream.write("commit %s\n" % branch)
651     #    gitStream.write("mark :%s\n" % details["change"])
652         self.committedChanges.add(int(details["change"]))
653         committer = ""
654         if author not in self.users:
655             self.getUserMapFromPerforceServer()
656         if author in self.users:
657             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
658         else:
659             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
661         self.gitStream.write("committer %s\n" % committer)
663         self.gitStream.write("data <<EOT\n")
664         self.gitStream.write(details["desc"])
665         self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
666         self.gitStream.write("EOT\n\n")
668         if len(parent) > 0:
669             if self.verbose:
670                 print "parent %s" % parent
671             self.gitStream.write("from %s\n" % parent)
673         for file in files:
674             path = file["path"]
675             if not path.startswith(branchPrefix):
676     #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
677                 continue
678             rev = file["rev"]
679             depotPath = path + "#" + rev
680             relPath = path[len(branchPrefix):]
681             action = file["action"]
683             if file["type"] == "apple":
684                 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
685                 continue
687             if action == "delete":
688                 self.gitStream.write("D %s\n" % relPath)
689             else:
690                 mode = 644
691                 if file["type"].startswith("x"):
692                     mode = 755
694                 data = self.p4File(depotPath)
696                 if self.isWindows and file["type"].endswith("text"):
697                     data = data.replace("\r\n", "\n")
699                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
700                 self.gitStream.write("data %s\n" % len(data))
701                 self.gitStream.write(data)
702                 self.gitStream.write("\n")
704         self.gitStream.write("\n")
706         change = int(details["change"])
708         if self.labels.has_key(change):
709             label = self.labels[change]
710             labelDetails = label[0]
711             labelRevisions = label[1]
712             if self.verbose:
713                 print "Change %s is labelled %s" % (change, labelDetails)
715             files = p4CmdList("files %s...@%s" % (branchPrefix, change))
717             if len(files) == len(labelRevisions):
719                 cleanedFiles = {}
720                 for info in files:
721                     if info["action"] == "delete":
722                         continue
723                     cleanedFiles[info["depotFile"]] = info["rev"]
725                 if cleanedFiles == labelRevisions:
726                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
727                     self.gitStream.write("from %s\n" % branch)
729                     owner = labelDetails["Owner"]
730                     tagger = ""
731                     if author in self.users:
732                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
733                     else:
734                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
735                     self.gitStream.write("tagger %s\n" % tagger)
736                     self.gitStream.write("data <<EOT\n")
737                     self.gitStream.write(labelDetails["Description"])
738                     self.gitStream.write("EOT\n\n")
740                 else:
741                     if not self.silent:
742                         print ("Tag %s does not match with change %s: files do not match."
743                                % (labelDetails["label"], change))
745             else:
746                 if not self.silent:
747                     print ("Tag %s does not match with change %s: file count is different."
748                            % (labelDetails["label"], change))
750     def getUserMapFromPerforceServer(self):
751         if self.userMapFromPerforceServer:
752             return
753         self.users = {}
755         for output in p4CmdList("users"):
756             if not output.has_key("User"):
757                 continue
758             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
760         cache = open(gitdir + "/p4-usercache.txt", "wb")
761         for user in self.users.keys():
762             cache.write("%s\t%s\n" % (user, self.users[user]))
763         cache.close();
764         self.userMapFromPerforceServer = True
766     def loadUserMapFromCache(self):
767         self.users = {}
768         self.userMapFromPerforceServer = False
769         try:
770             cache = open(gitdir + "/p4-usercache.txt", "rb")
771             lines = cache.readlines()
772             cache.close()
773             for line in lines:
774                 entry = line[:-1].split("\t")
775                 self.users[entry[0]] = entry[1]
776         except IOError:
777             self.getUserMapFromPerforceServer()
779     def getLabels(self):
780         self.labels = {}
782         l = p4CmdList("labels %s..." % self.depotPath)
783         if len(l) > 0 and not self.silent:
784             print "Finding files belonging to labels in %s" % self.depotPath
786         for output in l:
787             label = output["label"]
788             revisions = {}
789             newestChange = 0
790             if self.verbose:
791                 print "Querying files for label %s" % label
792             for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
793                 revisions[file["depotFile"]] = file["rev"]
794                 change = int(file["change"])
795                 if change > newestChange:
796                     newestChange = change
798             self.labels[newestChange] = [output, revisions]
800         if self.verbose:
801             print "Label changes: %s" % self.labels.keys()
803     def getBranchMapping(self):
804         self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
806         for info in p4CmdList("branches"):
807             details = p4Cmd("branch -o %s" % info["branch"])
808             viewIdx = 0
809             while details.has_key("View%s" % viewIdx):
810                 paths = details["View%s" % viewIdx].split(" ")
811                 viewIdx = viewIdx + 1
812                 # require standard //depot/foo/... //depot/bar/... mapping
813                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
814                     continue
815                 source = paths[0]
816                 destination = paths[1]
817                 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
818                     source = source[len(self.depotPath):-4]
819                     destination = destination[len(self.depotPath):-4]
820                     if destination not in self.knownBranches:
821                         self.knownBranches[destination] = source
822                     if source not in self.knownBranches:
823                         self.knownBranches[source] = source
825     def listExistingP4GitBranches(self):
826         self.p4BranchesInGit = []
828         cmdline = "git rev-parse --symbolic "
829         if self.importIntoRemotes:
830             cmdline += " --remotes"
831         else:
832             cmdline += " --branches"
834         for line in read_pipe_lines(cmdline):
835             if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
836                 continue
837             if self.importIntoRemotes:
838                 # strip off p4
839                 branch = line[3:-1]
840             else:
841                 branch = line[:-1]
842             self.p4BranchesInGit.append(branch)
843             self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
845     def createOrUpdateBranchesFromOrigin(self):
846         if not self.silent:
847             print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
849         for line in mypopen("git rev-parse --symbolic --remotes"):
850             if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
851                 continue
853             headName = line[len("origin/"):-1]
854             remoteHead = self.refPrefix + headName
855             originHead = "origin/" + headName
857             [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead))
858             if len(originPreviousDepotPath) == 0 or len(originP4Change) == 0:
859                 continue
861             update = False
862             if not gitBranchExists(remoteHead):
863                 if self.verbose:
864                     print "creating %s" % remoteHead
865                 update = True
866             else:
867                 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead))
868                 if len(p4Change) > 0:
869                     if originPreviousDepotPath == p4PreviousDepotPath:
870                         originP4Change = int(originP4Change)
871                         p4Change = int(p4Change)
872                         if originP4Change > p4Change:
873                             print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead, originP4Change, remoteHead, p4Change)
874                             update = True
875                     else:
876                         print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead, originPreviousDepotPath, remoteHead, p4PreviousDepotPath)
878             if update:
879                 system("git update-ref %s %s" % (remoteHead, originHead))
881     def run(self, args):
882         self.depotPath = ""
883         self.changeRange = ""
884         self.initialParent = ""
885         self.previousDepotPath = ""
887         # map from branch depot path to parent branch
888         self.knownBranches = {}
889         self.initialParents = {}
890         self.hasOrigin = gitBranchExists("origin")
892         if self.importIntoRemotes:
893             self.refPrefix = "refs/remotes/p4/"
894         else:
895             self.refPrefix = "refs/heads/"
897         if self.syncWithOrigin and self.hasOrigin:
898             if not self.silent:
899                 print "Syncing with origin first by calling git fetch origin"
900             system("git fetch origin")
902         if len(self.branch) == 0:
903             self.branch = self.refPrefix + "master"
904             if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
905                 system("git update-ref %s refs/heads/p4" % self.branch)
906                 system("git branch -D p4");
907             # create it /after/ importing, when master exists
908             if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
909                 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
911         if len(args) == 0:
912             if self.hasOrigin:
913                 self.createOrUpdateBranchesFromOrigin()
914             self.listExistingP4GitBranches()
916             if len(self.p4BranchesInGit) > 1:
917                 if not self.silent:
918                     print "Importing from/into multiple branches"
919                 self.detectBranches = True
921             if self.verbose:
922                 print "branches: %s" % self.p4BranchesInGit
924             p4Change = 0
925             for branch in self.p4BranchesInGit:
926                 logMsg =  extractLogMessageFromGitCommit(self.refPrefix + branch)
927                 (depotPath, change) = extractDepotPathAndChangeFromGitLog(logMsg)
929                 if self.verbose:
930                     print "path %s change %s" % (depotPath, change)
932                 if len(depotPath) > 0 and len(change) > 0:
933                     change = int(change) + 1
934                     p4Change = max(p4Change, change)
936                     if len(self.previousDepotPath) == 0:
937                         self.previousDepotPath = depotPath
938                     else:
939                         i = 0
940                         l = min(len(self.previousDepotPath), len(depotPath))
941                         while i < l and self.previousDepotPath[i] == depotPath[i]:
942                             i = i + 1
943                         self.previousDepotPath = self.previousDepotPath[:i]
945             if p4Change > 0:
946                 self.depotPath = self.previousDepotPath
947                 self.changeRange = "@%s,#head" % p4Change
948                 self.initialParent = parseRevision(self.branch)
949                 if not self.silent and not self.detectBranches:
950                     print "Performing incremental import into %s git branch" % self.branch
952         if not self.branch.startswith("refs/"):
953             self.branch = "refs/heads/" + self.branch
955         if len(self.depotPath) != 0:
956             self.depotPath = self.depotPath[:-1]
958         if len(args) == 0 and len(self.depotPath) != 0:
959             if not self.silent:
960                 print "Depot path: %s" % self.depotPath
961         elif len(args) != 1:
962             return False
963         else:
964             if len(self.depotPath) != 0 and self.depotPath != args[0]:
965                 print ("previous import used depot path %s and now %s was specified. "
966                        "This doesn't work!" % (self.depotPath, args[0]))
967                 sys.exit(1)
968             self.depotPath = args[0]
970         self.revision = ""
971         self.users = {}
973         if self.depotPath.find("@") != -1:
974             atIdx = self.depotPath.index("@")
975             self.changeRange = self.depotPath[atIdx:]
976             if self.changeRange == "@all":
977                 self.changeRange = ""
978             elif self.changeRange.find(",") == -1:
979                 self.revision = self.changeRange
980                 self.changeRange = ""
981             self.depotPath = self.depotPath[0:atIdx]
982         elif self.depotPath.find("#") != -1:
983             hashIdx = self.depotPath.index("#")
984             self.revision = self.depotPath[hashIdx:]
985             self.depotPath = self.depotPath[0:hashIdx]
986         elif len(self.previousDepotPath) == 0:
987             self.revision = "#head"
989         self.depotPath = re.sub ("\.\.\.$", "", self.depotPath)
990         if not self.depotPath.endswith("/"):
991             self.depotPath += "/"
993         self.loadUserMapFromCache()
994         self.labels = {}
995         if self.detectLabels:
996             self.getLabels();
998         if self.detectBranches:
999             self.getBranchMapping();
1000             if self.verbose:
1001                 print "p4-git branches: %s" % self.p4BranchesInGit
1002                 print "initial parents: %s" % self.initialParents
1003             for b in self.p4BranchesInGit:
1004                 if b != "master":
1005                     b = b[len(self.projectName):]
1006                 self.createdBranches.add(b)
1008         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1010         importProcess = subprocess.Popen(["git", "fast-import"],
1011                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
1012         self.gitOutput = importProcess.stdout
1013         self.gitStream = importProcess.stdin
1014         self.gitError = importProcess.stderr
1016         if len(self.revision) > 0:
1017             print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
1019             details = { "user" : "git perforce import user", "time" : int(time.time()) }
1020             details["desc"] = ("Initial import of %s from the state at revision %s"
1021                                % (self.depotPath, self.revision))
1022             details["change"] = self.revision
1023             newestRevision = 0
1025             fileCnt = 0
1026             for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
1027                 change = int(info["change"])
1028                 if change > newestRevision:
1029                     newestRevision = change
1031                 if info["action"] == "delete":
1032                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1033                     #fileCnt = fileCnt + 1
1034                     continue
1036                 for prop in [ "depotFile", "rev", "action", "type" ]:
1037                     details["%s%s" % (prop, fileCnt)] = info[prop]
1039                 fileCnt = fileCnt + 1
1041             details["change"] = newestRevision
1043             try:
1044                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
1045             except IOError:
1046                 print "IO error with git fast-import. Is your git version recent enough?"
1047                 print self.gitError.read()
1049         else:
1050             changes = []
1052             if len(self.changesFile) > 0:
1053                 output = open(self.changesFile).readlines()
1054                 changeSet = Set()
1055                 for line in output:
1056                     changeSet.add(int(line))
1058                 for change in changeSet:
1059                     changes.append(change)
1061                 changes.sort()
1062             else:
1063                 if self.verbose:
1064                     print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
1065                 output = read_pipe_lines("p4 changes %s...%s" % (self.depotPath, self.changeRange))
1067                 for line in output:
1068                     changeNum = line.split(" ")[1]
1069                     changes.append(changeNum)
1071                 changes.reverse()
1073                 if len(self.maxChanges) > 0:
1074                     changes = changes[0:min(int(self.maxChanges), len(changes))]
1076             if len(changes) == 0:
1077                 if not self.silent:
1078                     print "No changes to import!"
1079                 return True
1081             self.updatedBranches = set()
1083             cnt = 1
1084             for change in changes:
1085                 description = p4Cmd("describe %s" % change)
1087                 if not self.silent:
1088                     sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1089                     sys.stdout.flush()
1090                 cnt = cnt + 1
1092                 try:
1093                     if self.detectBranches:
1094                         branches = self.splitFilesIntoBranches(description)
1095                         for branch in branches.keys():
1096                             branchPrefix = self.depotPath + branch + "/"
1098                             parent = ""
1100                             filesForCommit = branches[branch]
1102                             if self.verbose:
1103                                 print "branch is %s" % branch
1105                             self.updatedBranches.add(branch)
1107                             if branch not in self.createdBranches:
1108                                 self.createdBranches.add(branch)
1109                                 parent = self.knownBranches[branch]
1110                                 if parent == branch:
1111                                     parent = ""
1112                                 elif self.verbose:
1113                                     print "parent determined through known branches: %s" % parent
1115                             # main branch? use master
1116                             if branch == "main":
1117                                 branch = "master"
1118                             else:
1119                                 branch = self.projectName + branch
1121                             if parent == "main":
1122                                 parent = "master"
1123                             elif len(parent) > 0:
1124                                 parent = self.projectName + parent
1126                             branch = self.refPrefix + branch
1127                             if len(parent) > 0:
1128                                 parent = self.refPrefix + parent
1130                             if self.verbose:
1131                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1133                             if len(parent) == 0 and branch in self.initialParents:
1134                                 parent = self.initialParents[branch]
1135                                 del self.initialParents[branch]
1137                             self.commit(description, filesForCommit, branch, branchPrefix, parent)
1138                     else:
1139                         files = self.extractFilesFromCommit(description)
1140                         self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1141                         self.initialParent = ""
1142                 except IOError:
1143                     print self.gitError.read()
1144                     sys.exit(1)
1146             if not self.silent:
1147                 print ""
1148                 if len(self.updatedBranches) > 0:
1149                     sys.stdout.write("Updated branches: ")
1150                     for b in self.updatedBranches:
1151                         sys.stdout.write("%s " % b)
1152                     sys.stdout.write("\n")
1155         self.gitStream.close()
1156         if importProcess.wait() != 0:
1157             die("fast-import failed: %s" % self.gitError.read())
1158         self.gitOutput.close()
1159         self.gitError.close()
1161         return True
1163 class P4Rebase(Command):
1164     def __init__(self):
1165         Command.__init__(self)
1166         self.options = [ ]
1167         self.description = ("Fetches the latest revision from perforce and "
1168                             + "rebases the current work (branch) against it")
1170     def run(self, args):
1171         sync = P4Sync()
1172         sync.run([])
1173         print "Rebasing the current branch"
1174         oldHead = read_pipe("git rev-parse HEAD")[:-1]
1175         system("git rebase p4")
1176         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1177         return True
1179 class P4Clone(P4Sync):
1180     def __init__(self):
1181         P4Sync.__init__(self)
1182         self.description = "Creates a new git repository and imports from Perforce into it"
1183         self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1184         self.needsGit = False
1186     def run(self, args):
1187         global gitdir
1189         if len(args) < 1:
1190             return False
1191         depotPath = args[0]
1192         destination = ""
1193         if len(args) == 2:
1194             destination = args[1]
1195         elif len(args) > 2:
1196             return False
1198         if not depotPath.startswith("//"):
1199             return False
1201         depotDir = re.sub("(@[^@]*)$", "", depotPath)
1202         depotDir = re.sub("(#[^#]*)$", "", depotDir)
1203         depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1204         depotDir = re.sub(r"/$", "", depotDir)
1206         if not destination:
1207             destination = os.path.split(depotDir)[-1]
1209         print "Importing from %s into %s" % (depotPath, destination)
1210         os.makedirs(destination)
1211         os.chdir(destination)
1212         system("git init")
1213         gitdir = os.getcwd() + "/.git"
1214         if not P4Sync.run(self, [depotPath]):
1215             return False
1216         if self.branch != "master":
1217             if gitBranchExists("refs/remotes/p4/master"):
1218                 system("git branch master refs/remotes/p4/master")
1219                 system("git checkout -f")
1220             else:
1221                 print "Could not detect main branch. No checkout/master branch created."
1222         return True
1224 class HelpFormatter(optparse.IndentedHelpFormatter):
1225     def __init__(self):
1226         optparse.IndentedHelpFormatter.__init__(self)
1228     def format_description(self, description):
1229         if description:
1230             return description + "\n"
1231         else:
1232             return ""
1234 def printUsage(commands):
1235     print "usage: %s <command> [options]" % sys.argv[0]
1236     print ""
1237     print "valid commands: %s" % ", ".join(commands)
1238     print ""
1239     print "Try %s <command> --help for command specific help." % sys.argv[0]
1240     print ""
1242 commands = {
1243     "debug" : P4Debug(),
1244     "submit" : P4Submit(),
1245     "sync" : P4Sync(),
1246     "rebase" : P4Rebase(),
1247     "clone" : P4Clone(),
1248     "rollback" : P4RollBack()
1251 if len(sys.argv[1:]) == 0:
1252     printUsage(commands.keys())
1253     sys.exit(2)
1255 cmd = ""
1256 cmdName = sys.argv[1]
1257 try:
1258     cmd = commands[cmdName]
1259 except KeyError:
1260     print "unknown command %s" % cmdName
1261     print ""
1262     printUsage(commands.keys())
1263     sys.exit(2)
1265 options = cmd.options
1266 cmd.gitdir = gitdir
1268 args = sys.argv[2:]
1270 if len(options) > 0:
1271     options.append(optparse.make_option("--git-dir", dest="gitdir"))
1273     parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1274                                    options,
1275                                    description = cmd.description,
1276                                    formatter = HelpFormatter())
1278     (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1280 if cmd.needsGit:
1281     gitdir = cmd.gitdir
1282     if len(gitdir) == 0:
1283         gitdir = ".git"
1284         if not isValidGitDir(gitdir):
1285             gitdir = read_pipe("git rev-parse --git-dir")[:-1]
1286             if os.path.exists(gitdir):
1287                 cdup = read_pipe("git rev-parse --show-cdup")[:-1];
1288                 if len(cdup) > 0:
1289                     os.chdir(cdup);
1291     if not isValidGitDir(gitdir):
1292         if isValidGitDir(gitdir + "/.git"):
1293             gitdir += "/.git"
1294         else:
1295             die("fatal: cannot locate git repository at %s" % gitdir)
1297     os.environ["GIT_DIR"] = gitdir
1299 if not cmd.run(args):
1300     parser.print_help()