Code

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