Code

8b00e350ec277f1f8fe78430f7234f5e45cd8af5
[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
15 from sets import Set;
17 verbose = False
19 def die(msg):
20     if verbose:
21         raise Exception(msg)
22     else:
23         sys.stderr.write(msg + "\n")
24         sys.exit(1)
26 def write_pipe(c, str):
27     if verbose:
28         sys.stderr.write('Writing pipe: %s\n' % c)
30     pipe = os.popen(c, 'w')
31     val = pipe.write(str)
32     if pipe.close():
33         die('Command failed: %s' % c)
35     return val
37 def read_pipe(c, ignore_error=False):
38     if verbose:
39         sys.stderr.write('Reading pipe: %s\n' % c)
41     pipe = os.popen(c, 'rb')
42     val = pipe.read()
43     if pipe.close() and not ignore_error:
44         die('Command failed: %s' % c)
46     return val
49 def read_pipe_lines(c):
50     if verbose:
51         sys.stderr.write('Reading pipe: %s\n' % c)
52     ## todo: check return status
53     pipe = os.popen(c, 'rb')
54     val = pipe.readlines()
55     if pipe.close():
56         die('Command failed: %s' % c)
58     return val
60 def system(cmd):
61     if verbose:
62         sys.stderr.write("executing %s\n" % cmd)
63     if os.system(cmd) != 0:
64         die("command failed: %s" % cmd)
66 def p4CmdList(cmd):
67     cmd = "p4 -G %s" % cmd
68     if verbose:
69         sys.stderr.write("Opening pipe: %s\n" % cmd)
70     pipe = os.popen(cmd, "rb")
72     result = []
73     try:
74         while True:
75             entry = marshal.load(pipe)
76             result.append(entry)
77     except EOFError:
78         pass
79     exitCode = pipe.close()
80     if exitCode != None:
81         entry = {}
82         entry["p4ExitCode"] = exitCode
83         result.append(entry)
85     return result
87 def p4Cmd(cmd):
88     list = p4CmdList(cmd)
89     result = {}
90     for entry in list:
91         result.update(entry)
92     return result;
94 def p4Where(depotPath):
95     if not depotPath.endswith("/"):
96         depotPath += "/"
97     output = p4Cmd("where %s..." % depotPath)
98     if output["code"] == "error":
99         return ""
100     clientPath = ""
101     if "path" in output:
102         clientPath = output.get("path")
103     elif "data" in output:
104         data = output.get("data")
105         lastSpace = data.rfind(" ")
106         clientPath = data[lastSpace + 1:]
108     if clientPath.endswith("..."):
109         clientPath = clientPath[:-3]
110     return clientPath
112 def currentGitBranch():
113     return read_pipe("git name-rev HEAD").split(" ")[1].strip()
115 def isValidGitDir(path):
116     if (os.path.exists(path + "/HEAD")
117         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).strip()
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 extractSettingsGitLog(log):
139     values = {}
140     for line in log.split("\n"):
141         line = line.strip()
142         m = re.search (r"^ *\[git-p4: (.*)\]$", line)
143         if not m:
144             continue
146         assignments = m.group(1).split (':')
147         for a in assignments:
148             vals = a.split ('=')
149             key = vals[0].strip()
150             val = ('='.join (vals[1:])).strip()
151             if val.endswith ('\"') and val.startswith('"'):
152                 val = val[1:-1]
154             values[key] = val
156     paths = values.get("depot-paths")
157     if not paths:
158         paths = values.get("depot-path")
159     values['depot-paths'] = paths.split(',')
160     return values
162 def gitBranchExists(branch):
163     proc = subprocess.Popen(["git", "rev-parse", branch],
164                             stderr=subprocess.PIPE, stdout=subprocess.PIPE);
165     return proc.wait() == 0;
167 def gitConfig(key):
168     return read_pipe("git config %s" % key, ignore_error=True).strip()
170 class Command:
171     def __init__(self):
172         self.usage = "usage: %prog [options]"
173         self.needsGit = True
175 class P4Debug(Command):
176     def __init__(self):
177         Command.__init__(self)
178         self.options = [
179             optparse.make_option("--verbose", dest="verbose", action="store_true",
180                                  default=False),
181             ]
182         self.description = "A tool to debug the output of p4 -G."
183         self.needsGit = False
184         self.verbose = False
186     def run(self, args):
187         j = 0
188         for output in p4CmdList(" ".join(args)):
189             print 'Element: %d' % j
190             j += 1
191             print output
192         return True
194 class P4RollBack(Command):
195     def __init__(self):
196         Command.__init__(self)
197         self.options = [
198             optparse.make_option("--verbose", dest="verbose", action="store_true"),
199             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
200         ]
201         self.description = "A tool to debug the multi-branch import. Don't use :)"
202         self.verbose = False
203         self.rollbackLocalBranches = False
205     def run(self, args):
206         if len(args) != 1:
207             return False
208         maxChange = int(args[0])
210         if "p4ExitCode" in p4Cmd("changes -m 1"):
211             die("Problems executing p4");
213         if self.rollbackLocalBranches:
214             refPrefix = "refs/heads/"
215             lines = read_pipe_lines("git rev-parse --symbolic --branches")
216         else:
217             refPrefix = "refs/remotes/"
218             lines = read_pipe_lines("git rev-parse --symbolic --remotes")
220         for line in lines:
221             if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
222                 line = line.strip()
223                 ref = refPrefix + line
224                 log = extractLogMessageFromGitCommit(ref)
225                 settings = extractSettingsGitLog(log)
227                 depotPaths = settings['depot-paths']
228                 change = settings['change']
230                 changed = False
232                 if len(p4Cmd("changes -m 1 "  + ' '.join (['%s...@%s' % (p, maxChange)
233                                                            for p in depotPaths]))) == 0:
234                     print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
235                     system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
236                     continue
238                 while change and int(change) > maxChange:
239                     changed = True
240                     if self.verbose:
241                         print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
242                     system("git update-ref %s \"%s^\"" % (ref, ref))
243                     log = extractLogMessageFromGitCommit(ref)
244                     settings =  extractSettingsGitLog(log)
247                     depotPaths = settings['depot-paths']
248                     change = settings['change']
250                 if changed:
251                     print "%s rewound to %s" % (ref, change)
253         return True
255 class P4Submit(Command):
256     def __init__(self):
257         Command.__init__(self)
258         self.options = [
259                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
260                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
261                 optparse.make_option("--origin", dest="origin"),
262                 optparse.make_option("--reset", action="store_true", dest="reset"),
263                 optparse.make_option("--log-substitutions", dest="substFile"),
264                 optparse.make_option("--dry-run", action="store_true"),
265                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
266                 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
267         ]
268         self.description = "Submit changes from git to the perforce depot."
269         self.usage += " [name of git branch to submit into perforce depot]"
270         self.firstTime = True
271         self.reset = False
272         self.interactive = True
273         self.dryRun = False
274         self.substFile = ""
275         self.firstTime = True
276         self.origin = ""
277         self.directSubmit = False
278         self.trustMeLikeAFool = False
279         self.verbose = False
281         self.logSubstitutions = {}
282         self.logSubstitutions["<enter description here>"] = "%log%"
283         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
285     def check(self):
286         if len(p4CmdList("opened ...")) > 0:
287             die("You have files opened with perforce! Close them before starting the sync.")
289     def start(self):
290         if len(self.config) > 0 and not self.reset:
291             die("Cannot start sync. Previous sync config found at %s\n"
292                 "If you want to start submitting again from scratch "
293                 "maybe you want to call git-p4 submit --reset" % self.configFile)
295         commits = []
296         if self.directSubmit:
297             commits.append("0")
298         else:
299             for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
300                 commits.append(line.strip())
301             commits.reverse()
303         self.config["commits"] = commits
305     def prepareLogMessage(self, template, message):
306         result = ""
308         for line in template.split("\n"):
309             if line.startswith("#"):
310                 result += line + "\n"
311                 continue
313             substituted = False
314             for key in self.logSubstitutions.keys():
315                 if line.find(key) != -1:
316                     value = self.logSubstitutions[key]
317                     value = value.replace("%log%", message)
318                     if value != "@remove@":
319                         result += line.replace(key, value) + "\n"
320                     substituted = True
321                     break
323             if not substituted:
324                 result += line + "\n"
326         return result
328     def applyCommit(self, id):
329         if self.directSubmit:
330             print "Applying local change in working directory/index"
331             diff = self.diffStatus
332         else:
333             print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
334             diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
335         filesToAdd = set()
336         filesToDelete = set()
337         editedFiles = set()
338         for line in diff:
339             modifier = line[0]
340             path = line[1:].strip()
341             if modifier == "M":
342                 system("p4 edit \"%s\"" % path)
343                 editedFiles.add(path)
344             elif modifier == "A":
345                 filesToAdd.add(path)
346                 if path in filesToDelete:
347                     filesToDelete.remove(path)
348             elif modifier == "D":
349                 filesToDelete.add(path)
350                 if path in filesToAdd:
351                     filesToAdd.remove(path)
352             else:
353                 die("unknown modifier %s for %s" % (modifier, path))
355         if self.directSubmit:
356             diffcmd = "cat \"%s\"" % self.diffFile
357         else:
358             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
359         patchcmd = diffcmd + " | git apply "
360         tryPatchCmd = patchcmd + "--check -"
361         applyPatchCmd = patchcmd + "--check --apply -"
363         if os.system(tryPatchCmd) != 0:
364             print "Unfortunately applying the change failed!"
365             print "What do you want to do?"
366             response = "x"
367             while response != "s" and response != "a" and response != "w":
368                 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
369                                      "and with .rej files / [w]rite the patch to a file (patch.txt) ")
370             if response == "s":
371                 print "Skipping! Good luck with the next patches..."
372                 return
373             elif response == "a":
374                 os.system(applyPatchCmd)
375                 if len(filesToAdd) > 0:
376                     print "You may also want to call p4 add on the following files:"
377                     print " ".join(filesToAdd)
378                 if len(filesToDelete):
379                     print "The following files should be scheduled for deletion with p4 delete:"
380                     print " ".join(filesToDelete)
381                 die("Please resolve and submit the conflict manually and "
382                     + "continue afterwards with git-p4 submit --continue")
383             elif response == "w":
384                 system(diffcmd + " > patch.txt")
385                 print "Patch saved to patch.txt in %s !" % self.clientPath
386                 die("Please resolve and submit the conflict manually and "
387                     "continue afterwards with git-p4 submit --continue")
389         system(applyPatchCmd)
391         for f in filesToAdd:
392             system("p4 add %s" % f)
393         for f in filesToDelete:
394             system("p4 revert %s" % f)
395             system("p4 delete %s" % f)
397         logMessage = ""
398         if not self.directSubmit:
399             logMessage = extractLogMessageFromGitCommit(id)
400             logMessage = logMessage.replace("\n", "\n\t")
401             logMessage = logMessage.strip()
403         template = read_pipe("p4 change -o")
405         if self.interactive:
406             submitTemplate = self.prepareLogMessage(template, logMessage)
407             diff = read_pipe("p4 diff -du ...")
409             for newFile in filesToAdd:
410                 diff += "==== new file ====\n"
411                 diff += "--- /dev/null\n"
412                 diff += "+++ %s\n" % newFile
413                 f = open(newFile, "r")
414                 for line in f.readlines():
415                     diff += "+" + line
416                 f.close()
418             separatorLine = "######## everything below this line is just the diff #######"
419             if platform.system() == "Windows":
420                 separatorLine += "\r"
421             separatorLine += "\n"
423             response = "e"
424             if self.trustMeLikeAFool:
425                 response = "y"
427             firstIteration = True
428             while response == "e":
429                 if not firstIteration:
430                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
431                 firstIteration = False
432                 if response == "e":
433                     [handle, fileName] = tempfile.mkstemp()
434                     tmpFile = os.fdopen(handle, "w+")
435                     tmpFile.write(submitTemplate + separatorLine + diff)
436                     tmpFile.close()
437                     defaultEditor = "vi"
438                     if platform.system() == "Windows":
439                         defaultEditor = "notepad"
440                     editor = os.environ.get("EDITOR", defaultEditor);
441                     system(editor + " " + fileName)
442                     tmpFile = open(fileName, "rb")
443                     message = tmpFile.read()
444                     tmpFile.close()
445                     os.remove(fileName)
446                     submitTemplate = message[:message.index(separatorLine)]
448             if response == "y" or response == "yes":
449                if self.dryRun:
450                    print submitTemplate
451                    raw_input("Press return to continue...")
452                else:
453                    if self.directSubmit:
454                        print "Submitting to git first"
455                        os.chdir(self.oldWorkingDirectory)
456                        write_pipe("git commit -a -F -", submitTemplate)
457                        os.chdir(self.clientPath)
459                    write_pipe("p4 submit -i", submitTemplate)
460             elif response == "s":
461                 for f in editedFiles:
462                     system("p4 revert \"%s\"" % f);
463                 for f in filesToAdd:
464                     system("p4 revert \"%s\"" % f);
465                     system("rm %s" %f)
466                 for f in filesToDelete:
467                     system("p4 delete \"%s\"" % f);
468                 return
469             else:
470                 print "Not submitting!"
471                 self.interactive = False
472         else:
473             fileName = "submit.txt"
474             file = open(fileName, "w+")
475             file.write(self.prepareLogMessage(template, logMessage))
476             file.close()
477             print ("Perforce submit template written as %s. "
478                    + "Please review/edit and then use p4 submit -i < %s to submit directly!"
479                    % (fileName, fileName))
481     def run(self, args):
482         if len(args) == 0:
483             self.master = currentGitBranch()
484             if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
485                 die("Detecting current git branch failed!")
486         elif len(args) == 1:
487             self.master = args[0]
488         else:
489             return False
491         depotPath = ""
492         settings = None
493         if gitBranchExists("p4"):
494             settings = extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
495         if len(depotPath) == 0 and gitBranchExists("origin"):
496             settings = extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
497         depotPath = settings['depot-paths'][0]
499         if len(depotPath) == 0:
500             print "Internal error: cannot locate perforce depot path from existing branches"
501             sys.exit(128)
503         self.clientPath = p4Where(depotPath)
505         if len(self.clientPath) == 0:
506             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
507             sys.exit(128)
509         print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
510         self.oldWorkingDirectory = os.getcwd()
512         if self.directSubmit:
513             self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
514             if len(self.diffStatus) == 0:
515                 print "No changes in working directory to submit."
516                 return True
517             patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
518             self.diffFile = self.gitdir + "/p4-git-diff"
519             f = open(self.diffFile, "wb")
520             f.write(patch)
521             f.close();
523         os.chdir(self.clientPath)
524         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
525         if response == "y" or response == "yes":
526             system("p4 sync ...")
528         if len(self.origin) == 0:
529             if gitBranchExists("p4"):
530                 self.origin = "p4"
531             else:
532                 self.origin = "origin"
534         if self.reset:
535             self.firstTime = True
537         if len(self.substFile) > 0:
538             for line in open(self.substFile, "r").readlines():
539                 tokens = line.strip().split("=")
540                 self.logSubstitutions[tokens[0]] = tokens[1]
542         self.check()
543         self.configFile = self.gitdir + "/p4-git-sync.cfg"
544         self.config = shelve.open(self.configFile, writeback=True)
546         if self.firstTime:
547             self.start()
549         commits = self.config.get("commits", [])
551         while len(commits) > 0:
552             self.firstTime = False
553             commit = commits[0]
554             commits = commits[1:]
555             self.config["commits"] = commits
556             self.applyCommit(commit)
557             if not self.interactive:
558                 break
560         self.config.close()
562         if self.directSubmit:
563             os.remove(self.diffFile)
565         if len(commits) == 0:
566             if self.firstTime:
567                 print "No changes found to apply between %s and current HEAD" % self.origin
568             else:
569                 print "All changes applied!"
570                 os.chdir(self.oldWorkingDirectory)
571                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
572                 if response == "y" or response == "yes":
573                     rebase = P4Rebase()
574                     rebase.run([])
575             os.remove(self.configFile)
577         return True
579 class P4Sync(Command):
580     def __init__(self):
581         Command.__init__(self)
582         self.options = [
583                 optparse.make_option("--branch", dest="branch"),
584                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
585                 optparse.make_option("--changesfile", dest="changesFile"),
586                 optparse.make_option("--silent", dest="silent", action="store_true"),
587                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
588                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
589                 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
590                                      help="Import into refs/heads/ , not refs/remotes"),
591                 optparse.make_option("--max-changes", dest="maxChanges"),
592                 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
593                                      help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
594         ]
595         self.description = """Imports from Perforce into a git repository.\n
596     example:
597     //depot/my/project/ -- to import the current head
598     //depot/my/project/@all -- to import everything
599     //depot/my/project/@1,6 -- to import only from revision 1 to 6
601     (a ... is not needed in the path p4 specification, it's added implicitly)"""
603         self.usage += " //depot/path[@revRange]"
604         self.silent = False
605         self.createdBranches = Set()
606         self.committedChanges = Set()
607         self.branch = ""
608         self.detectBranches = False
609         self.detectLabels = False
610         self.changesFile = ""
611         self.syncWithOrigin = True
612         self.verbose = False
613         self.importIntoRemotes = True
614         self.maxChanges = ""
615         self.isWindows = (platform.system() == "Windows")
616         self.keepRepoPath = False
617         self.depotPaths = None
619         if gitConfig("git-p4.syncFromOrigin") == "false":
620             self.syncWithOrigin = False
622     def extractFilesFromCommit(self, commit):
623         files = []
624         fnum = 0
625         while commit.has_key("depotFile%s" % fnum):
626             path =  commit["depotFile%s" % fnum]
628             found = [p for p in self.depotPaths
629                      if path.startswith (p)]
630             if not found:
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             files.append(file)
640             fnum = fnum + 1
641         return files
643     def stripRepoPath(self, path, prefixes):
644         if self.keepRepoPath:
645             prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
647         for p in prefixes:
648             if path.startswith(p):
649                 path = path[len(p):]
651         return path
653     def splitFilesIntoBranches(self, commit):
654         branches = {}
655         fnum = 0
656         while commit.has_key("depotFile%s" % fnum):
657             path =  commit["depotFile%s" % fnum]
658             found = [p for p in self.depotPaths
659                      if path.startswith (p)]
660             if not found:
661                 fnum = fnum + 1
662                 continue
664             file = {}
665             file["path"] = path
666             file["rev"] = commit["rev%s" % fnum]
667             file["action"] = commit["action%s" % fnum]
668             file["type"] = commit["type%s" % fnum]
669             fnum = fnum + 1
671             relPath = self.stripRepoPath(path, self.depotPaths)
673             for branch in self.knownBranches.keys():
675                 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
676                 if relPath.startswith(branch + "/"):
677                     if branch not in branches:
678                         branches[branch] = []
679                     branches[branch].append(file)
681         return branches
683     ## Should move this out, doesn't use SELF.
684     def readP4Files(self, files):
685         files = [f for f in files
686                  if f['action'] != 'delete']
688         if not files:
689             return
691         filedata = p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f['path'],
692                                                                  f['rev'])
693                                                     for f in files]))
695         j = 0;
696         contents = {}
697         while j < len(filedata):
698             stat = filedata[j]
699             j += 1
700             text = ''
701             while j < len(filedata) and filedata[j]['code'] in ('text',
702                                                                 'binary'):
703                 text += filedata[j]['data']
704                 j += 1
706             contents[stat['depotFile']] = text
708         for f in files:
709             assert not f.has_key('data')
710             f['data'] = contents[f['path']]
712     def commit(self, details, files, branch, branchPrefixes, parent = ""):
713         epoch = details["time"]
714         author = details["user"]
716         if self.verbose:
717             print "commit into %s" % branch
719         # start with reading files; if that fails, we should not
720         # create a commit.
721         new_files = []
722         for f in files:
723             if [p for p in branchPrefixes if f['path'].startswith(p)]:
724                 new_files.append (f)
725             else:
726                 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
727         files = new_files
728         self.readP4Files(files)
733         self.gitStream.write("commit %s\n" % branch)
734 #        gitStream.write("mark :%s\n" % details["change"])
735         self.committedChanges.add(int(details["change"]))
736         committer = ""
737         if author not in self.users:
738             self.getUserMapFromPerforceServer()
739         if author in self.users:
740             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
741         else:
742             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
744         self.gitStream.write("committer %s\n" % committer)
746         self.gitStream.write("data <<EOT\n")
747         self.gitStream.write(details["desc"])
748         self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
749                              "options = %s]\n"
750                              % (','.join (branchPrefixes), details["change"],
751                                 details['options']
752                                 ))
753         self.gitStream.write("EOT\n\n")
755         if len(parent) > 0:
756             if self.verbose:
757                 print "parent %s" % parent
758             self.gitStream.write("from %s\n" % parent)
760         for file in files:
761             if file["type"] == "apple":
762                 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
763                 continue
765             relPath = self.stripRepoPath(file['path'], branchPrefixes)
766             if file["action"] == "delete":
767                 self.gitStream.write("D %s\n" % relPath)
768             else:
769                 mode = 644
770                 if file["type"].startswith("x"):
771                     mode = 755
773                 data = file['data']
775                 if self.isWindows and file["type"].endswith("text"):
776                     data = data.replace("\r\n", "\n")
778                 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
779                 self.gitStream.write("data %s\n" % len(data))
780                 self.gitStream.write(data)
781                 self.gitStream.write("\n")
783         self.gitStream.write("\n")
785         change = int(details["change"])
787         if self.labels.has_key(change):
788             label = self.labels[change]
789             labelDetails = label[0]
790             labelRevisions = label[1]
791             if self.verbose:
792                 print "Change %s is labelled %s" % (change, labelDetails)
794             files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
795                                                     for p in branchPrefixes]))
797             if len(files) == len(labelRevisions):
799                 cleanedFiles = {}
800                 for info in files:
801                     if info["action"] == "delete":
802                         continue
803                     cleanedFiles[info["depotFile"]] = info["rev"]
805                 if cleanedFiles == labelRevisions:
806                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
807                     self.gitStream.write("from %s\n" % branch)
809                     owner = labelDetails["Owner"]
810                     tagger = ""
811                     if author in self.users:
812                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
813                     else:
814                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
815                     self.gitStream.write("tagger %s\n" % tagger)
816                     self.gitStream.write("data <<EOT\n")
817                     self.gitStream.write(labelDetails["Description"])
818                     self.gitStream.write("EOT\n\n")
820                 else:
821                     if not self.silent:
822                         print ("Tag %s does not match with change %s: files do not match."
823                                % (labelDetails["label"], change))
825             else:
826                 if not self.silent:
827                     print ("Tag %s does not match with change %s: file count is different."
828                            % (labelDetails["label"], change))
830     def getUserCacheFilename(self):
831         return os.environ["HOME"] + "/.gitp4-usercache.txt"
833     def getUserMapFromPerforceServer(self):
834         if self.userMapFromPerforceServer:
835             return
836         self.users = {}
838         for output in p4CmdList("users"):
839             if not output.has_key("User"):
840                 continue
841             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
844         s = ''
845         for (key, val) in self.users.items():
846             s += "%s\t%s\n" % (key, val)
848         open(self.getUserCacheFilename(), "wb").write(s)
849         self.userMapFromPerforceServer = True
851     def loadUserMapFromCache(self):
852         self.users = {}
853         self.userMapFromPerforceServer = False
854         try:
855             cache = open(self.getUserCacheFilename(), "rb")
856             lines = cache.readlines()
857             cache.close()
858             for line in lines:
859                 entry = line.strip().split("\t")
860                 self.users[entry[0]] = entry[1]
861         except IOError:
862             self.getUserMapFromPerforceServer()
864     def getLabels(self):
865         self.labels = {}
867         l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
868         if len(l) > 0 and not self.silent:
869             print "Finding files belonging to labels in %s" % `self.depotPath`
871         for output in l:
872             label = output["label"]
873             revisions = {}
874             newestChange = 0
875             if self.verbose:
876                 print "Querying files for label %s" % label
877             for file in p4CmdList("files "
878                                   +  ' '.join (["%s...@%s" % (p, label)
879                                                 for p in self.depotPaths])):
880                 revisions[file["depotFile"]] = file["rev"]
881                 change = int(file["change"])
882                 if change > newestChange:
883                     newestChange = change
885             self.labels[newestChange] = [output, revisions]
887         if self.verbose:
888             print "Label changes: %s" % self.labels.keys()
890     def guessProjectName(self):
891         for p in self.depotPaths:
892             return p [p.strip().rfind("/") + 1:]
894     def getBranchMapping(self):
896         ## FIXME - what's a P4 projectName ?
897         self.projectName = self.guessProjectName()
899         for info in p4CmdList("branches"):
900             details = p4Cmd("branch -o %s" % info["branch"])
901             viewIdx = 0
902             while details.has_key("View%s" % viewIdx):
903                 paths = details["View%s" % viewIdx].split(" ")
904                 viewIdx = viewIdx + 1
905                 # require standard //depot/foo/... //depot/bar/... mapping
906                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
907                     continue
908                 source = paths[0]
909                 destination = paths[1]
910                 ## HACK
911                 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
912                     source = source[len(self.depotPaths[0]):-4]
913                     destination = destination[len(self.depotPaths[0]):-4]
914                     if destination not in self.knownBranches:
915                         self.knownBranches[destination] = source
916                     if source not in self.knownBranches:
917                         self.knownBranches[source] = source
919     def listExistingP4GitBranches(self):
920         self.p4BranchesInGit = []
922         cmdline = "git rev-parse --symbolic "
923         if self.importIntoRemotes:
924             cmdline += " --remotes"
925         else:
926             cmdline += " --branches"
928         for line in read_pipe_lines(cmdline):
929             line = line.strip()
931             ## only import to p4/
932             if not line.startswith('p4/'):
933                 continue
934             branch = line
935             if self.importIntoRemotes:
936                 # strip off p4
937                 branch = re.sub ("^p4/", "", line)
939             self.p4BranchesInGit.append(branch)
940             self.initialParents[self.refPrefix + branch] = parseRevision(line)
942     def createOrUpdateBranchesFromOrigin(self):
943         if not self.silent:
944             print ("Creating/updating branch(es) in %s based on origin branch(es)"
945                    % self.refPrefix)
947         for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
948             line = line.strip()
949             if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
950                 continue
952             headName = line[len("origin/"):]
953             remoteHead = self.refPrefix + headName
954             originHead = "origin/" + headName
956             original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
957             if (not original.has_key('depot-paths')
958                 or not original.has_key('change')):
959                 continue
961             update = False
962             if not gitBranchExists(remoteHead):
963                 if self.verbose:
964                     print "creating %s" % remoteHead
965                 update = True
966             else:
967                 settings =  extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
968                 if settings.has_key('change') > 0:
969                     if settings['depot-paths'] == original['depot-paths']:
970                         originP4Change = int(original['change'])
971                         p4Change = int(settings['change'])
972                         if originP4Change > p4Change:
973                             print ("%s (%s) is newer than %s (%s). "
974                                    "Updating p4 branch from origin."
975                                    % (originHead, originP4Change,
976                                       remoteHead, p4Change))
977                             update = True
978                     else:
979                         print ("Ignoring: %s was imported from %s while "
980                                "%s was imported from %s"
981                                % (originHead, ','.join(original['depot-paths']),
982                                   remoteHead, ','.join(settings['depot-paths'])))
984             if update:
985                 system("git update-ref %s %s" % (remoteHead, originHead))
987     def updateOptionDict(self, d):
988         option_keys = {}
989         if self.keepRepoPath:
990             option_keys['keepRepoPath'] = 1
992         d["options"] = ' '.join(sorted(option_keys.keys()))
994     def readOptions(self, d):
995         self.keepRepoPath = (d.has_key('options')
996                              and ('keepRepoPath' in d['options']))
998     def run(self, args):
999         self.depotPaths = []
1000         self.changeRange = ""
1001         self.initialParent = ""
1002         self.previousDepotPaths = []
1004         # map from branch depot path to parent branch
1005         self.knownBranches = {}
1006         self.initialParents = {}
1007         self.hasOrigin = gitBranchExists("origin")
1009         if self.importIntoRemotes:
1010             self.refPrefix = "refs/remotes/p4/"
1011         else:
1012             self.refPrefix = "refs/heads/"
1014         if self.syncWithOrigin and self.hasOrigin:
1015             if not self.silent:
1016                 print "Syncing with origin first by calling git fetch origin"
1017             system("git fetch origin")
1019         if len(self.branch) == 0:
1020             self.branch = self.refPrefix + "p4/master"
1021             if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1022                 system("git update-ref %s refs/heads/p4" % self.branch)
1023                 system("git branch -D p4");
1024             # create it /after/ importing, when master exists
1025             if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1026                 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1028         # TODO: should always look at previous commits,
1029         # merge with previous imports, if possible.
1030         if args == []:
1031             if self.hasOrigin:
1032                 self.createOrUpdateBranchesFromOrigin()
1033             self.listExistingP4GitBranches()
1035             if len(self.p4BranchesInGit) > 1:
1036                 if not self.silent:
1037                     print "Importing from/into multiple branches"
1038                 self.detectBranches = True
1040             if self.verbose:
1041                 print "branches: %s" % self.p4BranchesInGit
1043             p4Change = 0
1044             for branch in self.p4BranchesInGit:
1045                 logMsg =  extractLogMessageFromGitCommit(self.refPrefix + branch)
1047                 settings = extractSettingsGitLog(logMsg)
1049                 self.readOptions(settings)
1050                 if (settings.has_key('depot-paths')
1051                     and settings.has_key ('change')):
1052                     change = int(settings['change']) + 1
1053                     p4Change = max(p4Change, change)
1055                     depotPaths = sorted(settings['depot-paths'])
1056                     if self.previousDepotPaths == []:
1057                         self.previousDepotPaths = depotPaths
1058                     else:
1059                         paths = []
1060                         for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1061                             for i in range(0, min(len(cur), len(prev))):
1062                                 if cur[i] <> prev[i]:
1063                                     i = i - 1
1064                                     break
1066                             paths.append (cur[:i + 1])
1068                         self.previousDepotPaths = paths
1070             if p4Change > 0:
1071                 self.depotPaths = sorted(self.previousDepotPaths)
1072                 self.changeRange = "@%s,#head" % p4Change
1073                 if not self.detectBranches:
1074                     self.initialParent = parseRevision(self.branch)
1075                 if not self.silent and not self.detectBranches:
1076                     print "Performing incremental import into %s git branch" % self.branch
1078         if not self.branch.startswith("refs/"):
1079             self.branch = "refs/heads/" + self.branch
1081         if len(args) == 0 and self.depotPaths:
1082             if not self.silent:
1083                 print "Depot paths: %s" % ' '.join(self.depotPaths)
1084         else:
1085             if self.depotPaths and self.depotPaths != args:
1086                 print ("previous import used depot path %s and now %s was specified. "
1087                        "This doesn't work!" % (' '.join (self.depotPaths),
1088                                                ' '.join (args)))
1089                 sys.exit(1)
1091             self.depotPaths = sorted(args)
1093         self.revision = ""
1094         self.users = {}
1096         newPaths = []
1097         for p in self.depotPaths:
1098             if p.find("@") != -1:
1099                 atIdx = p.index("@")
1100                 self.changeRange = p[atIdx:]
1101                 if self.changeRange == "@all":
1102                     self.changeRange = ""
1103                 elif ',' not in self.changeRange:
1104                     self.revision = self.changeRange
1105                     self.changeRange = ""
1106                 p = p[0:atIdx]
1107             elif p.find("#") != -1:
1108                 hashIdx = p.index("#")
1109                 self.revision = p[hashIdx:]
1110                 p = p[0:hashIdx]
1111             elif self.previousDepotPaths == []:
1112                 self.revision = "#head"
1114             p = re.sub ("\.\.\.$", "", p)
1115             if not p.endswith("/"):
1116                 p += "/"
1118             newPaths.append(p)
1120         self.depotPaths = newPaths
1123         self.loadUserMapFromCache()
1124         self.labels = {}
1125         if self.detectLabels:
1126             self.getLabels();
1128         if self.detectBranches:
1129             self.getBranchMapping();
1130             if self.verbose:
1131                 print "p4-git branches: %s" % self.p4BranchesInGit
1132                 print "initial parents: %s" % self.initialParents
1133             for b in self.p4BranchesInGit:
1134                 if b != "master":
1136                     ## FIXME
1137                     b = b[len(self.projectName):]
1138                 self.createdBranches.add(b)
1140         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1142         importProcess = subprocess.Popen(["git", "fast-import"],
1143                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1144                                          stderr=subprocess.PIPE);
1145         self.gitOutput = importProcess.stdout
1146         self.gitStream = importProcess.stdin
1147         self.gitError = importProcess.stderr
1149         if self.revision:
1150             print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
1152             details = { "user" : "git perforce import user", "time" : int(time.time()) }
1153             details["desc"] = ("Initial import of %s from the state at revision %s"
1154                                % (' '.join(self.depotPaths), self.revision))
1155             details["change"] = self.revision
1156             newestRevision = 0
1158             fileCnt = 0
1159             for info in p4CmdList("files "
1160                                   +  ' '.join(["%s...%s"
1161                                                % (p, self.revision)
1162                                                for p in self.depotPaths])):
1164                 if info['code'] == 'error':
1165                     sys.stderr.write("p4 returned an error: %s\n"
1166                                      % info['data'])
1167                     sys.exit(1)
1170                 change = int(info["change"])
1171                 if change > newestRevision:
1172                     newestRevision = change
1174                 if info["action"] == "delete":
1175                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1176                     #fileCnt = fileCnt + 1
1177                     continue
1179                 for prop in ["depotFile", "rev", "action", "type" ]:
1180                     details["%s%s" % (prop, fileCnt)] = info[prop]
1182                 fileCnt = fileCnt + 1
1184             details["change"] = newestRevision
1185             self.updateOptionDict(details)
1186             try:
1187                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1188             except IOError:
1189                 print "IO error with git fast-import. Is your git version recent enough?"
1190                 print self.gitError.read()
1192         else:
1193             changes = []
1195             if len(self.changesFile) > 0:
1196                 output = open(self.changesFile).readlines()
1197                 changeSet = Set()
1198                 for line in output:
1199                     changeSet.add(int(line))
1201                 for change in changeSet:
1202                     changes.append(change)
1204                 changes.sort()
1205             else:
1206                 if self.verbose:
1207                     print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1208                                                               self.changeRange)
1209                 assert self.depotPaths
1210                 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1211                                                                     for p in self.depotPaths]))
1213                 for line in output:
1214                     changeNum = line.split(" ")[1]
1215                     changes.append(changeNum)
1217                 changes.reverse()
1219                 if len(self.maxChanges) > 0:
1220                     changes = changes[0:min(int(self.maxChanges), len(changes))]
1222             if len(changes) == 0:
1223                 if not self.silent:
1224                     print "No changes to import!"
1225                 return True
1227             self.updatedBranches = set()
1229             cnt = 1
1230             for change in changes:
1231                 description = p4Cmd("describe %s" % change)
1232                 self.updateOptionDict(description)
1234                 if not self.silent:
1235                     sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1236                     sys.stdout.flush()
1237                 cnt = cnt + 1
1239                 try:
1240                     if self.detectBranches:
1241                         branches = self.splitFilesIntoBranches(description)
1242                         for branch in branches.keys():
1243                             ## HACK  --hwn
1244                             branchPrefix = self.depotPaths[0] + branch + "/"
1246                             parent = ""
1248                             filesForCommit = branches[branch]
1250                             if self.verbose:
1251                                 print "branch is %s" % branch
1253                             self.updatedBranches.add(branch)
1255                             if branch not in self.createdBranches:
1256                                 self.createdBranches.add(branch)
1257                                 parent = self.knownBranches[branch]
1258                                 if parent == branch:
1259                                     parent = ""
1260                                 elif self.verbose:
1261                                     print "parent determined through known branches: %s" % parent
1263                             # main branch? use master
1264                             if branch == "main":
1265                                 branch = "master"
1266                             else:
1268                                 ## FIXME
1269                                 branch = self.projectName + branch
1271                             if parent == "main":
1272                                 parent = "master"
1273                             elif len(parent) > 0:
1274                                 ## FIXME
1275                                 parent = self.projectName + parent
1277                             branch = self.refPrefix + branch
1278                             if len(parent) > 0:
1279                                 parent = self.refPrefix + parent
1281                             if self.verbose:
1282                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1284                             if len(parent) == 0 and branch in self.initialParents:
1285                                 parent = self.initialParents[branch]
1286                                 del self.initialParents[branch]
1288                             self.commit(description, filesForCommit, branch, branchPrefix, parent)
1289                     else:
1290                         files = self.extractFilesFromCommit(description)
1291                         self.commit(description, files, self.branch, self.depotPaths,
1292                                     self.initialParent)
1293                         self.initialParent = ""
1294                 except IOError:
1295                     print self.gitError.read()
1296                     sys.exit(1)
1298             if not self.silent:
1299                 print ""
1300                 if len(self.updatedBranches) > 0:
1301                     sys.stdout.write("Updated branches: ")
1302                     for b in self.updatedBranches:
1303                         sys.stdout.write("%s " % b)
1304                     sys.stdout.write("\n")
1307         self.gitStream.close()
1308         if importProcess.wait() != 0:
1309             die("fast-import failed: %s" % self.gitError.read())
1310         self.gitOutput.close()
1311         self.gitError.close()
1313         return True
1315 class P4Rebase(Command):
1316     def __init__(self):
1317         Command.__init__(self)
1318         self.options = [ ]
1319         self.description = ("Fetches the latest revision from perforce and "
1320                             + "rebases the current work (branch) against it")
1321         self.verbose = False
1323     def run(self, args):
1324         sync = P4Sync()
1325         sync.run([])
1326         print "Rebasing the current branch"
1327         oldHead = read_pipe("git rev-parse HEAD").strip()
1328         system("git rebase p4")
1329         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1330         return True
1332 class P4Clone(P4Sync):
1333     def __init__(self):
1334         P4Sync.__init__(self)
1335         self.description = "Creates a new git repository and imports from Perforce into it"
1336         self.usage = "usage: %prog [options] //depot/path[@revRange]"
1337         self.options.append(
1338             optparse.make_option("--destination", dest="cloneDestination",
1339                                  action='store', default=None,
1340                                  help="where to leave result of the clone"))
1341         self.cloneDestination = None
1342         self.needsGit = False
1344     def defaultDestination(self, args):
1345         ## TODO: use common prefix of args?
1346         depotPath = args[0]
1347         depotDir = re.sub("(@[^@]*)$", "", depotPath)
1348         depotDir = re.sub("(#[^#]*)$", "", depotDir)
1349         depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1350         depotDir = re.sub(r"/$", "", depotDir)
1351         return os.path.split(depotDir)[1]
1353     def run(self, args):
1354         if len(args) < 1:
1355             return False
1357         if self.keepRepoPath and not self.cloneDestination:
1358             sys.stderr.write("Must specify destination for --keep-path\n")
1359             sys.exit(1)
1361         depotPaths = args
1362         for p in depotPaths:
1363             if not p.startswith("//"):
1364                 return False
1366         if not self.cloneDestination:
1367             self.cloneDestination = self.defaultDestination()
1369         print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1370         os.makedirs(self.cloneDestination)
1371         os.chdir(self.cloneDestination)
1372         system("git init")
1373         self.gitdir = os.getcwd() + "/.git"
1374         if not P4Sync.run(self, depotPaths):
1375             return False
1376         if self.branch != "master":
1377             if gitBranchExists("refs/remotes/p4/master"):
1378                 system("git branch master refs/remotes/p4/master")
1379                 system("git checkout -f")
1380             else:
1381                 print "Could not detect main branch. No checkout/master branch created."
1383         return True
1385 class HelpFormatter(optparse.IndentedHelpFormatter):
1386     def __init__(self):
1387         optparse.IndentedHelpFormatter.__init__(self)
1389     def format_description(self, description):
1390         if description:
1391             return description + "\n"
1392         else:
1393             return ""
1395 def printUsage(commands):
1396     print "usage: %s <command> [options]" % sys.argv[0]
1397     print ""
1398     print "valid commands: %s" % ", ".join(commands)
1399     print ""
1400     print "Try %s <command> --help for command specific help." % sys.argv[0]
1401     print ""
1403 commands = {
1404     "debug" : P4Debug,
1405     "submit" : P4Submit,
1406     "sync" : P4Sync,
1407     "rebase" : P4Rebase,
1408     "clone" : P4Clone,
1409     "rollback" : P4RollBack
1413 def main():
1414     if len(sys.argv[1:]) == 0:
1415         printUsage(commands.keys())
1416         sys.exit(2)
1418     cmd = ""
1419     cmdName = sys.argv[1]
1420     try:
1421         klass = commands[cmdName]
1422         cmd = klass()
1423     except KeyError:
1424         print "unknown command %s" % cmdName
1425         print ""
1426         printUsage(commands.keys())
1427         sys.exit(2)
1429     options = cmd.options
1430     cmd.gitdir = os.environ.get("GIT_DIR", None)
1432     args = sys.argv[2:]
1434     if len(options) > 0:
1435         options.append(optparse.make_option("--git-dir", dest="gitdir"))
1437         parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1438                                        options,
1439                                        description = cmd.description,
1440                                        formatter = HelpFormatter())
1442         (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1443     global verbose
1444     verbose = cmd.verbose
1445     if cmd.needsGit:
1446         if cmd.gitdir == None:
1447             cmd.gitdir = os.path.abspath(".git")
1448             if not isValidGitDir(cmd.gitdir):
1449                 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1450                 if os.path.exists(cmd.gitdir):
1451                     cdup = read_pipe("git rev-parse --show-cdup").strip()
1452                     if len(cdup) > 0:
1453                         os.chdir(cdup);
1455         if not isValidGitDir(cmd.gitdir):
1456             if isValidGitDir(cmd.gitdir + "/.git"):
1457                 cmd.gitdir += "/.git"
1458             else:
1459                 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1461         os.environ["GIT_DIR"] = cmd.gitdir
1463     if not cmd.run(args):
1464         parser.print_help()
1467 if __name__ == '__main__':
1468     main()