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