Merge branch 'cr/tag'
[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 #
10
11 import optparse, sys, os, marshal, popen2, subprocess, shelve
12 import tempfile, getopt, sha, os.path, time, platform
13 import re
14
15 from sets import Set;
16
17 verbose = False
18
19 def die(msg):
20     if verbose:
21         raise Exception(msg)
22     else:
23         sys.stderr.write(msg + "\n")
24         sys.exit(1)
25
26 def write_pipe(c, str):
27     if verbose:
28         sys.stderr.write('Writing pipe: %s\n' % c)
29
30     pipe = os.popen(c, 'w')
31     val = pipe.write(str)
32     if pipe.close():
33         die('Command failed: %s' % c)
34
35     return val
36
37 def read_pipe(c, ignore_error=False):
38     if verbose:
39         sys.stderr.write('Reading pipe: %s\n' % c)
40
41     pipe = os.popen(c, 'rb')
42     val = pipe.read()
43     if pipe.close() and not ignore_error:
44         die('Command failed: %s' % c)
45
46     return val
47
48
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)
57
58     return val
59
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)
65
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)
70
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)
80
81     p4 = subprocess.Popen(cmd, shell=True,
82                           stdin=stdin_file,
83                           stdout=subprocess.PIPE)
84
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)
97
98     return result
99
100 def p4Cmd(cmd):
101     list = p4CmdList(cmd)
102     result = {}
103     for entry in list:
104         result.update(entry)
105     return result;
106
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:]
120
121     if clientPath.endswith("..."):
122         clientPath = clientPath[:-3]
123     return clientPath
124
125 def currentGitBranch():
126     return read_pipe("git name-rev HEAD").split(" ")[1].strip()
127
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
133
134 def parseRevision(ref):
135     return read_pipe("git rev-parse %s" % ref).strip()
136
137 def extractLogMessageFromGitCommit(commit):
138     logMessage = ""
139
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
147
148        logMessage += log
149     return logMessage
150
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
158
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]
166
167             values[key] = val
168
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
175
176 def gitBranchExists(branch):
177     proc = subprocess.Popen(["git", "rev-parse", branch],
178                             stderr=subprocess.PIPE, stdout=subprocess.PIPE);
179     return proc.wait() == 0;
180
181 def gitConfig(key):
182     return read_pipe("git config %s" % key, ignore_error=True).strip()
183
184 def p4BranchesInGit(branchesAreInRemotes = True):
185     branches = {}
186
187     cmdline = "git rev-parse --symbolic "
188     if branchesAreInRemotes:
189         cmdline += " --remotes"
190     else:
191         cmdline += " --branches"
192
193     for line in read_pipe_lines(cmdline):
194         line = line.strip()
195
196         ## only import to p4/
197         if not line.startswith('p4/') or line == "p4/HEAD":
198             continue
199         branch = line
200
201         # strip off p4
202         branch = re.sub ("^p4/", "", line)
203
204         branches[branch] = parseRevision(line)
205     return branches
206
207 def findUpstreamBranchPoint(head = "HEAD"):
208     branches = p4BranchesInGit()
209     # map from depot-path to branch name
210     branchByDepotPath = {}
211     for branch in branches.keys():
212         tip = branches[branch]
213         log = extractLogMessageFromGitCommit(tip)
214         settings = extractSettingsGitLog(log)
215         if settings.has_key("depot-paths"):
216             paths = ",".join(settings["depot-paths"])
217             branchByDepotPath[paths] = "remotes/p4/" + branch
218
219     settings = None
220     parent = 0
221     while parent < 65535:
222         commit = head + "~%s" % parent
223         log = extractLogMessageFromGitCommit(commit)
224         settings = extractSettingsGitLog(log)
225         if settings.has_key("depot-paths"):
226             paths = ",".join(settings["depot-paths"])
227             if branchByDepotPath.has_key(paths):
228                 return [branchByDepotPath[paths], settings]
229
230         parent = parent + 1
231
232     return ["", settings]
233
234 class Command:
235     def __init__(self):
236         self.usage = "usage: %prog [options]"
237         self.needsGit = True
238
239 class P4Debug(Command):
240     def __init__(self):
241         Command.__init__(self)
242         self.options = [
243             optparse.make_option("--verbose", dest="verbose", action="store_true",
244                                  default=False),
245             ]
246         self.description = "A tool to debug the output of p4 -G."
247         self.needsGit = False
248         self.verbose = False
249
250     def run(self, args):
251         j = 0
252         for output in p4CmdList(" ".join(args)):
253             print 'Element: %d' % j
254             j += 1
255             print output
256         return True
257
258 class P4RollBack(Command):
259     def __init__(self):
260         Command.__init__(self)
261         self.options = [
262             optparse.make_option("--verbose", dest="verbose", action="store_true"),
263             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
264         ]
265         self.description = "A tool to debug the multi-branch import. Don't use :)"
266         self.verbose = False
267         self.rollbackLocalBranches = False
268
269     def run(self, args):
270         if len(args) != 1:
271             return False
272         maxChange = int(args[0])
273
274         if "p4ExitCode" in p4Cmd("changes -m 1"):
275             die("Problems executing p4");
276
277         if self.rollbackLocalBranches:
278             refPrefix = "refs/heads/"
279             lines = read_pipe_lines("git rev-parse --symbolic --branches")
280         else:
281             refPrefix = "refs/remotes/"
282             lines = read_pipe_lines("git rev-parse --symbolic --remotes")
283
284         for line in lines:
285             if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
286                 line = line.strip()
287                 ref = refPrefix + line
288                 log = extractLogMessageFromGitCommit(ref)
289                 settings = extractSettingsGitLog(log)
290
291                 depotPaths = settings['depot-paths']
292                 change = settings['change']
293
294                 changed = False
295
296                 if len(p4Cmd("changes -m 1 "  + ' '.join (['%s...@%s' % (p, maxChange)
297                                                            for p in depotPaths]))) == 0:
298                     print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
299                     system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
300                     continue
301
302                 while change and int(change) > maxChange:
303                     changed = True
304                     if self.verbose:
305                         print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
306                     system("git update-ref %s \"%s^\"" % (ref, ref))
307                     log = extractLogMessageFromGitCommit(ref)
308                     settings =  extractSettingsGitLog(log)
309
310
311                     depotPaths = settings['depot-paths']
312                     change = settings['change']
313
314                 if changed:
315                     print "%s rewound to %s" % (ref, change)
316
317         return True
318
319 class P4Submit(Command):
320     def __init__(self):
321         Command.__init__(self)
322         self.options = [
323                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
324                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
325                 optparse.make_option("--origin", dest="origin"),
326                 optparse.make_option("--reset", action="store_true", dest="reset"),
327                 optparse.make_option("--log-substitutions", dest="substFile"),
328                 optparse.make_option("--dry-run", action="store_true"),
329                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
330                 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
331         ]
332         self.description = "Submit changes from git to the perforce depot."
333         self.usage += " [name of git branch to submit into perforce depot]"
334         self.firstTime = True
335         self.reset = False
336         self.interactive = True
337         self.dryRun = False
338         self.substFile = ""
339         self.firstTime = True
340         self.origin = ""
341         self.directSubmit = False
342         self.trustMeLikeAFool = False
343         self.verbose = False
344         self.isWindows = (platform.system() == "Windows")
345
346         self.logSubstitutions = {}
347         self.logSubstitutions["<enter description here>"] = "%log%"
348         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
349
350     def check(self):
351         if len(p4CmdList("opened ...")) > 0:
352             die("You have files opened with perforce! Close them before starting the sync.")
353
354     def start(self):
355         if len(self.config) > 0 and not self.reset:
356             die("Cannot start sync. Previous sync config found at %s\n"
357                 "If you want to start submitting again from scratch "
358                 "maybe you want to call git-p4 submit --reset" % self.configFile)
359
360         commits = []
361         if self.directSubmit:
362             commits.append("0")
363         else:
364             for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
365                 commits.append(line.strip())
366             commits.reverse()
367
368         self.config["commits"] = commits
369
370     def prepareLogMessage(self, template, message):
371         result = ""
372
373         for line in template.split("\n"):
374             if line.startswith("#"):
375                 result += line + "\n"
376                 continue
377
378             substituted = False
379             for key in self.logSubstitutions.keys():
380                 if line.find(key) != -1:
381                     value = self.logSubstitutions[key]
382                     value = value.replace("%log%", message)
383                     if value != "@remove@":
384                         result += line.replace(key, value) + "\n"
385                     substituted = True
386                     break
387
388             if not substituted:
389                 result += line + "\n"
390
391         return result
392
393     def prepareSubmitTemplate(self):
394         # remove lines in the Files section that show changes to files outside the depot path we're committing into
395         template = ""
396         inFilesSection = False
397         for line in read_pipe_lines("p4 change -o"):
398             if inFilesSection:
399                 if line.startswith("\t"):
400                     # path starts and ends with a tab
401                     path = line[1:]
402                     lastTab = path.rfind("\t")
403                     if lastTab != -1:
404                         path = path[:lastTab]
405                         if not path.startswith(self.depotPath):
406                             continue
407                 else:
408                     inFilesSection = False
409             else:
410                 if line.startswith("Files:"):
411                     inFilesSection = True
412
413             template += line
414
415         return template
416
417     def applyCommit(self, id):
418         if self.directSubmit:
419             print "Applying local change in working directory/index"
420             diff = self.diffStatus
421         else:
422             print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
423             diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
424         filesToAdd = set()
425         filesToDelete = set()
426         editedFiles = set()
427         for line in diff:
428             modifier = line[0]
429             path = line[1:].strip()
430             if modifier == "M":
431                 system("p4 edit \"%s\"" % path)
432                 editedFiles.add(path)
433             elif modifier == "A":
434                 filesToAdd.add(path)
435                 if path in filesToDelete:
436                     filesToDelete.remove(path)
437             elif modifier == "D":
438                 filesToDelete.add(path)
439                 if path in filesToAdd:
440                     filesToAdd.remove(path)
441             else:
442                 die("unknown modifier %s for %s" % (modifier, path))
443
444         if self.directSubmit:
445             diffcmd = "cat \"%s\"" % self.diffFile
446         else:
447             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
448         patchcmd = diffcmd + " | git apply "
449         tryPatchCmd = patchcmd + "--check -"
450         applyPatchCmd = patchcmd + "--check --apply -"
451
452         if os.system(tryPatchCmd) != 0:
453             print "Unfortunately applying the change failed!"
454             print "What do you want to do?"
455             response = "x"
456             while response != "s" and response != "a" and response != "w":
457                 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
458                                      "and with .rej files / [w]rite the patch to a file (patch.txt) ")
459             if response == "s":
460                 print "Skipping! Good luck with the next patches..."
461                 return
462             elif response == "a":
463                 os.system(applyPatchCmd)
464                 if len(filesToAdd) > 0:
465                     print "You may also want to call p4 add on the following files:"
466                     print " ".join(filesToAdd)
467                 if len(filesToDelete):
468                     print "The following files should be scheduled for deletion with p4 delete:"
469                     print " ".join(filesToDelete)
470                 die("Please resolve and submit the conflict manually and "
471                     + "continue afterwards with git-p4 submit --continue")
472             elif response == "w":
473                 system(diffcmd + " > patch.txt")
474                 print "Patch saved to patch.txt in %s !" % self.clientPath
475                 die("Please resolve and submit the conflict manually and "
476                     "continue afterwards with git-p4 submit --continue")
477
478         system(applyPatchCmd)
479
480         for f in filesToAdd:
481             system("p4 add \"%s\"" % f)
482         for f in filesToDelete:
483             system("p4 revert \"%s\"" % f)
484             system("p4 delete \"%s\"" % f)
485
486         logMessage = ""
487         if not self.directSubmit:
488             logMessage = extractLogMessageFromGitCommit(id)
489             logMessage = logMessage.replace("\n", "\n\t")
490             if self.isWindows:
491                 logMessage = logMessage.replace("\n", "\r\n")
492             logMessage = logMessage.strip()
493
494         template = self.prepareSubmitTemplate()
495
496         if self.interactive:
497             submitTemplate = self.prepareLogMessage(template, logMessage)
498             diff = read_pipe("p4 diff -du ...")
499
500             for newFile in filesToAdd:
501                 diff += "==== new file ====\n"
502                 diff += "--- /dev/null\n"
503                 diff += "+++ %s\n" % newFile
504                 f = open(newFile, "r")
505                 for line in f.readlines():
506                     diff += "+" + line
507                 f.close()
508
509             separatorLine = "######## everything below this line is just the diff #######"
510             if platform.system() == "Windows":
511                 separatorLine += "\r"
512             separatorLine += "\n"
513
514             response = "e"
515             if self.trustMeLikeAFool:
516                 response = "y"
517
518             firstIteration = True
519             while response == "e":
520                 if not firstIteration:
521                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
522                 firstIteration = False
523                 if response == "e":
524                     [handle, fileName] = tempfile.mkstemp()
525                     tmpFile = os.fdopen(handle, "w+")
526                     tmpFile.write(submitTemplate + separatorLine + diff)
527                     tmpFile.close()
528                     defaultEditor = "vi"
529                     if platform.system() == "Windows":
530                         defaultEditor = "notepad"
531                     editor = os.environ.get("EDITOR", defaultEditor);
532                     system(editor + " " + fileName)
533                     tmpFile = open(fileName, "rb")
534                     message = tmpFile.read()
535                     tmpFile.close()
536                     os.remove(fileName)
537                     submitTemplate = message[:message.index(separatorLine)]
538                     if self.isWindows:
539                         submitTemplate = submitTemplate.replace("\r\n", "\n")
540
541             if response == "y" or response == "yes":
542                if self.dryRun:
543                    print submitTemplate
544                    raw_input("Press return to continue...")
545                else:
546                    if self.directSubmit:
547                        print "Submitting to git first"
548                        os.chdir(self.oldWorkingDirectory)
549                        write_pipe("git commit -a -F -", submitTemplate)
550                        os.chdir(self.clientPath)
551
552                    write_pipe("p4 submit -i", submitTemplate)
553             elif response == "s":
554                 for f in editedFiles:
555                     system("p4 revert \"%s\"" % f);
556                 for f in filesToAdd:
557                     system("p4 revert \"%s\"" % f);
558                     system("rm %s" %f)
559                 for f in filesToDelete:
560                     system("p4 delete \"%s\"" % f);
561                 return
562             else:
563                 print "Not submitting!"
564                 self.interactive = False
565         else:
566             fileName = "submit.txt"
567             file = open(fileName, "w+")
568             file.write(self.prepareLogMessage(template, logMessage))
569             file.close()
570             print ("Perforce submit template written as %s. "
571                    + "Please review/edit and then use p4 submit -i < %s to submit directly!"
572                    % (fileName, fileName))
573
574     def run(self, args):
575         if len(args) == 0:
576             self.master = currentGitBranch()
577             if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
578                 die("Detecting current git branch failed!")
579         elif len(args) == 1:
580             self.master = args[0]
581         else:
582             return False
583
584         [upstream, settings] = findUpstreamBranchPoint()
585         self.depotPath = settings['depot-paths'][0]
586         if len(self.origin) == 0:
587             self.origin = upstream
588
589         if self.verbose:
590             print "Origin branch is " + self.origin
591
592         if len(self.depotPath) == 0:
593             print "Internal error: cannot locate perforce depot path from existing branches"
594             sys.exit(128)
595
596         self.clientPath = p4Where(self.depotPath)
597
598         if len(self.clientPath) == 0:
599             print "Error: Cannot locate perforce checkout of %s in client view" % self.depotPath
600             sys.exit(128)
601
602         print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
603         self.oldWorkingDirectory = os.getcwd()
604
605         if self.directSubmit:
606             self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
607             if len(self.diffStatus) == 0:
608                 print "No changes in working directory to submit."
609                 return True
610             patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
611             self.diffFile = self.gitdir + "/p4-git-diff"
612             f = open(self.diffFile, "wb")
613             f.write(patch)
614             f.close();
615
616         os.chdir(self.clientPath)
617         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
618         if response == "y" or response == "yes":
619             system("p4 sync ...")
620
621         if self.reset:
622             self.firstTime = True
623
624         if len(self.substFile) > 0:
625             for line in open(self.substFile, "r").readlines():
626                 tokens = line.strip().split("=")
627                 self.logSubstitutions[tokens[0]] = tokens[1]
628
629         self.check()
630         self.configFile = self.gitdir + "/p4-git-sync.cfg"
631         self.config = shelve.open(self.configFile, writeback=True)
632
633         if self.firstTime:
634             self.start()
635
636         commits = self.config.get("commits", [])
637
638         while len(commits) > 0:
639             self.firstTime = False
640             commit = commits[0]
641             commits = commits[1:]
642             self.config["commits"] = commits
643             self.applyCommit(commit)
644             if not self.interactive:
645                 break
646
647         self.config.close()
648
649         if self.directSubmit:
650             os.remove(self.diffFile)
651
652         if len(commits) == 0:
653             if self.firstTime:
654                 print "No changes found to apply between %s and current HEAD" % self.origin
655             else:
656                 print "All changes applied!"
657                 os.chdir(self.oldWorkingDirectory)
658                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
659                 if response == "y" or response == "yes":
660                     rebase = P4Rebase()
661                     rebase.run([])
662             os.remove(self.configFile)
663
664         return True
665
666 class P4Sync(Command):
667     def __init__(self):
668         Command.__init__(self)
669         self.options = [
670                 optparse.make_option("--branch", dest="branch"),
671                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
672                 optparse.make_option("--changesfile", dest="changesFile"),
673                 optparse.make_option("--silent", dest="silent", action="store_true"),
674                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
675                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
676                 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
677                                      help="Import into refs/heads/ , not refs/remotes"),
678                 optparse.make_option("--max-changes", dest="maxChanges"),
679                 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
680                                      help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
681         ]
682         self.description = """Imports from Perforce into a git repository.\n
683     example:
684     //depot/my/project/ -- to import the current head
685     //depot/my/project/@all -- to import everything
686     //depot/my/project/@1,6 -- to import only from revision 1 to 6
687
688     (a ... is not needed in the path p4 specification, it's added implicitly)"""
689
690         self.usage += " //depot/path[@revRange]"
691         self.silent = False
692         self.createdBranches = Set()
693         self.committedChanges = Set()
694         self.branch = ""
695         self.detectBranches = False
696         self.detectLabels = False
697         self.changesFile = ""
698         self.syncWithOrigin = True
699         self.verbose = False
700         self.importIntoRemotes = True
701         self.maxChanges = ""
702         self.isWindows = (platform.system() == "Windows")
703         self.keepRepoPath = False
704         self.depotPaths = None
705         self.p4BranchesInGit = []
706
707         if gitConfig("git-p4.syncFromOrigin") == "false":
708             self.syncWithOrigin = False
709
710     def extractFilesFromCommit(self, commit):
711         files = []
712         fnum = 0
713         while commit.has_key("depotFile%s" % fnum):
714             path =  commit["depotFile%s" % fnum]
715
716             found = [p for p in self.depotPaths
717                      if path.startswith (p)]
718             if not found:
719                 fnum = fnum + 1
720                 continue
721
722             file = {}
723             file["path"] = path
724             file["rev"] = commit["rev%s" % fnum]
725             file["action"] = commit["action%s" % fnum]
726             file["type"] = commit["type%s" % fnum]
727             files.append(file)
728             fnum = fnum + 1
729         return files
730
731     def stripRepoPath(self, path, prefixes):
732         if self.keepRepoPath:
733             prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
734
735         for p in prefixes:
736             if path.startswith(p):
737                 path = path[len(p):]
738
739         return path
740
741     def splitFilesIntoBranches(self, commit):
742         branches = {}
743         fnum = 0
744         while commit.has_key("depotFile%s" % fnum):
745             path =  commit["depotFile%s" % fnum]
746             found = [p for p in self.depotPaths
747                      if path.startswith (p)]
748             if not found:
749                 fnum = fnum + 1
750                 continue
751
752             file = {}
753             file["path"] = path
754             file["rev"] = commit["rev%s" % fnum]
755             file["action"] = commit["action%s" % fnum]
756             file["type"] = commit["type%s" % fnum]
757             fnum = fnum + 1
758
759             relPath = self.stripRepoPath(path, self.depotPaths)
760
761             for branch in self.knownBranches.keys():
762
763                 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
764                 if relPath.startswith(branch + "/"):
765                     if branch not in branches:
766                         branches[branch] = []
767                     branches[branch].append(file)
768                     break
769
770         return branches
771
772     ## Should move this out, doesn't use SELF.
773     def readP4Files(self, files):
774         files = [f for f in files
775                  if f['action'] != 'delete']
776
777         if not files:
778             return
779
780         filedata = p4CmdList('-x - print',
781                              stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
782                                               for f in files]),
783                              stdin_mode='w+')
784         if "p4ExitCode" in filedata[0]:
785             die("Problems executing p4. Error: [%d]."
786                 % (filedata[0]['p4ExitCode']));
787
788         j = 0;
789         contents = {}
790         while j < len(filedata):
791             stat = filedata[j]
792             j += 1
793             text = ''
794             while j < len(filedata) and filedata[j]['code'] in ('text',
795                                                                 'binary'):
796                 text += filedata[j]['data']
797                 j += 1
798
799
800             if not stat.has_key('depotFile'):
801                 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
802                 continue
803
804             contents[stat['depotFile']] = text
805
806         for f in files:
807             assert not f.has_key('data')
808             f['data'] = contents[f['path']]
809
810     def commit(self, details, files, branch, branchPrefixes, parent = ""):
811         epoch = details["time"]
812         author = details["user"]
813
814         if self.verbose:
815             print "commit into %s" % branch
816
817         # start with reading files; if that fails, we should not
818         # create a commit.
819         new_files = []
820         for f in files:
821             if [p for p in branchPrefixes if f['path'].startswith(p)]:
822                 new_files.append (f)
823             else:
824                 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
825         files = new_files
826         self.readP4Files(files)
827
828
829
830
831         self.gitStream.write("commit %s\n" % branch)
832 #        gitStream.write("mark :%s\n" % details["change"])
833         self.committedChanges.add(int(details["change"]))
834         committer = ""
835         if author not in self.users:
836             self.getUserMapFromPerforceServer()
837         if author in self.users:
838             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
839         else:
840             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
841
842         self.gitStream.write("committer %s\n" % committer)
843
844         self.gitStream.write("data <<EOT\n")
845         self.gitStream.write(details["desc"])
846         self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
847                              % (','.join (branchPrefixes), details["change"]))
848         if len(details['options']) > 0:
849             self.gitStream.write(": options = %s" % details['options'])
850         self.gitStream.write("]\nEOT\n\n")
851
852         if len(parent) > 0:
853             if self.verbose:
854                 print "parent %s" % parent
855             self.gitStream.write("from %s\n" % parent)
856
857         for file in files:
858             if file["type"] == "apple":
859                 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
860                 continue
861
862             relPath = self.stripRepoPath(file['path'], branchPrefixes)
863             if file["action"] == "delete":
864                 self.gitStream.write("D %s\n" % relPath)
865             else:
866                 data = file['data']
867
868                 mode = "644"
869                 if file["type"].startswith("x"):
870                     mode = "755"
871                 elif file["type"] == "symlink":
872                     mode = "120000"
873                     # p4 print on a symlink contains "target\n", so strip it off
874                     data = data[:-1]
875
876                 if self.isWindows and file["type"].endswith("text"):
877                     data = data.replace("\r\n", "\n")
878
879                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
880                 self.gitStream.write("data %s\n" % len(data))
881                 self.gitStream.write(data)
882                 self.gitStream.write("\n")
883
884         self.gitStream.write("\n")
885
886         change = int(details["change"])
887
888         if self.labels.has_key(change):
889             label = self.labels[change]
890             labelDetails = label[0]
891             labelRevisions = label[1]
892             if self.verbose:
893                 print "Change %s is labelled %s" % (change, labelDetails)
894
895             files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
896                                                     for p in branchPrefixes]))
897
898             if len(files) == len(labelRevisions):
899
900                 cleanedFiles = {}
901                 for info in files:
902                     if info["action"] == "delete":
903                         continue
904                     cleanedFiles[info["depotFile"]] = info["rev"]
905
906                 if cleanedFiles == labelRevisions:
907                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
908                     self.gitStream.write("from %s\n" % branch)
909
910                     owner = labelDetails["Owner"]
911                     tagger = ""
912                     if author in self.users:
913                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
914                     else:
915                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
916                     self.gitStream.write("tagger %s\n" % tagger)
917                     self.gitStream.write("data <<EOT\n")
918                     self.gitStream.write(labelDetails["Description"])
919                     self.gitStream.write("EOT\n\n")
920
921                 else:
922                     if not self.silent:
923                         print ("Tag %s does not match with change %s: files do not match."
924                                % (labelDetails["label"], change))
925
926             else:
927                 if not self.silent:
928                     print ("Tag %s does not match with change %s: file count is different."
929                            % (labelDetails["label"], change))
930
931     def getUserCacheFilename(self):
932         home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
933         return home + "/.gitp4-usercache.txt"
934
935     def getUserMapFromPerforceServer(self):
936         if self.userMapFromPerforceServer:
937             return
938         self.users = {}
939
940         for output in p4CmdList("users"):
941             if not output.has_key("User"):
942                 continue
943             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
944
945
946         s = ''
947         for (key, val) in self.users.items():
948             s += "%s\t%s\n" % (key, val)
949
950         open(self.getUserCacheFilename(), "wb").write(s)
951         self.userMapFromPerforceServer = True
952
953     def loadUserMapFromCache(self):
954         self.users = {}
955         self.userMapFromPerforceServer = False
956         try:
957             cache = open(self.getUserCacheFilename(), "rb")
958             lines = cache.readlines()
959             cache.close()
960             for line in lines:
961                 entry = line.strip().split("\t")
962                 self.users[entry[0]] = entry[1]
963         except IOError:
964             self.getUserMapFromPerforceServer()
965
966     def getLabels(self):
967         self.labels = {}
968
969         l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
970         if len(l) > 0 and not self.silent:
971             print "Finding files belonging to labels in %s" % `self.depotPath`
972
973         for output in l:
974             label = output["label"]
975             revisions = {}
976             newestChange = 0
977             if self.verbose:
978                 print "Querying files for label %s" % label
979             for file in p4CmdList("files "
980                                   +  ' '.join (["%s...@%s" % (p, label)
981                                                 for p in self.depotPaths])):
982                 revisions[file["depotFile"]] = file["rev"]
983                 change = int(file["change"])
984                 if change > newestChange:
985                     newestChange = change
986
987             self.labels[newestChange] = [output, revisions]
988
989         if self.verbose:
990             print "Label changes: %s" % self.labels.keys()
991
992     def guessProjectName(self):
993         for p in self.depotPaths:
994             if p.endswith("/"):
995                 p = p[:-1]
996             p = p[p.strip().rfind("/") + 1:]
997             if not p.endswith("/"):
998                p += "/"
999             return p
1000
1001     def getBranchMapping(self):
1002         lostAndFoundBranches = set()
1003
1004         for info in p4CmdList("branches"):
1005             details = p4Cmd("branch -o %s" % info["branch"])
1006             viewIdx = 0
1007             while details.has_key("View%s" % viewIdx):
1008                 paths = details["View%s" % viewIdx].split(" ")
1009                 viewIdx = viewIdx + 1
1010                 # require standard //depot/foo/... //depot/bar/... mapping
1011                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
1012                     continue
1013                 source = paths[0]
1014                 destination = paths[1]
1015                 ## HACK
1016                 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
1017                     source = source[len(self.depotPaths[0]):-4]
1018                     destination = destination[len(self.depotPaths[0]):-4]
1019
1020                     if destination in self.knownBranches:
1021                         if not self.silent:
1022                             print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
1023                             print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
1024                         continue
1025
1026                     self.knownBranches[destination] = source
1027
1028                     lostAndFoundBranches.discard(destination)
1029
1030                     if source not in self.knownBranches:
1031                         lostAndFoundBranches.add(source)
1032
1033
1034         for branch in lostAndFoundBranches:
1035             self.knownBranches[branch] = branch
1036
1037     def listExistingP4GitBranches(self):
1038         # branches holds mapping from name to commit
1039         branches = p4BranchesInGit(self.importIntoRemotes)
1040         self.p4BranchesInGit = branches.keys()
1041         for branch in branches.keys():
1042             self.initialParents[self.refPrefix + branch] = branches[branch]
1043
1044     def createOrUpdateBranchesFromOrigin(self):
1045         if not self.silent:
1046             print ("Creating/updating branch(es) in %s based on origin branch(es)"
1047                    % self.refPrefix)
1048
1049         originPrefix = "origin/p4/"
1050
1051         for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
1052             line = line.strip()
1053             if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
1054                 continue
1055
1056             headName = line[len(originPrefix):]
1057             remoteHead = self.refPrefix + headName
1058             originHead = line
1059
1060             original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
1061             if (not original.has_key('depot-paths')
1062                 or not original.has_key('change')):
1063                 continue
1064
1065             update = False
1066             if not gitBranchExists(remoteHead):
1067                 if self.verbose:
1068                     print "creating %s" % remoteHead
1069                 update = True
1070             else:
1071                 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
1072                 if settings.has_key('change') > 0:
1073                     if settings['depot-paths'] == original['depot-paths']:
1074                         originP4Change = int(original['change'])
1075                         p4Change = int(settings['change'])
1076                         if originP4Change > p4Change:
1077                             print ("%s (%s) is newer than %s (%s). "
1078                                    "Updating p4 branch from origin."
1079                                    % (originHead, originP4Change,
1080                                       remoteHead, p4Change))
1081                             update = True
1082                     else:
1083                         print ("Ignoring: %s was imported from %s while "
1084                                "%s was imported from %s"
1085                                % (originHead, ','.join(original['depot-paths']),
1086                                   remoteHead, ','.join(settings['depot-paths'])))
1087
1088             if update:
1089                 system("git update-ref %s %s" % (remoteHead, originHead))
1090
1091     def updateOptionDict(self, d):
1092         option_keys = {}
1093         if self.keepRepoPath:
1094             option_keys['keepRepoPath'] = 1
1095
1096         d["options"] = ' '.join(sorted(option_keys.keys()))
1097
1098     def readOptions(self, d):
1099         self.keepRepoPath = (d.has_key('options')
1100                              and ('keepRepoPath' in d['options']))
1101
1102     def run(self, args):
1103         self.depotPaths = []
1104         self.changeRange = ""
1105         self.initialParent = ""
1106         self.previousDepotPaths = []
1107
1108         # map from branch depot path to parent branch
1109         self.knownBranches = {}
1110         self.initialParents = {}
1111         self.hasOrigin = gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
1112         if not self.syncWithOrigin:
1113             self.hasOrigin = False
1114
1115         if self.importIntoRemotes:
1116             self.refPrefix = "refs/remotes/p4/"
1117         else:
1118             self.refPrefix = "refs/heads/p4/"
1119
1120         if self.syncWithOrigin and self.hasOrigin:
1121             if not self.silent:
1122                 print "Syncing with origin first by calling git fetch origin"
1123             system("git fetch origin")
1124
1125         if len(self.branch) == 0:
1126             self.branch = self.refPrefix + "master"
1127             if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1128                 system("git update-ref %s refs/heads/p4" % self.branch)
1129                 system("git branch -D p4");
1130             # create it /after/ importing, when master exists
1131             if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1132                 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1133
1134         # TODO: should always look at previous commits,
1135         # merge with previous imports, if possible.
1136         if args == []:
1137             if self.hasOrigin:
1138                 self.createOrUpdateBranchesFromOrigin()
1139             self.listExistingP4GitBranches()
1140
1141             if len(self.p4BranchesInGit) > 1:
1142                 if not self.silent:
1143                     print "Importing from/into multiple branches"
1144                 self.detectBranches = True
1145
1146             if self.verbose:
1147                 print "branches: %s" % self.p4BranchesInGit
1148
1149             p4Change = 0
1150             for branch in self.p4BranchesInGit:
1151                 logMsg =  extractLogMessageFromGitCommit(self.refPrefix + branch)
1152
1153                 settings = extractSettingsGitLog(logMsg)
1154
1155                 self.readOptions(settings)
1156                 if (settings.has_key('depot-paths')
1157                     and settings.has_key ('change')):
1158                     change = int(settings['change']) + 1
1159                     p4Change = max(p4Change, change)
1160
1161                     depotPaths = sorted(settings['depot-paths'])
1162                     if self.previousDepotPaths == []:
1163                         self.previousDepotPaths = depotPaths
1164                     else:
1165                         paths = []
1166                         for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1167                             for i in range(0, min(len(cur), len(prev))):
1168                                 if cur[i] <> prev[i]:
1169                                     i = i - 1
1170                                     break
1171
1172                             paths.append (cur[:i + 1])
1173
1174                         self.previousDepotPaths = paths
1175
1176             if p4Change > 0:
1177                 self.depotPaths = sorted(self.previousDepotPaths)
1178                 self.changeRange = "@%s,#head" % p4Change
1179                 if not self.detectBranches:
1180                     self.initialParent = parseRevision(self.branch)
1181                 if not self.silent and not self.detectBranches:
1182                     print "Performing incremental import into %s git branch" % self.branch
1183
1184         if not self.branch.startswith("refs/"):
1185             self.branch = "refs/heads/" + self.branch
1186
1187         if len(args) == 0 and self.depotPaths:
1188             if not self.silent:
1189                 print "Depot paths: %s" % ' '.join(self.depotPaths)
1190         else:
1191             if self.depotPaths and self.depotPaths != args:
1192                 print ("previous import used depot path %s and now %s was specified. "
1193                        "This doesn't work!" % (' '.join (self.depotPaths),
1194                                                ' '.join (args)))
1195                 sys.exit(1)
1196
1197             self.depotPaths = sorted(args)
1198
1199         self.revision = ""
1200         self.users = {}
1201
1202         newPaths = []
1203         for p in self.depotPaths:
1204             if p.find("@") != -1:
1205                 atIdx = p.index("@")
1206                 self.changeRange = p[atIdx:]
1207                 if self.changeRange == "@all":
1208                     self.changeRange = ""
1209                 elif ',' not in self.changeRange:
1210                     self.revision = self.changeRange
1211                     self.changeRange = ""
1212                 p = p[:atIdx]
1213             elif p.find("#") != -1:
1214                 hashIdx = p.index("#")
1215                 self.revision = p[hashIdx:]
1216                 p = p[:hashIdx]
1217             elif self.previousDepotPaths == []:
1218                 self.revision = "#head"
1219
1220             p = re.sub ("\.\.\.$", "", p)
1221             if not p.endswith("/"):
1222                 p += "/"
1223
1224             newPaths.append(p)
1225
1226         self.depotPaths = newPaths
1227
1228
1229         self.loadUserMapFromCache()
1230         self.labels = {}
1231         if self.detectLabels:
1232             self.getLabels();
1233
1234         if self.detectBranches:
1235             ## FIXME - what's a P4 projectName ?
1236             self.projectName = self.guessProjectName()
1237
1238             if not self.hasOrigin:
1239                 self.getBranchMapping();
1240             if self.verbose:
1241                 print "p4-git branches: %s" % self.p4BranchesInGit
1242                 print "initial parents: %s" % self.initialParents
1243             for b in self.p4BranchesInGit:
1244                 if b != "master":
1245
1246                     ## FIXME
1247                     b = b[len(self.projectName):]
1248                 self.createdBranches.add(b)
1249
1250         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1251
1252         importProcess = subprocess.Popen(["git", "fast-import"],
1253                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1254                                          stderr=subprocess.PIPE);
1255         self.gitOutput = importProcess.stdout
1256         self.gitStream = importProcess.stdin
1257         self.gitError = importProcess.stderr
1258
1259         if self.revision:
1260             print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), self.revision, self.branch)
1261
1262             details = { "user" : "git perforce import user", "time" : int(time.time()) }
1263             details["desc"] = ("Initial import of %s from the state at revision %s"
1264                                % (' '.join(self.depotPaths), self.revision))
1265             details["change"] = self.revision
1266             newestRevision = 0
1267
1268             fileCnt = 0
1269             for info in p4CmdList("files "
1270                                   +  ' '.join(["%s...%s"
1271                                                % (p, self.revision)
1272                                                for p in self.depotPaths])):
1273
1274                 if info['code'] == 'error':
1275                     sys.stderr.write("p4 returned an error: %s\n"
1276                                      % info['data'])
1277                     sys.exit(1)
1278
1279
1280                 change = int(info["change"])
1281                 if change > newestRevision:
1282                     newestRevision = change
1283
1284                 if info["action"] == "delete":
1285                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1286                     #fileCnt = fileCnt + 1
1287                     continue
1288
1289                 for prop in ["depotFile", "rev", "action", "type" ]:
1290                     details["%s%s" % (prop, fileCnt)] = info[prop]
1291
1292                 fileCnt = fileCnt + 1
1293
1294             details["change"] = newestRevision
1295             self.updateOptionDict(details)
1296             try:
1297                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1298             except IOError:
1299                 print "IO error with git fast-import. Is your git version recent enough?"
1300                 print self.gitError.read()
1301
1302         else:
1303             changes = []
1304
1305             if len(self.changesFile) > 0:
1306                 output = open(self.changesFile).readlines()
1307                 changeSet = Set()
1308                 for line in output:
1309                     changeSet.add(int(line))
1310
1311                 for change in changeSet:
1312                     changes.append(change)
1313
1314                 changes.sort()
1315             else:
1316                 if self.verbose:
1317                     print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1318                                                               self.changeRange)
1319                 assert self.depotPaths
1320                 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1321                                                                     for p in self.depotPaths]))
1322
1323                 for line in output:
1324                     changeNum = line.split(" ")[1]
1325                     changes.append(changeNum)
1326
1327                 changes.sort()
1328
1329                 if len(self.maxChanges) > 0:
1330                     changes = changes[:min(int(self.maxChanges), len(changes))]
1331
1332             if len(changes) == 0:
1333                 if not self.silent:
1334                     print "No changes to import!"
1335                 return True
1336
1337             if not self.silent and not self.detectBranches:
1338                 print "Import destination: %s" % self.branch
1339
1340             self.updatedBranches = set()
1341
1342             cnt = 1
1343             for change in changes:
1344                 description = p4Cmd("describe %s" % change)
1345                 self.updateOptionDict(description)
1346
1347                 if not self.silent:
1348                     sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1349                     sys.stdout.flush()
1350                 cnt = cnt + 1
1351
1352                 try:
1353                     if self.detectBranches:
1354                         branches = self.splitFilesIntoBranches(description)
1355                         for branch in branches.keys():
1356                             ## HACK  --hwn
1357                             branchPrefix = self.depotPaths[0] + branch + "/"
1358
1359                             parent = ""
1360
1361                             filesForCommit = branches[branch]
1362
1363                             if self.verbose:
1364                                 print "branch is %s" % branch
1365
1366                             self.updatedBranches.add(branch)
1367
1368                             if branch not in self.createdBranches:
1369                                 self.createdBranches.add(branch)
1370                                 parent = self.knownBranches[branch]
1371                                 if parent == branch:
1372                                     parent = ""
1373                                 elif self.verbose:
1374                                     print "parent determined through known branches: %s" % parent
1375
1376                             # main branch? use master
1377                             if branch == "main":
1378                                 branch = "master"
1379                             else:
1380
1381                                 ## FIXME
1382                                 branch = self.projectName + branch
1383
1384                             if parent == "main":
1385                                 parent = "master"
1386                             elif len(parent) > 0:
1387                                 ## FIXME
1388                                 parent = self.projectName + parent
1389
1390                             branch = self.refPrefix + branch
1391                             if len(parent) > 0:
1392                                 parent = self.refPrefix + parent
1393
1394                             if self.verbose:
1395                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1396
1397                             if len(parent) == 0 and branch in self.initialParents:
1398                                 parent = self.initialParents[branch]
1399                                 del self.initialParents[branch]
1400
1401                             self.commit(description, filesForCommit, branch, [branchPrefix], parent)
1402                     else:
1403                         files = self.extractFilesFromCommit(description)
1404                         self.commit(description, files, self.branch, self.depotPaths,
1405                                     self.initialParent)
1406                         self.initialParent = ""
1407                 except IOError:
1408                     print self.gitError.read()
1409                     sys.exit(1)
1410
1411             if not self.silent:
1412                 print ""
1413                 if len(self.updatedBranches) > 0:
1414                     sys.stdout.write("Updated branches: ")
1415                     for b in self.updatedBranches:
1416                         sys.stdout.write("%s " % b)
1417                     sys.stdout.write("\n")
1418
1419
1420         self.gitStream.close()
1421         if importProcess.wait() != 0:
1422             die("fast-import failed: %s" % self.gitError.read())
1423         self.gitOutput.close()
1424         self.gitError.close()
1425
1426         return True
1427
1428 class P4Rebase(Command):
1429     def __init__(self):
1430         Command.__init__(self)
1431         self.options = [ ]
1432         self.description = ("Fetches the latest revision from perforce and "
1433                             + "rebases the current work (branch) against it")
1434         self.verbose = False
1435
1436     def run(self, args):
1437         sync = P4Sync()
1438         sync.run([])
1439
1440         [upstream, settings] = findUpstreamBranchPoint()
1441         if len(upstream) == 0:
1442             die("Cannot find upstream branchpoint for rebase")
1443
1444         # the branchpoint may be p4/foo~3, so strip off the parent
1445         upstream = re.sub("~[0-9]+$", "", upstream)
1446
1447         print "Rebasing the current branch onto %s" % upstream
1448         oldHead = read_pipe("git rev-parse HEAD").strip()
1449         system("git rebase %s" % upstream)
1450         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1451         return True
1452
1453 class P4Clone(P4Sync):
1454     def __init__(self):
1455         P4Sync.__init__(self)
1456         self.description = "Creates a new git repository and imports from Perforce into it"
1457         self.usage = "usage: %prog [options] //depot/path[@revRange]"
1458         self.options.append(
1459             optparse.make_option("--destination", dest="cloneDestination",
1460                                  action='store', default=None,
1461                                  help="where to leave result of the clone"))
1462         self.cloneDestination = None
1463         self.needsGit = False
1464
1465     def defaultDestination(self, args):
1466         ## TODO: use common prefix of args?
1467         depotPath = args[0]
1468         depotDir = re.sub("(@[^@]*)$", "", depotPath)
1469         depotDir = re.sub("(#[^#]*)$", "", depotDir)
1470         depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1471         depotDir = re.sub(r"/$", "", depotDir)
1472         return os.path.split(depotDir)[1]
1473
1474     def run(self, args):
1475         if len(args) < 1:
1476             return False
1477
1478         if self.keepRepoPath and not self.cloneDestination:
1479             sys.stderr.write("Must specify destination for --keep-path\n")
1480             sys.exit(1)
1481
1482         depotPaths = args
1483
1484         if not self.cloneDestination and len(depotPaths) > 1:
1485             self.cloneDestination = depotPaths[-1]
1486             depotPaths = depotPaths[:-1]
1487
1488         for p in depotPaths:
1489             if not p.startswith("//"):
1490                 return False
1491
1492         if not self.cloneDestination:
1493             self.cloneDestination = self.defaultDestination(args)
1494
1495         print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1496         if not os.path.exists(self.cloneDestination):
1497             os.makedirs(self.cloneDestination)
1498         os.chdir(self.cloneDestination)
1499         system("git init")
1500         self.gitdir = os.getcwd() + "/.git"
1501         if not P4Sync.run(self, depotPaths):
1502             return False
1503         if self.branch != "master":
1504             if gitBranchExists("refs/remotes/p4/master"):
1505                 system("git branch master refs/remotes/p4/master")
1506                 system("git checkout -f")
1507             else:
1508                 print "Could not detect main branch. No checkout/master branch created."
1509
1510         return True
1511
1512 class P4Branches(Command):
1513     def __init__(self):
1514         Command.__init__(self)
1515         self.options = [ ]
1516         self.description = ("Shows the git branches that hold imports and their "
1517                             + "corresponding perforce depot paths")
1518         self.verbose = False
1519
1520     def run(self, args):
1521         cmdline = "git rev-parse --symbolic "
1522         cmdline += " --remotes"
1523
1524         for line in read_pipe_lines(cmdline):
1525             line = line.strip()
1526
1527             if not line.startswith('p4/') or line == "p4/HEAD":
1528                 continue
1529             branch = line
1530
1531             log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
1532             settings = extractSettingsGitLog(log)
1533
1534             print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
1535         return True
1536
1537 class HelpFormatter(optparse.IndentedHelpFormatter):
1538     def __init__(self):
1539         optparse.IndentedHelpFormatter.__init__(self)
1540
1541     def format_description(self, description):
1542         if description:
1543             return description + "\n"
1544         else:
1545             return ""
1546
1547 def printUsage(commands):
1548     print "usage: %s <command> [options]" % sys.argv[0]
1549     print ""
1550     print "valid commands: %s" % ", ".join(commands)
1551     print ""
1552     print "Try %s <command> --help for command specific help." % sys.argv[0]
1553     print ""
1554
1555 commands = {
1556     "debug" : P4Debug,
1557     "submit" : P4Submit,
1558     "sync" : P4Sync,
1559     "rebase" : P4Rebase,
1560     "clone" : P4Clone,
1561     "rollback" : P4RollBack,
1562     "branches" : P4Branches
1563 }
1564
1565
1566 def main():
1567     if len(sys.argv[1:]) == 0:
1568         printUsage(commands.keys())
1569         sys.exit(2)
1570
1571     cmd = ""
1572     cmdName = sys.argv[1]
1573     try:
1574         klass = commands[cmdName]
1575         cmd = klass()
1576     except KeyError:
1577         print "unknown command %s" % cmdName
1578         print ""
1579         printUsage(commands.keys())
1580         sys.exit(2)
1581
1582     options = cmd.options
1583     cmd.gitdir = os.environ.get("GIT_DIR", None)
1584
1585     args = sys.argv[2:]
1586
1587     if len(options) > 0:
1588         options.append(optparse.make_option("--git-dir", dest="gitdir"))
1589
1590         parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1591                                        options,
1592                                        description = cmd.description,
1593                                        formatter = HelpFormatter())
1594
1595         (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1596     global verbose
1597     verbose = cmd.verbose
1598     if cmd.needsGit:
1599         if cmd.gitdir == None:
1600             cmd.gitdir = os.path.abspath(".git")
1601             if not isValidGitDir(cmd.gitdir):
1602                 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1603                 if os.path.exists(cmd.gitdir):
1604                     cdup = read_pipe("git rev-parse --show-cdup").strip()
1605                     if len(cdup) > 0:
1606                         os.chdir(cdup);
1607
1608         if not isValidGitDir(cmd.gitdir):
1609             if isValidGitDir(cmd.gitdir + "/.git"):
1610                 cmd.gitdir += "/.git"
1611             else:
1612                 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1613
1614         os.environ["GIT_DIR"] = cmd.gitdir
1615
1616     if not cmd.run(args):
1617         parser.print_help()
1618
1619
1620 if __name__ == '__main__':
1621     main()