Code

Detect exec bit in more cases.
[git.git] / contrib / fast-import / git-p4
1 #!/usr/bin/env python
2 #
3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
4 #
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
7 #            2007 Trolltech ASA
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
9 #
11 import optparse, sys, os, marshal, popen2, subprocess, shelve
12 import tempfile, getopt, sha, os.path, time, platform
13 import re
15 from sets import Set;
17 verbose = False
19 def die(msg):
20     if verbose:
21         raise Exception(msg)
22     else:
23         sys.stderr.write(msg + "\n")
24         sys.exit(1)
26 def write_pipe(c, str):
27     if verbose:
28         sys.stderr.write('Writing pipe: %s\n' % c)
30     pipe = os.popen(c, 'w')
31     val = pipe.write(str)
32     if pipe.close():
33         die('Command failed: %s' % c)
35     return val
37 def read_pipe(c, ignore_error=False):
38     if verbose:
39         sys.stderr.write('Reading pipe: %s\n' % c)
41     pipe = os.popen(c, 'rb')
42     val = pipe.read()
43     if pipe.close() and not ignore_error:
44         die('Command failed: %s' % c)
46     return val
49 def read_pipe_lines(c):
50     if verbose:
51         sys.stderr.write('Reading pipe: %s\n' % c)
52     ## todo: check return status
53     pipe = os.popen(c, 'rb')
54     val = pipe.readlines()
55     if pipe.close():
56         die('Command failed: %s' % c)
58     return val
60 def system(cmd):
61     if verbose:
62         sys.stderr.write("executing %s\n" % cmd)
63     if os.system(cmd) != 0:
64         die("command failed: %s" % cmd)
66 def isP4Exec(kind):
67     """Determine if a Perforce 'kind' should have execute permission
69     'p4 help filetypes' gives a list of the types.  If it starts with 'x',
70     or x follows one of a few letters.  Otherwise, if there is an 'x' after
71     a plus sign, it is also executable"""
72     return (re.search(r"(^[cku]?x)|\+.*x", kind) != None)
74 def p4CmdList(cmd, stdin=None, stdin_mode='w+b'):
75     cmd = "p4 -G %s" % cmd
76     if verbose:
77         sys.stderr.write("Opening pipe: %s\n" % cmd)
79     # Use a temporary file to avoid deadlocks without
80     # subprocess.communicate(), which would put another copy
81     # of stdout into memory.
82     stdin_file = None
83     if stdin is not None:
84         stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
85         stdin_file.write(stdin)
86         stdin_file.flush()
87         stdin_file.seek(0)
89     p4 = subprocess.Popen(cmd, shell=True,
90                           stdin=stdin_file,
91                           stdout=subprocess.PIPE)
93     result = []
94     try:
95         while True:
96             entry = marshal.load(p4.stdout)
97             result.append(entry)
98     except EOFError:
99         pass
100     exitCode = p4.wait()
101     if exitCode != 0:
102         entry = {}
103         entry["p4ExitCode"] = exitCode
104         result.append(entry)
106     return result
108 def p4Cmd(cmd):
109     list = p4CmdList(cmd)
110     result = {}
111     for entry in list:
112         result.update(entry)
113     return result;
115 def p4Where(depotPath):
116     if not depotPath.endswith("/"):
117         depotPath += "/"
118     output = p4Cmd("where %s..." % depotPath)
119     if output["code"] == "error":
120         return ""
121     clientPath = ""
122     if "path" in output:
123         clientPath = output.get("path")
124     elif "data" in output:
125         data = output.get("data")
126         lastSpace = data.rfind(" ")
127         clientPath = data[lastSpace + 1:]
129     if clientPath.endswith("..."):
130         clientPath = clientPath[:-3]
131     return clientPath
133 def currentGitBranch():
134     return read_pipe("git name-rev HEAD").split(" ")[1].strip()
136 def isValidGitDir(path):
137     if (os.path.exists(path + "/HEAD")
138         and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
139         return True;
140     return False
142 def parseRevision(ref):
143     return read_pipe("git rev-parse %s" % ref).strip()
145 def extractLogMessageFromGitCommit(commit):
146     logMessage = ""
148     ## fixme: title is first line of commit, not 1st paragraph.
149     foundTitle = False
150     for log in read_pipe_lines("git cat-file commit %s" % commit):
151        if not foundTitle:
152            if len(log) == 1:
153                foundTitle = True
154            continue
156        logMessage += log
157     return logMessage
159 def extractSettingsGitLog(log):
160     values = {}
161     for line in log.split("\n"):
162         line = line.strip()
163         m = re.search (r"^ *\[git-p4: (.*)\]$", line)
164         if not m:
165             continue
167         assignments = m.group(1).split (':')
168         for a in assignments:
169             vals = a.split ('=')
170             key = vals[0].strip()
171             val = ('='.join (vals[1:])).strip()
172             if val.endswith ('\"') and val.startswith('"'):
173                 val = val[1:-1]
175             values[key] = val
177     paths = values.get("depot-paths")
178     if not paths:
179         paths = values.get("depot-path")
180     if paths:
181         values['depot-paths'] = paths.split(',')
182     return values
184 def gitBranchExists(branch):
185     proc = subprocess.Popen(["git", "rev-parse", branch],
186                             stderr=subprocess.PIPE, stdout=subprocess.PIPE);
187     return proc.wait() == 0;
189 def gitConfig(key):
190     return read_pipe("git config %s" % key, ignore_error=True).strip()
192 def p4BranchesInGit(branchesAreInRemotes = True):
193     branches = {}
195     cmdline = "git rev-parse --symbolic "
196     if branchesAreInRemotes:
197         cmdline += " --remotes"
198     else:
199         cmdline += " --branches"
201     for line in read_pipe_lines(cmdline):
202         line = line.strip()
204         ## only import to p4/
205         if not line.startswith('p4/') or line == "p4/HEAD":
206             continue
207         branch = line
209         # strip off p4
210         branch = re.sub ("^p4/", "", line)
212         branches[branch] = parseRevision(line)
213     return branches
215 def findUpstreamBranchPoint(head = "HEAD"):
216     branches = p4BranchesInGit()
217     # map from depot-path to branch name
218     branchByDepotPath = {}
219     for branch in branches.keys():
220         tip = branches[branch]
221         log = extractLogMessageFromGitCommit(tip)
222         settings = extractSettingsGitLog(log)
223         if settings.has_key("depot-paths"):
224             paths = ",".join(settings["depot-paths"])
225             branchByDepotPath[paths] = "remotes/p4/" + branch
227     settings = None
228     parent = 0
229     while parent < 65535:
230         commit = head + "~%s" % parent
231         log = extractLogMessageFromGitCommit(commit)
232         settings = extractSettingsGitLog(log)
233         if settings.has_key("depot-paths"):
234             paths = ",".join(settings["depot-paths"])
235             if branchByDepotPath.has_key(paths):
236                 return [branchByDepotPath[paths], settings]
238         parent = parent + 1
240     return ["", settings]
242 def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
243     if not silent:
244         print ("Creating/updating branch(es) in %s based on origin branch(es)"
245                % localRefPrefix)
247     originPrefix = "origin/p4/"
249     for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
250         line = line.strip()
251         if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
252             continue
254         headName = line[len(originPrefix):]
255         remoteHead = localRefPrefix + headName
256         originHead = line
258         original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
259         if (not original.has_key('depot-paths')
260             or not original.has_key('change')):
261             continue
263         update = False
264         if not gitBranchExists(remoteHead):
265             if verbose:
266                 print "creating %s" % remoteHead
267             update = True
268         else:
269             settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
270             if settings.has_key('change') > 0:
271                 if settings['depot-paths'] == original['depot-paths']:
272                     originP4Change = int(original['change'])
273                     p4Change = int(settings['change'])
274                     if originP4Change > p4Change:
275                         print ("%s (%s) is newer than %s (%s). "
276                                "Updating p4 branch from origin."
277                                % (originHead, originP4Change,
278                                   remoteHead, p4Change))
279                         update = True
280                 else:
281                     print ("Ignoring: %s was imported from %s while "
282                            "%s was imported from %s"
283                            % (originHead, ','.join(original['depot-paths']),
284                               remoteHead, ','.join(settings['depot-paths'])))
286         if update:
287             system("git update-ref %s %s" % (remoteHead, originHead))
289 def originP4BranchesExist():
290         return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
292 class Command:
293     def __init__(self):
294         self.usage = "usage: %prog [options]"
295         self.needsGit = True
297 class P4Debug(Command):
298     def __init__(self):
299         Command.__init__(self)
300         self.options = [
301             optparse.make_option("--verbose", dest="verbose", action="store_true",
302                                  default=False),
303             ]
304         self.description = "A tool to debug the output of p4 -G."
305         self.needsGit = False
306         self.verbose = False
308     def run(self, args):
309         j = 0
310         for output in p4CmdList(" ".join(args)):
311             print 'Element: %d' % j
312             j += 1
313             print output
314         return True
316 class P4RollBack(Command):
317     def __init__(self):
318         Command.__init__(self)
319         self.options = [
320             optparse.make_option("--verbose", dest="verbose", action="store_true"),
321             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
322         ]
323         self.description = "A tool to debug the multi-branch import. Don't use :)"
324         self.verbose = False
325         self.rollbackLocalBranches = False
327     def run(self, args):
328         if len(args) != 1:
329             return False
330         maxChange = int(args[0])
332         if "p4ExitCode" in p4Cmd("changes -m 1"):
333             die("Problems executing p4");
335         if self.rollbackLocalBranches:
336             refPrefix = "refs/heads/"
337             lines = read_pipe_lines("git rev-parse --symbolic --branches")
338         else:
339             refPrefix = "refs/remotes/"
340             lines = read_pipe_lines("git rev-parse --symbolic --remotes")
342         for line in lines:
343             if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
344                 line = line.strip()
345                 ref = refPrefix + line
346                 log = extractLogMessageFromGitCommit(ref)
347                 settings = extractSettingsGitLog(log)
349                 depotPaths = settings['depot-paths']
350                 change = settings['change']
352                 changed = False
354                 if len(p4Cmd("changes -m 1 "  + ' '.join (['%s...@%s' % (p, maxChange)
355                                                            for p in depotPaths]))) == 0:
356                     print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
357                     system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
358                     continue
360                 while change and int(change) > maxChange:
361                     changed = True
362                     if self.verbose:
363                         print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
364                     system("git update-ref %s \"%s^\"" % (ref, ref))
365                     log = extractLogMessageFromGitCommit(ref)
366                     settings =  extractSettingsGitLog(log)
369                     depotPaths = settings['depot-paths']
370                     change = settings['change']
372                 if changed:
373                     print "%s rewound to %s" % (ref, change)
375         return True
377 class P4Submit(Command):
378     def __init__(self):
379         Command.__init__(self)
380         self.options = [
381                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
382                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
383                 optparse.make_option("--origin", dest="origin"),
384                 optparse.make_option("--reset", action="store_true", dest="reset"),
385                 optparse.make_option("--log-substitutions", dest="substFile"),
386                 optparse.make_option("--dry-run", action="store_true"),
387                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
388                 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
389         ]
390         self.description = "Submit changes from git to the perforce depot."
391         self.usage += " [name of git branch to submit into perforce depot]"
392         self.firstTime = True
393         self.reset = False
394         self.interactive = True
395         self.dryRun = False
396         self.substFile = ""
397         self.firstTime = True
398         self.origin = ""
399         self.directSubmit = False
400         self.trustMeLikeAFool = False
401         self.verbose = False
402         self.isWindows = (platform.system() == "Windows")
404         self.logSubstitutions = {}
405         self.logSubstitutions["<enter description here>"] = "%log%"
406         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
408     def check(self):
409         if len(p4CmdList("opened ...")) > 0:
410             die("You have files opened with perforce! Close them before starting the sync.")
412     def start(self):
413         if len(self.config) > 0 and not self.reset:
414             die("Cannot start sync. Previous sync config found at %s\n"
415                 "If you want to start submitting again from scratch "
416                 "maybe you want to call git-p4 submit --reset" % self.configFile)
418         commits = []
419         if self.directSubmit:
420             commits.append("0")
421         else:
422             for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
423                 commits.append(line.strip())
424             commits.reverse()
426         self.config["commits"] = commits
428     def prepareLogMessage(self, template, message):
429         result = ""
431         for line in template.split("\n"):
432             if line.startswith("#"):
433                 result += line + "\n"
434                 continue
436             substituted = False
437             for key in self.logSubstitutions.keys():
438                 if line.find(key) != -1:
439                     value = self.logSubstitutions[key]
440                     value = value.replace("%log%", message)
441                     if value != "@remove@":
442                         result += line.replace(key, value) + "\n"
443                     substituted = True
444                     break
446             if not substituted:
447                 result += line + "\n"
449         return result
451     def prepareSubmitTemplate(self):
452         # remove lines in the Files section that show changes to files outside the depot path we're committing into
453         template = ""
454         inFilesSection = False
455         for line in read_pipe_lines("p4 change -o"):
456             if inFilesSection:
457                 if line.startswith("\t"):
458                     # path starts and ends with a tab
459                     path = line[1:]
460                     lastTab = path.rfind("\t")
461                     if lastTab != -1:
462                         path = path[:lastTab]
463                         if not path.startswith(self.depotPath):
464                             continue
465                 else:
466                     inFilesSection = False
467             else:
468                 if line.startswith("Files:"):
469                     inFilesSection = True
471             template += line
473         return template
475     def applyCommit(self, id):
476         if self.directSubmit:
477             print "Applying local change in working directory/index"
478             diff = self.diffStatus
479         else:
480             print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
481             diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
482         filesToAdd = set()
483         filesToDelete = set()
484         editedFiles = set()
485         for line in diff:
486             modifier = line[0]
487             path = line[1:].strip()
488             if modifier == "M":
489                 system("p4 edit \"%s\"" % path)
490                 editedFiles.add(path)
491             elif modifier == "A":
492                 filesToAdd.add(path)
493                 if path in filesToDelete:
494                     filesToDelete.remove(path)
495             elif modifier == "D":
496                 filesToDelete.add(path)
497                 if path in filesToAdd:
498                     filesToAdd.remove(path)
499             else:
500                 die("unknown modifier %s for %s" % (modifier, path))
502         if self.directSubmit:
503             diffcmd = "cat \"%s\"" % self.diffFile
504         else:
505             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
506         patchcmd = diffcmd + " | git apply "
507         tryPatchCmd = patchcmd + "--check -"
508         applyPatchCmd = patchcmd + "--check --apply -"
510         if os.system(tryPatchCmd) != 0:
511             print "Unfortunately applying the change failed!"
512             print "What do you want to do?"
513             response = "x"
514             while response != "s" and response != "a" and response != "w":
515                 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
516                                      "and with .rej files / [w]rite the patch to a file (patch.txt) ")
517             if response == "s":
518                 print "Skipping! Good luck with the next patches..."
519                 return
520             elif response == "a":
521                 os.system(applyPatchCmd)
522                 if len(filesToAdd) > 0:
523                     print "You may also want to call p4 add on the following files:"
524                     print " ".join(filesToAdd)
525                 if len(filesToDelete):
526                     print "The following files should be scheduled for deletion with p4 delete:"
527                     print " ".join(filesToDelete)
528                 die("Please resolve and submit the conflict manually and "
529                     + "continue afterwards with git-p4 submit --continue")
530             elif response == "w":
531                 system(diffcmd + " > patch.txt")
532                 print "Patch saved to patch.txt in %s !" % self.clientPath
533                 die("Please resolve and submit the conflict manually and "
534                     "continue afterwards with git-p4 submit --continue")
536         system(applyPatchCmd)
538         for f in filesToAdd:
539             system("p4 add \"%s\"" % f)
540         for f in filesToDelete:
541             system("p4 revert \"%s\"" % f)
542             system("p4 delete \"%s\"" % f)
544         logMessage = ""
545         if not self.directSubmit:
546             logMessage = extractLogMessageFromGitCommit(id)
547             logMessage = logMessage.replace("\n", "\n\t")
548             if self.isWindows:
549                 logMessage = logMessage.replace("\n", "\r\n")
550             logMessage = logMessage.strip()
552         template = self.prepareSubmitTemplate()
554         if self.interactive:
555             submitTemplate = self.prepareLogMessage(template, logMessage)
556             diff = read_pipe("p4 diff -du ...")
558             for newFile in filesToAdd:
559                 diff += "==== new file ====\n"
560                 diff += "--- /dev/null\n"
561                 diff += "+++ %s\n" % newFile
562                 f = open(newFile, "r")
563                 for line in f.readlines():
564                     diff += "+" + line
565                 f.close()
567             separatorLine = "######## everything below this line is just the diff #######"
568             if platform.system() == "Windows":
569                 separatorLine += "\r"
570             separatorLine += "\n"
572             response = "e"
573             if self.trustMeLikeAFool:
574                 response = "y"
576             firstIteration = True
577             while response == "e":
578                 if not firstIteration:
579                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
580                 firstIteration = False
581                 if response == "e":
582                     [handle, fileName] = tempfile.mkstemp()
583                     tmpFile = os.fdopen(handle, "w+")
584                     tmpFile.write(submitTemplate + separatorLine + diff)
585                     tmpFile.close()
586                     defaultEditor = "vi"
587                     if platform.system() == "Windows":
588                         defaultEditor = "notepad"
589                     editor = os.environ.get("EDITOR", defaultEditor);
590                     system(editor + " " + fileName)
591                     tmpFile = open(fileName, "rb")
592                     message = tmpFile.read()
593                     tmpFile.close()
594                     os.remove(fileName)
595                     submitTemplate = message[:message.index(separatorLine)]
596                     if self.isWindows:
597                         submitTemplate = submitTemplate.replace("\r\n", "\n")
599             if response == "y" or response == "yes":
600                if self.dryRun:
601                    print submitTemplate
602                    raw_input("Press return to continue...")
603                else:
604                    if self.directSubmit:
605                        print "Submitting to git first"
606                        os.chdir(self.oldWorkingDirectory)
607                        write_pipe("git commit -a -F -", submitTemplate)
608                        os.chdir(self.clientPath)
610                    write_pipe("p4 submit -i", submitTemplate)
611             elif response == "s":
612                 for f in editedFiles:
613                     system("p4 revert \"%s\"" % f);
614                 for f in filesToAdd:
615                     system("p4 revert \"%s\"" % f);
616                     system("rm %s" %f)
617                 for f in filesToDelete:
618                     system("p4 delete \"%s\"" % f);
619                 return
620             else:
621                 print "Not submitting!"
622                 self.interactive = False
623         else:
624             fileName = "submit.txt"
625             file = open(fileName, "w+")
626             file.write(self.prepareLogMessage(template, logMessage))
627             file.close()
628             print ("Perforce submit template written as %s. "
629                    + "Please review/edit and then use p4 submit -i < %s to submit directly!"
630                    % (fileName, fileName))
632     def run(self, args):
633         if len(args) == 0:
634             self.master = currentGitBranch()
635             if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
636                 die("Detecting current git branch failed!")
637         elif len(args) == 1:
638             self.master = args[0]
639         else:
640             return False
642         [upstream, settings] = findUpstreamBranchPoint()
643         self.depotPath = settings['depot-paths'][0]
644         if len(self.origin) == 0:
645             self.origin = upstream
647         if self.verbose:
648             print "Origin branch is " + self.origin
650         if len(self.depotPath) == 0:
651             print "Internal error: cannot locate perforce depot path from existing branches"
652             sys.exit(128)
654         self.clientPath = p4Where(self.depotPath)
656         if len(self.clientPath) == 0:
657             print "Error: Cannot locate perforce checkout of %s in client view" % self.depotPath
658             sys.exit(128)
660         print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
661         self.oldWorkingDirectory = os.getcwd()
663         if self.directSubmit:
664             self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
665             if len(self.diffStatus) == 0:
666                 print "No changes in working directory to submit."
667                 return True
668             patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
669             self.diffFile = self.gitdir + "/p4-git-diff"
670             f = open(self.diffFile, "wb")
671             f.write(patch)
672             f.close();
674         os.chdir(self.clientPath)
675         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
676         if response == "y" or response == "yes":
677             system("p4 sync ...")
679         if self.reset:
680             self.firstTime = True
682         if len(self.substFile) > 0:
683             for line in open(self.substFile, "r").readlines():
684                 tokens = line.strip().split("=")
685                 self.logSubstitutions[tokens[0]] = tokens[1]
687         self.check()
688         self.configFile = self.gitdir + "/p4-git-sync.cfg"
689         self.config = shelve.open(self.configFile, writeback=True)
691         if self.firstTime:
692             self.start()
694         commits = self.config.get("commits", [])
696         while len(commits) > 0:
697             self.firstTime = False
698             commit = commits[0]
699             commits = commits[1:]
700             self.config["commits"] = commits
701             self.applyCommit(commit)
702             if not self.interactive:
703                 break
705         self.config.close()
707         if self.directSubmit:
708             os.remove(self.diffFile)
710         if len(commits) == 0:
711             if self.firstTime:
712                 print "No changes found to apply between %s and current HEAD" % self.origin
713             else:
714                 print "All changes applied!"
715                 os.chdir(self.oldWorkingDirectory)
716                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
717                 if response == "y" or response == "yes":
718                     rebase = P4Rebase()
719                     rebase.run([])
720             os.remove(self.configFile)
722         return True
724 class P4Sync(Command):
725     def __init__(self):
726         Command.__init__(self)
727         self.options = [
728                 optparse.make_option("--branch", dest="branch"),
729                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
730                 optparse.make_option("--changesfile", dest="changesFile"),
731                 optparse.make_option("--silent", dest="silent", action="store_true"),
732                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
733                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
734                 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
735                                      help="Import into refs/heads/ , not refs/remotes"),
736                 optparse.make_option("--max-changes", dest="maxChanges"),
737                 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
738                                      help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
739         ]
740         self.description = """Imports from Perforce into a git repository.\n
741     example:
742     //depot/my/project/ -- to import the current head
743     //depot/my/project/@all -- to import everything
744     //depot/my/project/@1,6 -- to import only from revision 1 to 6
746     (a ... is not needed in the path p4 specification, it's added implicitly)"""
748         self.usage += " //depot/path[@revRange]"
749         self.silent = False
750         self.createdBranches = Set()
751         self.committedChanges = Set()
752         self.branch = ""
753         self.detectBranches = False
754         self.detectLabels = False
755         self.changesFile = ""
756         self.syncWithOrigin = True
757         self.verbose = False
758         self.importIntoRemotes = True
759         self.maxChanges = ""
760         self.isWindows = (platform.system() == "Windows")
761         self.keepRepoPath = False
762         self.depotPaths = None
763         self.p4BranchesInGit = []
765         if gitConfig("git-p4.syncFromOrigin") == "false":
766             self.syncWithOrigin = False
768     def extractFilesFromCommit(self, commit):
769         files = []
770         fnum = 0
771         while commit.has_key("depotFile%s" % fnum):
772             path =  commit["depotFile%s" % fnum]
774             found = [p for p in self.depotPaths
775                      if path.startswith (p)]
776             if not found:
777                 fnum = fnum + 1
778                 continue
780             file = {}
781             file["path"] = path
782             file["rev"] = commit["rev%s" % fnum]
783             file["action"] = commit["action%s" % fnum]
784             file["type"] = commit["type%s" % fnum]
785             files.append(file)
786             fnum = fnum + 1
787         return files
789     def stripRepoPath(self, path, prefixes):
790         if self.keepRepoPath:
791             prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
793         for p in prefixes:
794             if path.startswith(p):
795                 path = path[len(p):]
797         return path
799     def splitFilesIntoBranches(self, commit):
800         branches = {}
801         fnum = 0
802         while commit.has_key("depotFile%s" % fnum):
803             path =  commit["depotFile%s" % fnum]
804             found = [p for p in self.depotPaths
805                      if path.startswith (p)]
806             if not found:
807                 fnum = fnum + 1
808                 continue
810             file = {}
811             file["path"] = path
812             file["rev"] = commit["rev%s" % fnum]
813             file["action"] = commit["action%s" % fnum]
814             file["type"] = commit["type%s" % fnum]
815             fnum = fnum + 1
817             relPath = self.stripRepoPath(path, self.depotPaths)
819             for branch in self.knownBranches.keys():
821                 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
822                 if relPath.startswith(branch + "/"):
823                     if branch not in branches:
824                         branches[branch] = []
825                     branches[branch].append(file)
826                     break
828         return branches
830     ## Should move this out, doesn't use SELF.
831     def readP4Files(self, files):
832         files = [f for f in files
833                  if f['action'] != 'delete']
835         if not files:
836             return
838         filedata = p4CmdList('-x - print',
839                              stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
840                                               for f in files]),
841                              stdin_mode='w+')
842         if "p4ExitCode" in filedata[0]:
843             die("Problems executing p4. Error: [%d]."
844                 % (filedata[0]['p4ExitCode']));
846         j = 0;
847         contents = {}
848         while j < len(filedata):
849             stat = filedata[j]
850             j += 1
851             text = ''
852             while j < len(filedata) and filedata[j]['code'] in ('text',
853                                                                 'binary'):
854                 text += filedata[j]['data']
855                 j += 1
858             if not stat.has_key('depotFile'):
859                 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
860                 continue
862             contents[stat['depotFile']] = text
864         for f in files:
865             assert not f.has_key('data')
866             f['data'] = contents[f['path']]
868     def commit(self, details, files, branch, branchPrefixes, parent = ""):
869         epoch = details["time"]
870         author = details["user"]
872         if self.verbose:
873             print "commit into %s" % branch
875         # start with reading files; if that fails, we should not
876         # create a commit.
877         new_files = []
878         for f in files:
879             if [p for p in branchPrefixes if f['path'].startswith(p)]:
880                 new_files.append (f)
881             else:
882                 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
883         files = new_files
884         self.readP4Files(files)
889         self.gitStream.write("commit %s\n" % branch)
890 #        gitStream.write("mark :%s\n" % details["change"])
891         self.committedChanges.add(int(details["change"]))
892         committer = ""
893         if author not in self.users:
894             self.getUserMapFromPerforceServer()
895         if author in self.users:
896             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
897         else:
898             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
900         self.gitStream.write("committer %s\n" % committer)
902         self.gitStream.write("data <<EOT\n")
903         self.gitStream.write(details["desc"])
904         self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
905                              % (','.join (branchPrefixes), details["change"]))
906         if len(details['options']) > 0:
907             self.gitStream.write(": options = %s" % details['options'])
908         self.gitStream.write("]\nEOT\n\n")
910         if len(parent) > 0:
911             if self.verbose:
912                 print "parent %s" % parent
913             self.gitStream.write("from %s\n" % parent)
915         for file in files:
916             if file["type"] == "apple":
917                 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
918                 continue
920             relPath = self.stripRepoPath(file['path'], branchPrefixes)
921             if file["action"] == "delete":
922                 self.gitStream.write("D %s\n" % relPath)
923             else:
924                 data = file['data']
926                 mode = "644"
927                 if isP4Exec(file["type"]):
928                     mode = "755"
929                 elif file["type"] == "symlink":
930                     mode = "120000"
931                     # p4 print on a symlink contains "target\n", so strip it off
932                     data = data[:-1]
934                 if self.isWindows and file["type"].endswith("text"):
935                     data = data.replace("\r\n", "\n")
937                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
938                 self.gitStream.write("data %s\n" % len(data))
939                 self.gitStream.write(data)
940                 self.gitStream.write("\n")
942         self.gitStream.write("\n")
944         change = int(details["change"])
946         if self.labels.has_key(change):
947             label = self.labels[change]
948             labelDetails = label[0]
949             labelRevisions = label[1]
950             if self.verbose:
951                 print "Change %s is labelled %s" % (change, labelDetails)
953             files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
954                                                     for p in branchPrefixes]))
956             if len(files) == len(labelRevisions):
958                 cleanedFiles = {}
959                 for info in files:
960                     if info["action"] == "delete":
961                         continue
962                     cleanedFiles[info["depotFile"]] = info["rev"]
964                 if cleanedFiles == labelRevisions:
965                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
966                     self.gitStream.write("from %s\n" % branch)
968                     owner = labelDetails["Owner"]
969                     tagger = ""
970                     if author in self.users:
971                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
972                     else:
973                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
974                     self.gitStream.write("tagger %s\n" % tagger)
975                     self.gitStream.write("data <<EOT\n")
976                     self.gitStream.write(labelDetails["Description"])
977                     self.gitStream.write("EOT\n\n")
979                 else:
980                     if not self.silent:
981                         print ("Tag %s does not match with change %s: files do not match."
982                                % (labelDetails["label"], change))
984             else:
985                 if not self.silent:
986                     print ("Tag %s does not match with change %s: file count is different."
987                            % (labelDetails["label"], change))
989     def getUserCacheFilename(self):
990         home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
991         return home + "/.gitp4-usercache.txt"
993     def getUserMapFromPerforceServer(self):
994         if self.userMapFromPerforceServer:
995             return
996         self.users = {}
998         for output in p4CmdList("users"):
999             if not output.has_key("User"):
1000                 continue
1001             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
1004         s = ''
1005         for (key, val) in self.users.items():
1006             s += "%s\t%s\n" % (key, val)
1008         open(self.getUserCacheFilename(), "wb").write(s)
1009         self.userMapFromPerforceServer = True
1011     def loadUserMapFromCache(self):
1012         self.users = {}
1013         self.userMapFromPerforceServer = False
1014         try:
1015             cache = open(self.getUserCacheFilename(), "rb")
1016             lines = cache.readlines()
1017             cache.close()
1018             for line in lines:
1019                 entry = line.strip().split("\t")
1020                 self.users[entry[0]] = entry[1]
1021         except IOError:
1022             self.getUserMapFromPerforceServer()
1024     def getLabels(self):
1025         self.labels = {}
1027         l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
1028         if len(l) > 0 and not self.silent:
1029             print "Finding files belonging to labels in %s" % `self.depotPath`
1031         for output in l:
1032             label = output["label"]
1033             revisions = {}
1034             newestChange = 0
1035             if self.verbose:
1036                 print "Querying files for label %s" % label
1037             for file in p4CmdList("files "
1038                                   +  ' '.join (["%s...@%s" % (p, label)
1039                                                 for p in self.depotPaths])):
1040                 revisions[file["depotFile"]] = file["rev"]
1041                 change = int(file["change"])
1042                 if change > newestChange:
1043                     newestChange = change
1045             self.labels[newestChange] = [output, revisions]
1047         if self.verbose:
1048             print "Label changes: %s" % self.labels.keys()
1050     def guessProjectName(self):
1051         for p in self.depotPaths:
1052             if p.endswith("/"):
1053                 p = p[:-1]
1054             p = p[p.strip().rfind("/") + 1:]
1055             if not p.endswith("/"):
1056                p += "/"
1057             return p
1059     def getBranchMapping(self):
1060         lostAndFoundBranches = set()
1062         for info in p4CmdList("branches"):
1063             details = p4Cmd("branch -o %s" % info["branch"])
1064             viewIdx = 0
1065             while details.has_key("View%s" % viewIdx):
1066                 paths = details["View%s" % viewIdx].split(" ")
1067                 viewIdx = viewIdx + 1
1068                 # require standard //depot/foo/... //depot/bar/... mapping
1069                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
1070                     continue
1071                 source = paths[0]
1072                 destination = paths[1]
1073                 ## HACK
1074                 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
1075                     source = source[len(self.depotPaths[0]):-4]
1076                     destination = destination[len(self.depotPaths[0]):-4]
1078                     if destination in self.knownBranches:
1079                         if not self.silent:
1080                             print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
1081                             print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
1082                         continue
1084                     self.knownBranches[destination] = source
1086                     lostAndFoundBranches.discard(destination)
1088                     if source not in self.knownBranches:
1089                         lostAndFoundBranches.add(source)
1092         for branch in lostAndFoundBranches:
1093             self.knownBranches[branch] = branch
1095     def listExistingP4GitBranches(self):
1096         # branches holds mapping from name to commit
1097         branches = p4BranchesInGit(self.importIntoRemotes)
1098         self.p4BranchesInGit = branches.keys()
1099         for branch in branches.keys():
1100             self.initialParents[self.refPrefix + branch] = branches[branch]
1102     def updateOptionDict(self, d):
1103         option_keys = {}
1104         if self.keepRepoPath:
1105             option_keys['keepRepoPath'] = 1
1107         d["options"] = ' '.join(sorted(option_keys.keys()))
1109     def readOptions(self, d):
1110         self.keepRepoPath = (d.has_key('options')
1111                              and ('keepRepoPath' in d['options']))
1113     def run(self, args):
1114         self.depotPaths = []
1115         self.changeRange = ""
1116         self.initialParent = ""
1117         self.previousDepotPaths = []
1119         # map from branch depot path to parent branch
1120         self.knownBranches = {}
1121         self.initialParents = {}
1122         self.hasOrigin = originP4BranchesExist()
1123         if not self.syncWithOrigin:
1124             self.hasOrigin = False
1126         if self.importIntoRemotes:
1127             self.refPrefix = "refs/remotes/p4/"
1128         else:
1129             self.refPrefix = "refs/heads/p4/"
1131         if self.syncWithOrigin and self.hasOrigin:
1132             if not self.silent:
1133                 print "Syncing with origin first by calling git fetch origin"
1134             system("git fetch origin")
1136         if len(self.branch) == 0:
1137             self.branch = self.refPrefix + "master"
1138             if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1139                 system("git update-ref %s refs/heads/p4" % self.branch)
1140                 system("git branch -D p4");
1141             # create it /after/ importing, when master exists
1142             if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes and gitBranchExists(self.branch):
1143                 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1145         # TODO: should always look at previous commits,
1146         # merge with previous imports, if possible.
1147         if args == []:
1148             if self.hasOrigin:
1149                 createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
1150             self.listExistingP4GitBranches()
1152             if len(self.p4BranchesInGit) > 1:
1153                 if not self.silent:
1154                     print "Importing from/into multiple branches"
1155                 self.detectBranches = True
1157             if self.verbose:
1158                 print "branches: %s" % self.p4BranchesInGit
1160             p4Change = 0
1161             for branch in self.p4BranchesInGit:
1162                 logMsg =  extractLogMessageFromGitCommit(self.refPrefix + branch)
1164                 settings = extractSettingsGitLog(logMsg)
1166                 self.readOptions(settings)
1167                 if (settings.has_key('depot-paths')
1168                     and settings.has_key ('change')):
1169                     change = int(settings['change']) + 1
1170                     p4Change = max(p4Change, change)
1172                     depotPaths = sorted(settings['depot-paths'])
1173                     if self.previousDepotPaths == []:
1174                         self.previousDepotPaths = depotPaths
1175                     else:
1176                         paths = []
1177                         for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1178                             for i in range(0, min(len(cur), len(prev))):
1179                                 if cur[i] <> prev[i]:
1180                                     i = i - 1
1181                                     break
1183                             paths.append (cur[:i + 1])
1185                         self.previousDepotPaths = paths
1187             if p4Change > 0:
1188                 self.depotPaths = sorted(self.previousDepotPaths)
1189                 self.changeRange = "@%s,#head" % p4Change
1190                 if not self.detectBranches:
1191                     self.initialParent = parseRevision(self.branch)
1192                 if not self.silent and not self.detectBranches:
1193                     print "Performing incremental import into %s git branch" % self.branch
1195         if not self.branch.startswith("refs/"):
1196             self.branch = "refs/heads/" + self.branch
1198         if len(args) == 0 and self.depotPaths:
1199             if not self.silent:
1200                 print "Depot paths: %s" % ' '.join(self.depotPaths)
1201         else:
1202             if self.depotPaths and self.depotPaths != args:
1203                 print ("previous import used depot path %s and now %s was specified. "
1204                        "This doesn't work!" % (' '.join (self.depotPaths),
1205                                                ' '.join (args)))
1206                 sys.exit(1)
1208             self.depotPaths = sorted(args)
1210         self.revision = ""
1211         self.users = {}
1213         newPaths = []
1214         for p in self.depotPaths:
1215             if p.find("@") != -1:
1216                 atIdx = p.index("@")
1217                 self.changeRange = p[atIdx:]
1218                 if self.changeRange == "@all":
1219                     self.changeRange = ""
1220                 elif ',' not in self.changeRange:
1221                     self.revision = self.changeRange
1222                     self.changeRange = ""
1223                 p = p[:atIdx]
1224             elif p.find("#") != -1:
1225                 hashIdx = p.index("#")
1226                 self.revision = p[hashIdx:]
1227                 p = p[:hashIdx]
1228             elif self.previousDepotPaths == []:
1229                 self.revision = "#head"
1231             p = re.sub ("\.\.\.$", "", p)
1232             if not p.endswith("/"):
1233                 p += "/"
1235             newPaths.append(p)
1237         self.depotPaths = newPaths
1240         self.loadUserMapFromCache()
1241         self.labels = {}
1242         if self.detectLabels:
1243             self.getLabels();
1245         if self.detectBranches:
1246             ## FIXME - what's a P4 projectName ?
1247             self.projectName = self.guessProjectName()
1249             if not self.hasOrigin:
1250                 self.getBranchMapping();
1251             if self.verbose:
1252                 print "p4-git branches: %s" % self.p4BranchesInGit
1253                 print "initial parents: %s" % self.initialParents
1254             for b in self.p4BranchesInGit:
1255                 if b != "master":
1257                     ## FIXME
1258                     b = b[len(self.projectName):]
1259                 self.createdBranches.add(b)
1261         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1263         importProcess = subprocess.Popen(["git", "fast-import"],
1264                                          stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1265                                          stderr=subprocess.PIPE);
1266         self.gitOutput = importProcess.stdout
1267         self.gitStream = importProcess.stdin
1268         self.gitError = importProcess.stderr
1270         if self.revision:
1271             print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), self.revision, self.branch)
1273             details = { "user" : "git perforce import user", "time" : int(time.time()) }
1274             details["desc"] = ("Initial import of %s from the state at revision %s"
1275                                % (' '.join(self.depotPaths), self.revision))
1276             details["change"] = self.revision
1277             newestRevision = 0
1279             fileCnt = 0
1280             for info in p4CmdList("files "
1281                                   +  ' '.join(["%s...%s"
1282                                                % (p, self.revision)
1283                                                for p in self.depotPaths])):
1285                 if info['code'] == 'error':
1286                     sys.stderr.write("p4 returned an error: %s\n"
1287                                      % info['data'])
1288                     sys.exit(1)
1291                 change = int(info["change"])
1292                 if change > newestRevision:
1293                     newestRevision = change
1295                 if info["action"] == "delete":
1296                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1297                     #fileCnt = fileCnt + 1
1298                     continue
1300                 for prop in ["depotFile", "rev", "action", "type" ]:
1301                     details["%s%s" % (prop, fileCnt)] = info[prop]
1303                 fileCnt = fileCnt + 1
1305             details["change"] = newestRevision
1306             self.updateOptionDict(details)
1307             try:
1308                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1309             except IOError:
1310                 print "IO error with git fast-import. Is your git version recent enough?"
1311                 print self.gitError.read()
1313         else:
1314             changes = []
1316             if len(self.changesFile) > 0:
1317                 output = open(self.changesFile).readlines()
1318                 changeSet = Set()
1319                 for line in output:
1320                     changeSet.add(int(line))
1322                 for change in changeSet:
1323                     changes.append(change)
1325                 changes.sort()
1326             else:
1327                 if self.verbose:
1328                     print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1329                                                               self.changeRange)
1330                 assert self.depotPaths
1331                 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1332                                                                     for p in self.depotPaths]))
1334                 for line in output:
1335                     changeNum = line.split(" ")[1]
1336                     changes.append(int(changeNum))
1338                 changes.sort()
1340                 if len(self.maxChanges) > 0:
1341                     changes = changes[:min(int(self.maxChanges), len(changes))]
1343             if len(changes) == 0:
1344                 if not self.silent:
1345                     print "No changes to import!"
1346                 return True
1348             if not self.silent and not self.detectBranches:
1349                 print "Import destination: %s" % self.branch
1351             self.updatedBranches = set()
1353             cnt = 1
1354             for change in changes:
1355                 description = p4Cmd("describe %s" % change)
1356                 self.updateOptionDict(description)
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
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 + "/"
1370                             parent = ""
1372                             filesForCommit = branches[branch]
1374                             if self.verbose:
1375                                 print "branch is %s" % branch
1377                             self.updatedBranches.add(branch)
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
1387                             # main branch? use master
1388                             if branch == "main":
1389                                 branch = "master"
1390                             else:
1392                                 ## FIXME
1393                                 branch = self.projectName + branch
1395                             if parent == "main":
1396                                 parent = "master"
1397                             elif len(parent) > 0:
1398                                 ## FIXME
1399                                 parent = self.projectName + parent
1401                             branch = self.refPrefix + branch
1402                             if len(parent) > 0:
1403                                 parent = self.refPrefix + parent
1405                             if self.verbose:
1406                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1408                             if len(parent) == 0 and branch in self.initialParents:
1409                                 parent = self.initialParents[branch]
1410                                 del self.initialParents[branch]
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)
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")
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()
1437         return True
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
1447     def run(self, args):
1448         sync = P4Sync()
1449         sync.run([])
1451         [upstream, settings] = findUpstreamBranchPoint()
1452         if len(upstream) == 0:
1453             die("Cannot find upstream branchpoint for rebase")
1455         # the branchpoint may be p4/foo~3, so strip off the parent
1456         upstream = re.sub("~[0-9]+$", "", upstream)
1458         print "Rebasing the current branch onto %s" % upstream
1459         oldHead = read_pipe("git rev-parse HEAD").strip()
1460         system("git rebase %s" % upstream)
1461         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1462         return True
1464 class P4Clone(P4Sync):
1465     def __init__(self):
1466         P4Sync.__init__(self)
1467         self.description = "Creates a new git repository and imports from Perforce into it"
1468         self.usage = "usage: %prog [options] //depot/path[@revRange]"
1469         self.options.append(
1470             optparse.make_option("--destination", dest="cloneDestination",
1471                                  action='store', default=None,
1472                                  help="where to leave result of the clone"))
1473         self.cloneDestination = None
1474         self.needsGit = False
1476     def defaultDestination(self, args):
1477         ## TODO: use common prefix of args?
1478         depotPath = args[0]
1479         depotDir = re.sub("(@[^@]*)$", "", depotPath)
1480         depotDir = re.sub("(#[^#]*)$", "", depotDir)
1481         depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1482         depotDir = re.sub(r"/$", "", depotDir)
1483         return os.path.split(depotDir)[1]
1485     def run(self, args):
1486         if len(args) < 1:
1487             return False
1489         if self.keepRepoPath and not self.cloneDestination:
1490             sys.stderr.write("Must specify destination for --keep-path\n")
1491             sys.exit(1)
1493         depotPaths = args
1495         if not self.cloneDestination and len(depotPaths) > 1:
1496             self.cloneDestination = depotPaths[-1]
1497             depotPaths = depotPaths[:-1]
1499         for p in depotPaths:
1500             if not p.startswith("//"):
1501                 return False
1503         if not self.cloneDestination:
1504             self.cloneDestination = self.defaultDestination(args)
1506         print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1507         if not os.path.exists(self.cloneDestination):
1508             os.makedirs(self.cloneDestination)
1509         os.chdir(self.cloneDestination)
1510         system("git init")
1511         self.gitdir = os.getcwd() + "/.git"
1512         if not P4Sync.run(self, depotPaths):
1513             return False
1514         if self.branch != "master":
1515             if gitBranchExists("refs/remotes/p4/master"):
1516                 system("git branch master refs/remotes/p4/master")
1517                 system("git checkout -f")
1518             else:
1519                 print "Could not detect main branch. No checkout/master branch created."
1521         return True
1523 class P4Branches(Command):
1524     def __init__(self):
1525         Command.__init__(self)
1526         self.options = [ ]
1527         self.description = ("Shows the git branches that hold imports and their "
1528                             + "corresponding perforce depot paths")
1529         self.verbose = False
1531     def run(self, args):
1532         if originP4BranchesExist():
1533             createOrUpdateBranchesFromOrigin()
1535         cmdline = "git rev-parse --symbolic "
1536         cmdline += " --remotes"
1538         for line in read_pipe_lines(cmdline):
1539             line = line.strip()
1541             if not line.startswith('p4/') or line == "p4/HEAD":
1542                 continue
1543             branch = line
1545             log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
1546             settings = extractSettingsGitLog(log)
1548             print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
1549         return True
1551 class HelpFormatter(optparse.IndentedHelpFormatter):
1552     def __init__(self):
1553         optparse.IndentedHelpFormatter.__init__(self)
1555     def format_description(self, description):
1556         if description:
1557             return description + "\n"
1558         else:
1559             return ""
1561 def printUsage(commands):
1562     print "usage: %s <command> [options]" % sys.argv[0]
1563     print ""
1564     print "valid commands: %s" % ", ".join(commands)
1565     print ""
1566     print "Try %s <command> --help for command specific help." % sys.argv[0]
1567     print ""
1569 commands = {
1570     "debug" : P4Debug,
1571     "submit" : P4Submit,
1572     "sync" : P4Sync,
1573     "rebase" : P4Rebase,
1574     "clone" : P4Clone,
1575     "rollback" : P4RollBack,
1576     "branches" : P4Branches
1580 def main():
1581     if len(sys.argv[1:]) == 0:
1582         printUsage(commands.keys())
1583         sys.exit(2)
1585     cmd = ""
1586     cmdName = sys.argv[1]
1587     try:
1588         klass = commands[cmdName]
1589         cmd = klass()
1590     except KeyError:
1591         print "unknown command %s" % cmdName
1592         print ""
1593         printUsage(commands.keys())
1594         sys.exit(2)
1596     options = cmd.options
1597     cmd.gitdir = os.environ.get("GIT_DIR", None)
1599     args = sys.argv[2:]
1601     if len(options) > 0:
1602         options.append(optparse.make_option("--git-dir", dest="gitdir"))
1604         parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1605                                        options,
1606                                        description = cmd.description,
1607                                        formatter = HelpFormatter())
1609         (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1610     global verbose
1611     verbose = cmd.verbose
1612     if cmd.needsGit:
1613         if cmd.gitdir == None:
1614             cmd.gitdir = os.path.abspath(".git")
1615             if not isValidGitDir(cmd.gitdir):
1616                 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1617                 if os.path.exists(cmd.gitdir):
1618                     cdup = read_pipe("git rev-parse --show-cdup").strip()
1619                     if len(cdup) > 0:
1620                         os.chdir(cdup);
1622         if not isValidGitDir(cmd.gitdir):
1623             if isValidGitDir(cmd.gitdir + "/.git"):
1624                 cmd.gitdir += "/.git"
1625             else:
1626                 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1628         os.environ["GIT_DIR"] = cmd.gitdir
1630     if not cmd.run(args):
1631         parser.print_help()
1634 if __name__ == '__main__':
1635     main()