Code

54053e3f3d404567ce4b5734b2c7e94cdf666645
[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, stdin=None, stdin_mode='w+b'):
67     cmd = "p4 -G %s" % cmd
68     if verbose:
69         sys.stderr.write("Opening pipe: %s\n" % cmd)
71     # Use a temporary file to avoid deadlocks without
72     # subprocess.communicate(), which would put another copy
73     # of stdout into memory.
74     stdin_file = None
75     if stdin is not None:
76         stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
77         stdin_file.write(stdin)
78         stdin_file.flush()
79         stdin_file.seek(0)
81     p4 = subprocess.Popen(cmd, shell=True,
82                           stdin=stdin_file,
83                           stdout=subprocess.PIPE)
85     result = []
86     try:
87         while True:
88             entry = marshal.load(p4.stdout)
89             result.append(entry)
90     except EOFError:
91         pass
92     exitCode = p4.wait()
93     if exitCode != 0:
94         entry = {}
95         entry["p4ExitCode"] = exitCode
96         result.append(entry)
98     return result
100 def p4Cmd(cmd):
101     list = p4CmdList(cmd)
102     result = {}
103     for entry in list:
104         result.update(entry)
105     return result;
107 def p4Where(depotPath):
108     if not depotPath.endswith("/"):
109         depotPath += "/"
110     output = p4Cmd("where %s..." % depotPath)
111     if output["code"] == "error":
112         return ""
113     clientPath = ""
114     if "path" in output:
115         clientPath = output.get("path")
116     elif "data" in output:
117         data = output.get("data")
118         lastSpace = data.rfind(" ")
119         clientPath = data[lastSpace + 1:]
121     if clientPath.endswith("..."):
122         clientPath = clientPath[:-3]
123     return clientPath
125 def currentGitBranch():
126     return read_pipe("git name-rev HEAD").split(" ")[1].strip()
128 def isValidGitDir(path):
129     if (os.path.exists(path + "/HEAD")
130         and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
131         return True;
132     return False
134 def parseRevision(ref):
135     return read_pipe("git rev-parse %s" % ref).strip()
137 def extractLogMessageFromGitCommit(commit):
138     logMessage = ""
140     ## fixme: title is first line of commit, not 1st paragraph.
141     foundTitle = False
142     for log in read_pipe_lines("git cat-file commit %s" % commit):
143        if not foundTitle:
144            if len(log) == 1:
145                foundTitle = True
146            continue
148        logMessage += log
149     return logMessage
151 def extractSettingsGitLog(log):
152     values = {}
153     for line in log.split("\n"):
154         line = line.strip()
155         m = re.search (r"^ *\[git-p4: (.*)\]$", line)
156         if not m:
157             continue
159         assignments = m.group(1).split (':')
160         for a in assignments:
161             vals = a.split ('=')
162             key = vals[0].strip()
163             val = ('='.join (vals[1:])).strip()
164             if val.endswith ('\"') and val.startswith('"'):
165                 val = val[1:-1]
167             values[key] = val
169     paths = values.get("depot-paths")
170     if not paths:
171         paths = values.get("depot-path")
172     if paths:
173         values['depot-paths'] = paths.split(',')
174     return values
176 def gitBranchExists(branch):
177     proc = subprocess.Popen(["git", "rev-parse", branch],
178                             stderr=subprocess.PIPE, stdout=subprocess.PIPE);
179     return proc.wait() == 0;
181 def gitConfig(key):
182     return read_pipe("git config %s" % key, ignore_error=True).strip()
184 def findUpstreamBranchPoint(head = "HEAD"):
185     settings = None
186     branchPoint = ""
187     parent = 0
188     while parent < 65535:
189         commit = head + "~%s" % parent
190         log = extractLogMessageFromGitCommit(commit)
191         settings = extractSettingsGitLog(log)
192         if not settings.has_key("depot-paths"):
193             parent = parent + 1
194             continue
196         names = read_pipe_lines("git name-rev \"--refs=refs/remotes/p4/*\" \"%s\"" % commit)
197         if len(names) <= 0:
198             continue
200         # strip away the beginning of 'HEAD~42 refs/remotes/p4/foo'
201         branchPoint = names[0].strip()[len(commit) + 1:]
202         break
204     return [branchPoint, settings]
206 class Command:
207     def __init__(self):
208         self.usage = "usage: %prog [options]"
209         self.needsGit = True
211 class P4Debug(Command):
212     def __init__(self):
213         Command.__init__(self)
214         self.options = [
215             optparse.make_option("--verbose", dest="verbose", action="store_true",
216                                  default=False),
217             ]
218         self.description = "A tool to debug the output of p4 -G."
219         self.needsGit = False
220         self.verbose = False
222     def run(self, args):
223         j = 0
224         for output in p4CmdList(" ".join(args)):
225             print 'Element: %d' % j
226             j += 1
227             print output
228         return True
230 class P4RollBack(Command):
231     def __init__(self):
232         Command.__init__(self)
233         self.options = [
234             optparse.make_option("--verbose", dest="verbose", action="store_true"),
235             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
236         ]
237         self.description = "A tool to debug the multi-branch import. Don't use :)"
238         self.verbose = False
239         self.rollbackLocalBranches = False
241     def run(self, args):
242         if len(args) != 1:
243             return False
244         maxChange = int(args[0])
246         if "p4ExitCode" in p4Cmd("changes -m 1"):
247             die("Problems executing p4");
249         if self.rollbackLocalBranches:
250             refPrefix = "refs/heads/"
251             lines = read_pipe_lines("git rev-parse --symbolic --branches")
252         else:
253             refPrefix = "refs/remotes/"
254             lines = read_pipe_lines("git rev-parse --symbolic --remotes")
256         for line in lines:
257             if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
258                 line = line.strip()
259                 ref = refPrefix + line
260                 log = extractLogMessageFromGitCommit(ref)
261                 settings = extractSettingsGitLog(log)
263                 depotPaths = settings['depot-paths']
264                 change = settings['change']
266                 changed = False
268                 if len(p4Cmd("changes -m 1 "  + ' '.join (['%s...@%s' % (p, maxChange)
269                                                            for p in depotPaths]))) == 0:
270                     print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
271                     system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
272                     continue
274                 while change and int(change) > maxChange:
275                     changed = True
276                     if self.verbose:
277                         print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
278                     system("git update-ref %s \"%s^\"" % (ref, ref))
279                     log = extractLogMessageFromGitCommit(ref)
280                     settings =  extractSettingsGitLog(log)
283                     depotPaths = settings['depot-paths']
284                     change = settings['change']
286                 if changed:
287                     print "%s rewound to %s" % (ref, change)
289         return True
291 class P4Submit(Command):
292     def __init__(self):
293         Command.__init__(self)
294         self.options = [
295                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
296                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
297                 optparse.make_option("--origin", dest="origin"),
298                 optparse.make_option("--reset", action="store_true", dest="reset"),
299                 optparse.make_option("--log-substitutions", dest="substFile"),
300                 optparse.make_option("--dry-run", action="store_true"),
301                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
302                 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
303         ]
304         self.description = "Submit changes from git to the perforce depot."
305         self.usage += " [name of git branch to submit into perforce depot]"
306         self.firstTime = True
307         self.reset = False
308         self.interactive = True
309         self.dryRun = False
310         self.substFile = ""
311         self.firstTime = True
312         self.origin = ""
313         self.directSubmit = False
314         self.trustMeLikeAFool = False
315         self.verbose = False
316         self.isWindows = (platform.system() == "Windows")
318         self.logSubstitutions = {}
319         self.logSubstitutions["<enter description here>"] = "%log%"
320         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
322     def check(self):
323         if len(p4CmdList("opened ...")) > 0:
324             die("You have files opened with perforce! Close them before starting the sync.")
326     def start(self):
327         if len(self.config) > 0 and not self.reset:
328             die("Cannot start sync. Previous sync config found at %s\n"
329                 "If you want to start submitting again from scratch "
330                 "maybe you want to call git-p4 submit --reset" % self.configFile)
332         commits = []
333         if self.directSubmit:
334             commits.append("0")
335         else:
336             for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
337                 commits.append(line.strip())
338             commits.reverse()
340         self.config["commits"] = commits
342     def prepareLogMessage(self, template, message):
343         result = ""
345         for line in template.split("\n"):
346             if line.startswith("#"):
347                 result += line + "\n"
348                 continue
350             substituted = False
351             for key in self.logSubstitutions.keys():
352                 if line.find(key) != -1:
353                     value = self.logSubstitutions[key]
354                     value = value.replace("%log%", message)
355                     if value != "@remove@":
356                         result += line.replace(key, value) + "\n"
357                     substituted = True
358                     break
360             if not substituted:
361                 result += line + "\n"
363         return result
365     def applyCommit(self, id):
366         if self.directSubmit:
367             print "Applying local change in working directory/index"
368             diff = self.diffStatus
369         else:
370             print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
371             diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
372         filesToAdd = set()
373         filesToDelete = set()
374         editedFiles = set()
375         for line in diff:
376             modifier = line[0]
377             path = line[1:].strip()
378             if modifier == "M":
379                 system("p4 edit \"%s\"" % path)
380                 editedFiles.add(path)
381             elif modifier == "A":
382                 filesToAdd.add(path)
383                 if path in filesToDelete:
384                     filesToDelete.remove(path)
385             elif modifier == "D":
386                 filesToDelete.add(path)
387                 if path in filesToAdd:
388                     filesToAdd.remove(path)
389             else:
390                 die("unknown modifier %s for %s" % (modifier, path))
392         if self.directSubmit:
393             diffcmd = "cat \"%s\"" % self.diffFile
394         else:
395             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
396         patchcmd = diffcmd + " | git apply "
397         tryPatchCmd = patchcmd + "--check -"
398         applyPatchCmd = patchcmd + "--check --apply -"
400         if os.system(tryPatchCmd) != 0:
401             print "Unfortunately applying the change failed!"
402             print "What do you want to do?"
403             response = "x"
404             while response != "s" and response != "a" and response != "w":
405                 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
406                                      "and with .rej files / [w]rite the patch to a file (patch.txt) ")
407             if response == "s":
408                 print "Skipping! Good luck with the next patches..."
409                 return
410             elif response == "a":
411                 os.system(applyPatchCmd)
412                 if len(filesToAdd) > 0:
413                     print "You may also want to call p4 add on the following files:"
414                     print " ".join(filesToAdd)
415                 if len(filesToDelete):
416                     print "The following files should be scheduled for deletion with p4 delete:"
417                     print " ".join(filesToDelete)
418                 die("Please resolve and submit the conflict manually and "
419                     + "continue afterwards with git-p4 submit --continue")
420             elif response == "w":
421                 system(diffcmd + " > patch.txt")
422                 print "Patch saved to patch.txt in %s !" % self.clientPath
423                 die("Please resolve and submit the conflict manually and "
424                     "continue afterwards with git-p4 submit --continue")
426         system(applyPatchCmd)
428         for f in filesToAdd:
429             system("p4 add \"%s\"" % f)
430         for f in filesToDelete:
431             system("p4 revert \"%s\"" % f)
432             system("p4 delete \"%s\"" % f)
434         logMessage = ""
435         if not self.directSubmit:
436             logMessage = extractLogMessageFromGitCommit(id)
437             logMessage = logMessage.replace("\n", "\n\t")
438             if self.isWindows:
439                 logMessage = logMessage.replace("\n", "\r\n")
440             logMessage = logMessage.strip()
442         template = read_pipe("p4 change -o")
444         if self.interactive:
445             submitTemplate = self.prepareLogMessage(template, logMessage)
446             diff = read_pipe("p4 diff -du ...")
448             for newFile in filesToAdd:
449                 diff += "==== new file ====\n"
450                 diff += "--- /dev/null\n"
451                 diff += "+++ %s\n" % newFile
452                 f = open(newFile, "r")
453                 for line in f.readlines():
454                     diff += "+" + line
455                 f.close()
457             separatorLine = "######## everything below this line is just the diff #######"
458             if platform.system() == "Windows":
459                 separatorLine += "\r"
460             separatorLine += "\n"
462             response = "e"
463             if self.trustMeLikeAFool:
464                 response = "y"
466             firstIteration = True
467             while response == "e":
468                 if not firstIteration:
469                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
470                 firstIteration = False
471                 if response == "e":
472                     [handle, fileName] = tempfile.mkstemp()
473                     tmpFile = os.fdopen(handle, "w+")
474                     tmpFile.write(submitTemplate + separatorLine + diff)
475                     tmpFile.close()
476                     defaultEditor = "vi"
477                     if platform.system() == "Windows":
478                         defaultEditor = "notepad"
479                     editor = os.environ.get("EDITOR", defaultEditor);
480                     system(editor + " " + fileName)
481                     tmpFile = open(fileName, "rb")
482                     message = tmpFile.read()
483                     tmpFile.close()
484                     os.remove(fileName)
485                     submitTemplate = message[:message.index(separatorLine)]
486                     if self.isWindows:
487                         submitTemplate = submitTemplate.replace("\r\n", "\n")
489             if response == "y" or response == "yes":
490                if self.dryRun:
491                    print submitTemplate
492                    raw_input("Press return to continue...")
493                else:
494                    if self.directSubmit:
495                        print "Submitting to git first"
496                        os.chdir(self.oldWorkingDirectory)
497                        write_pipe("git commit -a -F -", submitTemplate)
498                        os.chdir(self.clientPath)
500                    write_pipe("p4 submit -i", submitTemplate)
501             elif response == "s":
502                 for f in editedFiles:
503                     system("p4 revert \"%s\"" % f);
504                 for f in filesToAdd:
505                     system("p4 revert \"%s\"" % f);
506                     system("rm %s" %f)
507                 for f in filesToDelete:
508                     system("p4 delete \"%s\"" % f);
509                 return
510             else:
511                 print "Not submitting!"
512                 self.interactive = False
513         else:
514             fileName = "submit.txt"
515             file = open(fileName, "w+")
516             file.write(self.prepareLogMessage(template, logMessage))
517             file.close()
518             print ("Perforce submit template written as %s. "
519                    + "Please review/edit and then use p4 submit -i < %s to submit directly!"
520                    % (fileName, fileName))
522     def run(self, args):
523         if len(args) == 0:
524             self.master = currentGitBranch()
525             if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
526                 die("Detecting current git branch failed!")
527         elif len(args) == 1:
528             self.master = args[0]
529         else:
530             return False
532         [upstream, settings] = findUpstreamBranchPoint()
533         depotPath = settings['depot-paths'][0]
534         if len(self.origin) == 0:
535             self.origin = upstream
537         if self.verbose:
538             print "Origin branch is " + self.origin
540         if len(depotPath) == 0:
541             print "Internal error: cannot locate perforce depot path from existing branches"
542             sys.exit(128)
544         self.clientPath = p4Where(depotPath)
546         if len(self.clientPath) == 0:
547             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
548             sys.exit(128)
550         print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
551         self.oldWorkingDirectory = os.getcwd()
553         if self.directSubmit:
554             self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
555             if len(self.diffStatus) == 0:
556                 print "No changes in working directory to submit."
557                 return True
558             patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
559             self.diffFile = self.gitdir + "/p4-git-diff"
560             f = open(self.diffFile, "wb")
561             f.write(patch)
562             f.close();
564         os.chdir(self.clientPath)
565         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
566         if response == "y" or response == "yes":
567             system("p4 sync ...")
569         if self.reset:
570             self.firstTime = True
572         if len(self.substFile) > 0:
573             for line in open(self.substFile, "r").readlines():
574                 tokens = line.strip().split("=")
575                 self.logSubstitutions[tokens[0]] = tokens[1]
577         self.check()
578         self.configFile = self.gitdir + "/p4-git-sync.cfg"
579         self.config = shelve.open(self.configFile, writeback=True)
581         if self.firstTime:
582             self.start()
584         commits = self.config.get("commits", [])
586         while len(commits) > 0:
587             self.firstTime = False
588             commit = commits[0]
589             commits = commits[1:]
590             self.config["commits"] = commits
591             self.applyCommit(commit)
592             if not self.interactive:
593                 break
595         self.config.close()
597         if self.directSubmit:
598             os.remove(self.diffFile)
600         if len(commits) == 0:
601             if self.firstTime:
602                 print "No changes found to apply between %s and current HEAD" % self.origin
603             else:
604                 print "All changes applied!"
605                 os.chdir(self.oldWorkingDirectory)
606                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
607                 if response == "y" or response == "yes":
608                     rebase = P4Rebase()
609                     rebase.run([])
610             os.remove(self.configFile)
612         return True
614 class P4Sync(Command):
615     def __init__(self):
616         Command.__init__(self)
617         self.options = [
618                 optparse.make_option("--branch", dest="branch"),
619                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
620                 optparse.make_option("--changesfile", dest="changesFile"),
621                 optparse.make_option("--silent", dest="silent", action="store_true"),
622                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
623                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
624                 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
625                                      help="Import into refs/heads/ , not refs/remotes"),
626                 optparse.make_option("--max-changes", dest="maxChanges"),
627                 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
628                                      help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
629         ]
630         self.description = """Imports from Perforce into a git repository.\n
631     example:
632     //depot/my/project/ -- to import the current head
633     //depot/my/project/@all -- to import everything
634     //depot/my/project/@1,6 -- to import only from revision 1 to 6
636     (a ... is not needed in the path p4 specification, it's added implicitly)"""
638         self.usage += " //depot/path[@revRange]"
639         self.silent = False
640         self.createdBranches = Set()
641         self.committedChanges = Set()
642         self.branch = ""
643         self.detectBranches = False
644         self.detectLabels = False
645         self.changesFile = ""
646         self.syncWithOrigin = True
647         self.verbose = False
648         self.importIntoRemotes = True
649         self.maxChanges = ""
650         self.isWindows = (platform.system() == "Windows")
651         self.keepRepoPath = False
652         self.depotPaths = None
653         self.p4BranchesInGit = []
655         if gitConfig("git-p4.syncFromOrigin") == "false":
656             self.syncWithOrigin = False
658     def extractFilesFromCommit(self, commit):
659         files = []
660         fnum = 0
661         while commit.has_key("depotFile%s" % fnum):
662             path =  commit["depotFile%s" % fnum]
664             found = [p for p in self.depotPaths
665                      if path.startswith (p)]
666             if not found:
667                 fnum = fnum + 1
668                 continue
670             file = {}
671             file["path"] = path
672             file["rev"] = commit["rev%s" % fnum]
673             file["action"] = commit["action%s" % fnum]
674             file["type"] = commit["type%s" % fnum]
675             files.append(file)
676             fnum = fnum + 1
677         return files
679     def stripRepoPath(self, path, prefixes):
680         if self.keepRepoPath:
681             prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
683         for p in prefixes:
684             if path.startswith(p):
685                 path = path[len(p):]
687         return path
689     def splitFilesIntoBranches(self, commit):
690         branches = {}
691         fnum = 0
692         while commit.has_key("depotFile%s" % fnum):
693             path =  commit["depotFile%s" % fnum]
694             found = [p for p in self.depotPaths
695                      if path.startswith (p)]
696             if not found:
697                 fnum = fnum + 1
698                 continue
700             file = {}
701             file["path"] = path
702             file["rev"] = commit["rev%s" % fnum]
703             file["action"] = commit["action%s" % fnum]
704             file["type"] = commit["type%s" % fnum]
705             fnum = fnum + 1
707             relPath = self.stripRepoPath(path, self.depotPaths)
709             for branch in self.knownBranches.keys():
711                 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
712                 if relPath.startswith(branch + "/"):
713                     if branch not in branches:
714                         branches[branch] = []
715                     branches[branch].append(file)
716                     break
718         return branches
720     ## Should move this out, doesn't use SELF.
721     def readP4Files(self, files):
722         files = [f for f in files
723                  if f['action'] != 'delete']
725         if not files:
726             return
728         filedata = p4CmdList('-x - print',
729                              stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
730                                               for f in files]),
731                              stdin_mode='w+')
732         if "p4ExitCode" in filedata[0]:
733             die("Problems executing p4. Error: [%d]."
734                 % (filedata[0]['p4ExitCode']));
736         j = 0;
737         contents = {}
738         while j < len(filedata):
739             stat = filedata[j]
740             j += 1
741             text = ''
742             while j < len(filedata) and filedata[j]['code'] in ('text',
743                                                                 'binary'):
744                 text += filedata[j]['data']
745                 j += 1
748             if not stat.has_key('depotFile'):
749                 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
750                 continue
752             contents[stat['depotFile']] = text
754         for f in files:
755             assert not f.has_key('data')
756             f['data'] = contents[f['path']]
758     def commit(self, details, files, branch, branchPrefixes, parent = ""):
759         epoch = details["time"]
760         author = details["user"]
762         if self.verbose:
763             print "commit into %s" % branch
765         # start with reading files; if that fails, we should not
766         # create a commit.
767         new_files = []
768         for f in files:
769             if [p for p in branchPrefixes if f['path'].startswith(p)]:
770                 new_files.append (f)
771             else:
772                 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
773         files = new_files
774         self.readP4Files(files)
779         self.gitStream.write("commit %s\n" % branch)
780 #        gitStream.write("mark :%s\n" % details["change"])
781         self.committedChanges.add(int(details["change"]))
782         committer = ""
783         if author not in self.users:
784             self.getUserMapFromPerforceServer()
785         if author in self.users:
786             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
787         else:
788             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
790         self.gitStream.write("committer %s\n" % committer)
792         self.gitStream.write("data <<EOT\n")
793         self.gitStream.write(details["desc"])
794         self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
795                              % (','.join (branchPrefixes), details["change"]))
796         if len(details['options']) > 0:
797             self.gitStream.write(": options = %s" % details['options'])
798         self.gitStream.write("]\nEOT\n\n")
800         if len(parent) > 0:
801             if self.verbose:
802                 print "parent %s" % parent
803             self.gitStream.write("from %s\n" % parent)
805         for file in files:
806             if file["type"] == "apple":
807                 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
808                 continue
810             relPath = self.stripRepoPath(file['path'], branchPrefixes)
811             if file["action"] == "delete":
812                 self.gitStream.write("D %s\n" % relPath)
813             else:
814                 mode = 644
815                 if file["type"].startswith("x"):
816                     mode = 755
818                 data = file['data']
820                 if self.isWindows and file["type"].endswith("text"):
821                     data = data.replace("\r\n", "\n")
823                 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
824                 self.gitStream.write("data %s\n" % len(data))
825                 self.gitStream.write(data)
826                 self.gitStream.write("\n")
828         self.gitStream.write("\n")
830         change = int(details["change"])
832         if self.labels.has_key(change):
833             label = self.labels[change]
834             labelDetails = label[0]
835             labelRevisions = label[1]
836             if self.verbose:
837                 print "Change %s is labelled %s" % (change, labelDetails)
839             files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
840                                                     for p in branchPrefixes]))
842             if len(files) == len(labelRevisions):
844                 cleanedFiles = {}
845                 for info in files:
846                     if info["action"] == "delete":
847                         continue
848                     cleanedFiles[info["depotFile"]] = info["rev"]
850                 if cleanedFiles == labelRevisions:
851                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
852                     self.gitStream.write("from %s\n" % branch)
854                     owner = labelDetails["Owner"]
855                     tagger = ""
856                     if author in self.users:
857                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
858                     else:
859                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
860                     self.gitStream.write("tagger %s\n" % tagger)
861                     self.gitStream.write("data <<EOT\n")
862                     self.gitStream.write(labelDetails["Description"])
863                     self.gitStream.write("EOT\n\n")
865                 else:
866                     if not self.silent:
867                         print ("Tag %s does not match with change %s: files do not match."
868                                % (labelDetails["label"], change))
870             else:
871                 if not self.silent:
872                     print ("Tag %s does not match with change %s: file count is different."
873                            % (labelDetails["label"], change))
875     def getUserCacheFilename(self):
876         return os.environ["HOME"] + "/.gitp4-usercache.txt"
878     def getUserMapFromPerforceServer(self):
879         if self.userMapFromPerforceServer:
880             return
881         self.users = {}
883         for output in p4CmdList("users"):
884             if not output.has_key("User"):
885                 continue
886             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
889         s = ''
890         for (key, val) in self.users.items():
891             s += "%s\t%s\n" % (key, val)
893         open(self.getUserCacheFilename(), "wb").write(s)
894         self.userMapFromPerforceServer = True
896     def loadUserMapFromCache(self):
897         self.users = {}
898         self.userMapFromPerforceServer = False
899         try:
900             cache = open(self.getUserCacheFilename(), "rb")
901             lines = cache.readlines()
902             cache.close()
903             for line in lines:
904                 entry = line.strip().split("\t")
905                 self.users[entry[0]] = entry[1]
906         except IOError:
907             self.getUserMapFromPerforceServer()
909     def getLabels(self):
910         self.labels = {}
912         l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
913         if len(l) > 0 and not self.silent:
914             print "Finding files belonging to labels in %s" % `self.depotPath`
916         for output in l:
917             label = output["label"]
918             revisions = {}
919             newestChange = 0
920             if self.verbose:
921                 print "Querying files for label %s" % label
922             for file in p4CmdList("files "
923                                   +  ' '.join (["%s...@%s" % (p, label)
924                                                 for p in self.depotPaths])):
925                 revisions[file["depotFile"]] = file["rev"]
926                 change = int(file["change"])
927                 if change > newestChange:
928                     newestChange = change
930             self.labels[newestChange] = [output, revisions]
932         if self.verbose:
933             print "Label changes: %s" % self.labels.keys()
935     def guessProjectName(self):
936         for p in self.depotPaths:
937             if p.endswith("/"):
938                 p = p[:-1]
939             p = p[p.strip().rfind("/") + 1:]
940             if not p.endswith("/"):
941                p += "/"
942             return p
944     def getBranchMapping(self):
945         lostAndFoundBranches = set()
947         for info in p4CmdList("branches"):
948             details = p4Cmd("branch -o %s" % info["branch"])
949             viewIdx = 0
950             while details.has_key("View%s" % viewIdx):
951                 paths = details["View%s" % viewIdx].split(" ")
952                 viewIdx = viewIdx + 1
953                 # require standard //depot/foo/... //depot/bar/... mapping
954                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
955                     continue
956                 source = paths[0]
957                 destination = paths[1]
958                 ## HACK
959                 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
960                     source = source[len(self.depotPaths[0]):-4]
961                     destination = destination[len(self.depotPaths[0]):-4]
963                     if destination in self.knownBranches:
964                         if not self.silent:
965                             print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
966                             print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
967                         continue
969                     self.knownBranches[destination] = source
971                     lostAndFoundBranches.discard(destination)
973                     if source not in self.knownBranches:
974                         lostAndFoundBranches.add(source)
977         for branch in lostAndFoundBranches:
978             self.knownBranches[branch] = branch
980     def listExistingP4GitBranches(self):
981         self.p4BranchesInGit = []
983         cmdline = "git rev-parse --symbolic "
984         if self.importIntoRemotes:
985             cmdline += " --remotes"
986         else:
987             cmdline += " --branches"
989         for line in read_pipe_lines(cmdline):
990             line = line.strip()
992             ## only import to p4/
993             if not line.startswith('p4/') or line == "p4/HEAD":
994                 continue
995             branch = line
997             # strip off p4
998             branch = re.sub ("^p4/", "", line)
1000             self.p4BranchesInGit.append(branch)
1001             self.initialParents[self.refPrefix + branch] = parseRevision(line)
1003     def createOrUpdateBranchesFromOrigin(self):
1004         if not self.silent:
1005             print ("Creating/updating branch(es) in %s based on origin branch(es)"
1006                    % self.refPrefix)
1008         originPrefix = "origin/p4/"
1010         for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
1011             line = line.strip()
1012             if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
1013                 continue
1015             headName = line[len(originPrefix):]
1016             remoteHead = self.refPrefix + headName
1017             originHead = line
1019             original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
1020             if (not original.has_key('depot-paths')
1021                 or not original.has_key('change')):
1022                 continue
1024             update = False
1025             if not gitBranchExists(remoteHead):
1026                 if self.verbose:
1027                     print "creating %s" % remoteHead
1028                 update = True
1029             else:
1030                 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
1031                 if settings.has_key('change') > 0:
1032                     if settings['depot-paths'] == original['depot-paths']:
1033                         originP4Change = int(original['change'])
1034                         p4Change = int(settings['change'])
1035                         if originP4Change > p4Change:
1036                             print ("%s (%s) is newer than %s (%s). "
1037                                    "Updating p4 branch from origin."
1038                                    % (originHead, originP4Change,
1039                                       remoteHead, p4Change))
1040                             update = True
1041                     else:
1042                         print ("Ignoring: %s was imported from %s while "
1043                                "%s was imported from %s"
1044                                % (originHead, ','.join(original['depot-paths']),
1045                                   remoteHead, ','.join(settings['depot-paths'])))
1047             if update:
1048                 system("git update-ref %s %s" % (remoteHead, originHead))
1050     def updateOptionDict(self, d):
1051         option_keys = {}
1052         if self.keepRepoPath:
1053             option_keys['keepRepoPath'] = 1
1055         d["options"] = ' '.join(sorted(option_keys.keys()))
1057     def readOptions(self, d):
1058         self.keepRepoPath = (d.has_key('options')
1059                              and ('keepRepoPath' in d['options']))
1061     def run(self, args):
1062         self.depotPaths = []
1063         self.changeRange = ""
1064         self.initialParent = ""
1065         self.previousDepotPaths = []
1067         # map from branch depot path to parent branch
1068         self.knownBranches = {}
1069         self.initialParents = {}
1070         self.hasOrigin = gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
1071         if not self.syncWithOrigin:
1072             self.hasOrigin = False
1074         if self.importIntoRemotes:
1075             self.refPrefix = "refs/remotes/p4/"
1076         else:
1077             self.refPrefix = "refs/heads/p4/"
1079         if self.syncWithOrigin and self.hasOrigin:
1080             if not self.silent:
1081                 print "Syncing with origin first by calling git fetch origin"
1082             system("git fetch origin")
1084         if len(self.branch) == 0:
1085             self.branch = self.refPrefix + "master"
1086             if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1087                 system("git update-ref %s refs/heads/p4" % self.branch)
1088                 system("git branch -D p4");
1089             # create it /after/ importing, when master exists
1090             if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1091                 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1093         # TODO: should always look at previous commits,
1094         # merge with previous imports, if possible.
1095         if args == []:
1096             if self.hasOrigin:
1097                 self.createOrUpdateBranchesFromOrigin()
1098             self.listExistingP4GitBranches()
1100             if len(self.p4BranchesInGit) > 1:
1101                 if not self.silent:
1102                     print "Importing from/into multiple branches"
1103                 self.detectBranches = True
1105             if self.verbose:
1106                 print "branches: %s" % self.p4BranchesInGit
1108             p4Change = 0
1109             for branch in self.p4BranchesInGit:
1110                 logMsg =  extractLogMessageFromGitCommit(self.refPrefix + branch)
1112                 settings = extractSettingsGitLog(logMsg)
1114                 self.readOptions(settings)
1115                 if (settings.has_key('depot-paths')
1116                     and settings.has_key ('change')):
1117                     change = int(settings['change']) + 1
1118                     p4Change = max(p4Change, change)
1120                     depotPaths = sorted(settings['depot-paths'])
1121                     if self.previousDepotPaths == []:
1122                         self.previousDepotPaths = depotPaths
1123                     else:
1124                         paths = []
1125                         for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1126                             for i in range(0, min(len(cur), len(prev))):
1127                                 if cur[i] <> prev[i]:
1128                                     i = i - 1
1129                                     break
1131                             paths.append (cur[:i + 1])
1133                         self.previousDepotPaths = paths
1135             if p4Change > 0:
1136                 self.depotPaths = sorted(self.previousDepotPaths)
1137                 self.changeRange = "@%s,#head" % p4Change
1138                 if not self.detectBranches:
1139                     self.initialParent = parseRevision(self.branch)
1140                 if not self.silent and not self.detectBranches:
1141                     print "Performing incremental import into %s git branch" % self.branch
1143         if not self.branch.startswith("refs/"):
1144             self.branch = "refs/heads/" + self.branch
1146         if len(args) == 0 and self.depotPaths:
1147             if not self.silent:
1148                 print "Depot paths: %s" % ' '.join(self.depotPaths)
1149         else:
1150             if self.depotPaths and self.depotPaths != args:
1151                 print ("previous import used depot path %s and now %s was specified. "
1152                        "This doesn't work!" % (' '.join (self.depotPaths),
1153                                                ' '.join (args)))
1154                 sys.exit(1)
1156             self.depotPaths = sorted(args)
1158         self.revision = ""
1159         self.users = {}
1161         newPaths = []
1162         for p in self.depotPaths:
1163             if p.find("@") != -1:
1164                 atIdx = p.index("@")
1165                 self.changeRange = p[atIdx:]
1166                 if self.changeRange == "@all":
1167                     self.changeRange = ""
1168                 elif ',' not in self.changeRange:
1169                     self.revision = self.changeRange
1170                     self.changeRange = ""
1171                 p = p[0:atIdx]
1172             elif p.find("#") != -1:
1173                 hashIdx = p.index("#")
1174                 self.revision = p[hashIdx:]
1175                 p = p[0:hashIdx]
1176             elif self.previousDepotPaths == []:
1177                 self.revision = "#head"
1179             p = re.sub ("\.\.\.$", "", p)
1180             if not p.endswith("/"):
1181                 p += "/"
1183             newPaths.append(p)
1185         self.depotPaths = newPaths
1188         self.loadUserMapFromCache()
1189         self.labels = {}
1190         if self.detectLabels:
1191             self.getLabels();
1193         if self.detectBranches:
1194             ## FIXME - what's a P4 projectName ?
1195             self.projectName = self.guessProjectName()
1197             if not self.hasOrigin:
1198                 self.getBranchMapping();
1199             if self.verbose:
1200                 print "p4-git branches: %s" % self.p4BranchesInGit
1201                 print "initial parents: %s" % self.initialParents
1202             for b in self.p4BranchesInGit:
1203                 if b != "master":
1205                     ## FIXME
1206                     b = b[len(self.projectName):]
1207                 self.createdBranches.add(b)
1209         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1211         importProcess = subprocess.Popen(["git", "fast-import"],
1212                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1213                                          stderr=subprocess.PIPE);
1214         self.gitOutput = importProcess.stdout
1215         self.gitStream = importProcess.stdin
1216         self.gitError = importProcess.stderr
1218         if self.revision:
1219             print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), self.revision, self.branch)
1221             details = { "user" : "git perforce import user", "time" : int(time.time()) }
1222             details["desc"] = ("Initial import of %s from the state at revision %s"
1223                                % (' '.join(self.depotPaths), self.revision))
1224             details["change"] = self.revision
1225             newestRevision = 0
1227             fileCnt = 0
1228             for info in p4CmdList("files "
1229                                   +  ' '.join(["%s...%s"
1230                                                % (p, self.revision)
1231                                                for p in self.depotPaths])):
1233                 if info['code'] == 'error':
1234                     sys.stderr.write("p4 returned an error: %s\n"
1235                                      % info['data'])
1236                     sys.exit(1)
1239                 change = int(info["change"])
1240                 if change > newestRevision:
1241                     newestRevision = change
1243                 if info["action"] == "delete":
1244                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1245                     #fileCnt = fileCnt + 1
1246                     continue
1248                 for prop in ["depotFile", "rev", "action", "type" ]:
1249                     details["%s%s" % (prop, fileCnt)] = info[prop]
1251                 fileCnt = fileCnt + 1
1253             details["change"] = newestRevision
1254             self.updateOptionDict(details)
1255             try:
1256                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1257             except IOError:
1258                 print "IO error with git fast-import. Is your git version recent enough?"
1259                 print self.gitError.read()
1261         else:
1262             changes = []
1264             if len(self.changesFile) > 0:
1265                 output = open(self.changesFile).readlines()
1266                 changeSet = Set()
1267                 for line in output:
1268                     changeSet.add(int(line))
1270                 for change in changeSet:
1271                     changes.append(change)
1273                 changes.sort()
1274             else:
1275                 if self.verbose:
1276                     print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1277                                                               self.changeRange)
1278                 assert self.depotPaths
1279                 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1280                                                                     for p in self.depotPaths]))
1282                 for line in output:
1283                     changeNum = line.split(" ")[1]
1284                     changes.append(changeNum)
1286                 changes.reverse()
1288                 if len(self.maxChanges) > 0:
1289                     changes = changes[0:min(int(self.maxChanges), len(changes))]
1291             if len(changes) == 0:
1292                 if not self.silent:
1293                     print "No changes to import!"
1294                 return True
1296             if not self.silent and not self.detectBranches:
1297                 print "Import destination: %s" % self.branch
1299             self.updatedBranches = set()
1301             cnt = 1
1302             for change in changes:
1303                 description = p4Cmd("describe %s" % change)
1304                 self.updateOptionDict(description)
1306                 if not self.silent:
1307                     sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1308                     sys.stdout.flush()
1309                 cnt = cnt + 1
1311                 try:
1312                     if self.detectBranches:
1313                         branches = self.splitFilesIntoBranches(description)
1314                         for branch in branches.keys():
1315                             ## HACK  --hwn
1316                             branchPrefix = self.depotPaths[0] + branch + "/"
1318                             parent = ""
1320                             filesForCommit = branches[branch]
1322                             if self.verbose:
1323                                 print "branch is %s" % branch
1325                             self.updatedBranches.add(branch)
1327                             if branch not in self.createdBranches:
1328                                 self.createdBranches.add(branch)
1329                                 parent = self.knownBranches[branch]
1330                                 if parent == branch:
1331                                     parent = ""
1332                                 elif self.verbose:
1333                                     print "parent determined through known branches: %s" % parent
1335                             # main branch? use master
1336                             if branch == "main":
1337                                 branch = "master"
1338                             else:
1340                                 ## FIXME
1341                                 branch = self.projectName + branch
1343                             if parent == "main":
1344                                 parent = "master"
1345                             elif len(parent) > 0:
1346                                 ## FIXME
1347                                 parent = self.projectName + parent
1349                             branch = self.refPrefix + branch
1350                             if len(parent) > 0:
1351                                 parent = self.refPrefix + parent
1353                             if self.verbose:
1354                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1356                             if len(parent) == 0 and branch in self.initialParents:
1357                                 parent = self.initialParents[branch]
1358                                 del self.initialParents[branch]
1360                             self.commit(description, filesForCommit, branch, [branchPrefix], parent)
1361                     else:
1362                         files = self.extractFilesFromCommit(description)
1363                         self.commit(description, files, self.branch, self.depotPaths,
1364                                     self.initialParent)
1365                         self.initialParent = ""
1366                 except IOError:
1367                     print self.gitError.read()
1368                     sys.exit(1)
1370             if not self.silent:
1371                 print ""
1372                 if len(self.updatedBranches) > 0:
1373                     sys.stdout.write("Updated branches: ")
1374                     for b in self.updatedBranches:
1375                         sys.stdout.write("%s " % b)
1376                     sys.stdout.write("\n")
1379         self.gitStream.close()
1380         if importProcess.wait() != 0:
1381             die("fast-import failed: %s" % self.gitError.read())
1382         self.gitOutput.close()
1383         self.gitError.close()
1385         return True
1387 class P4Rebase(Command):
1388     def __init__(self):
1389         Command.__init__(self)
1390         self.options = [ ]
1391         self.description = ("Fetches the latest revision from perforce and "
1392                             + "rebases the current work (branch) against it")
1393         self.verbose = False
1395     def run(self, args):
1396         sync = P4Sync()
1397         sync.run([])
1399         [upstream, settings] = findUpstreamBranchPoint()
1400         if len(upstream) == 0:
1401             die("Cannot find upstream branchpoint for rebase")
1403         # the branchpoint may be p4/foo~3, so strip off the parent
1404         upstream = re.sub("~[0-9]+$", "", upstream)
1406         print "Rebasing the current branch onto %s" % upstream
1407         oldHead = read_pipe("git rev-parse HEAD").strip()
1408         system("git rebase %s" % upstream)
1409         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1410         return True
1412 class P4Clone(P4Sync):
1413     def __init__(self):
1414         P4Sync.__init__(self)
1415         self.description = "Creates a new git repository and imports from Perforce into it"
1416         self.usage = "usage: %prog [options] //depot/path[@revRange]"
1417         self.options.append(
1418             optparse.make_option("--destination", dest="cloneDestination",
1419                                  action='store', default=None,
1420                                  help="where to leave result of the clone"))
1421         self.cloneDestination = None
1422         self.needsGit = False
1424     def defaultDestination(self, args):
1425         ## TODO: use common prefix of args?
1426         depotPath = args[0]
1427         depotDir = re.sub("(@[^@]*)$", "", depotPath)
1428         depotDir = re.sub("(#[^#]*)$", "", depotDir)
1429         depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1430         depotDir = re.sub(r"/$", "", depotDir)
1431         return os.path.split(depotDir)[1]
1433     def run(self, args):
1434         if len(args) < 1:
1435             return False
1437         if self.keepRepoPath and not self.cloneDestination:
1438             sys.stderr.write("Must specify destination for --keep-path\n")
1439             sys.exit(1)
1441         depotPaths = args
1443         if not self.cloneDestination and len(depotPaths) > 1:
1444             self.cloneDestination = depotPaths[-1]
1445             depotPaths = depotPaths[:-1]
1447         for p in depotPaths:
1448             if not p.startswith("//"):
1449                 return False
1451         if not self.cloneDestination:
1452             self.cloneDestination = self.defaultDestination(args)
1454         print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1455         if not os.path.exists(self.cloneDestination):
1456             os.makedirs(self.cloneDestination)
1457         os.chdir(self.cloneDestination)
1458         system("git init")
1459         self.gitdir = os.getcwd() + "/.git"
1460         if not P4Sync.run(self, depotPaths):
1461             return False
1462         if self.branch != "master":
1463             if gitBranchExists("refs/remotes/p4/master"):
1464                 system("git branch master refs/remotes/p4/master")
1465                 system("git checkout -f")
1466             else:
1467                 print "Could not detect main branch. No checkout/master branch created."
1469         return True
1471 class P4Branches(Command):
1472     def __init__(self):
1473         Command.__init__(self)
1474         self.options = [ ]
1475         self.description = ("Shows the git branches that hold imports and their "
1476                             + "corresponding perforce depot paths")
1477         self.verbose = False
1479     def run(self, args):
1480         cmdline = "git rev-parse --symbolic "
1481         cmdline += " --remotes"
1483         for line in read_pipe_lines(cmdline):
1484             line = line.strip()
1486             if not line.startswith('p4/') or line == "p4/HEAD":
1487                 continue
1488             branch = line
1490             log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
1491             settings = extractSettingsGitLog(log)
1493             print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
1494         return True
1496 class HelpFormatter(optparse.IndentedHelpFormatter):
1497     def __init__(self):
1498         optparse.IndentedHelpFormatter.__init__(self)
1500     def format_description(self, description):
1501         if description:
1502             return description + "\n"
1503         else:
1504             return ""
1506 def printUsage(commands):
1507     print "usage: %s <command> [options]" % sys.argv[0]
1508     print ""
1509     print "valid commands: %s" % ", ".join(commands)
1510     print ""
1511     print "Try %s <command> --help for command specific help." % sys.argv[0]
1512     print ""
1514 commands = {
1515     "debug" : P4Debug,
1516     "submit" : P4Submit,
1517     "sync" : P4Sync,
1518     "rebase" : P4Rebase,
1519     "clone" : P4Clone,
1520     "rollback" : P4RollBack,
1521     "branches" : P4Branches
1525 def main():
1526     if len(sys.argv[1:]) == 0:
1527         printUsage(commands.keys())
1528         sys.exit(2)
1530     cmd = ""
1531     cmdName = sys.argv[1]
1532     try:
1533         klass = commands[cmdName]
1534         cmd = klass()
1535     except KeyError:
1536         print "unknown command %s" % cmdName
1537         print ""
1538         printUsage(commands.keys())
1539         sys.exit(2)
1541     options = cmd.options
1542     cmd.gitdir = os.environ.get("GIT_DIR", None)
1544     args = sys.argv[2:]
1546     if len(options) > 0:
1547         options.append(optparse.make_option("--git-dir", dest="gitdir"))
1549         parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1550                                        options,
1551                                        description = cmd.description,
1552                                        formatter = HelpFormatter())
1554         (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1555     global verbose
1556     verbose = cmd.verbose
1557     if cmd.needsGit:
1558         if cmd.gitdir == None:
1559             cmd.gitdir = os.path.abspath(".git")
1560             if not isValidGitDir(cmd.gitdir):
1561                 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1562                 if os.path.exists(cmd.gitdir):
1563                     cdup = read_pipe("git rev-parse --show-cdup").strip()
1564                     if len(cdup) > 0:
1565                         os.chdir(cdup);
1567         if not isValidGitDir(cmd.gitdir):
1568             if isValidGitDir(cmd.gitdir + "/.git"):
1569                 cmd.gitdir += "/.git"
1570             else:
1571                 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1573         os.environ["GIT_DIR"] = cmd.gitdir
1575     if not cmd.run(args):
1576         parser.print_help()
1579 if __name__ == '__main__':
1580     main()