Code

Make sure all popen calls use binary mode (for Windows) and
[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 <hausmann@kde.org>
6 # Copyright: 2007 Simon Hausmann <hausmann@kde.org>
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
13 from sets import Set;
15 gitdir = os.environ.get("GIT_DIR", "")
17 def mypopen(command):
18     return os.popen(command, "rb");
20 def p4CmdList(cmd):
21     cmd = "p4 -G %s" % cmd
22     pipe = os.popen(cmd, "rb")
24     result = []
25     try:
26         while True:
27             entry = marshal.load(pipe)
28             result.append(entry)
29     except EOFError:
30         pass
31     pipe.close()
33     return result
35 def p4Cmd(cmd):
36     list = p4CmdList(cmd)
37     result = {}
38     for entry in list:
39         result.update(entry)
40     return result;
42 def p4Where(depotPath):
43     if not depotPath.endswith("/"):
44         depotPath += "/"
45     output = p4Cmd("where %s..." % depotPath)
46     clientPath = ""
47     if "path" in output:
48         clientPath = output.get("path")
49     elif "data" in output:
50         data = output.get("data")
51         lastSpace = data.rfind(" ")
52         clientPath = data[lastSpace + 1:]
54     if clientPath.endswith("..."):
55         clientPath = clientPath[:-3]
56     return clientPath
58 def die(msg):
59     sys.stderr.write(msg + "\n")
60     sys.exit(1)
62 def currentGitBranch():
63     return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
65 def isValidGitDir(path):
66     if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
67         return True;
68     return False
70 def system(cmd):
71     if os.system(cmd) != 0:
72         die("command failed: %s" % cmd)
74 def extractLogMessageFromGitCommit(commit):
75     logMessage = ""
76     foundTitle = False
77     for log in mypopen("git cat-file commit %s" % commit).readlines():
78        if not foundTitle:
79            if len(log) == 1:
80                foundTitle = True
81            continue
83        logMessage += log
84     return logMessage
86 def extractDepotPathAndChangeFromGitLog(log):
87     values = {}
88     for line in log.split("\n"):
89         line = line.strip()
90         if line.startswith("[git-p4:") and line.endswith("]"):
91             line = line[8:-1].strip()
92             for assignment in line.split(":"):
93                 variable = assignment.strip()
94                 value = ""
95                 equalPos = assignment.find("=")
96                 if equalPos != -1:
97                     variable = assignment[:equalPos].strip()
98                     value = assignment[equalPos + 1:].strip()
99                     if value.startswith("\"") and value.endswith("\""):
100                         value = value[1:-1]
101                 values[variable] = value
103     return values.get("depot-path"), values.get("change")
105 def gitBranchExists(branch):
106     proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
107     return proc.wait() == 0;
109 class Command:
110     def __init__(self):
111         self.usage = "usage: %prog [options]"
112         self.needsGit = True
114 class P4Debug(Command):
115     def __init__(self):
116         Command.__init__(self)
117         self.options = [
118         ]
119         self.description = "A tool to debug the output of p4 -G."
120         self.needsGit = False
122     def run(self, args):
123         for output in p4CmdList(" ".join(args)):
124             print output
125         return True
127 class P4CleanTags(Command):
128     def __init__(self):
129         Command.__init__(self)
130         self.options = [
131 #                optparse.make_option("--branch", dest="branch", default="refs/heads/master")
132         ]
133         self.description = "A tool to remove stale unused tags from incremental perforce imports."
134     def run(self, args):
135         branch = currentGitBranch()
136         print "Cleaning out stale p4 import tags..."
137         sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % branch)
138         output = sout.read()
139         try:
140             tagIdx = output.index(" tags/p4/")
141         except:
142             print "Cannot find any p4/* tag. Nothing to do."
143             sys.exit(0)
145         try:
146             caretIdx = output.index("^")
147         except:
148             caretIdx = len(output) - 1
149         rev = int(output[tagIdx + 9 : caretIdx])
151         allTags = mypopen("git tag -l p4/").readlines()
152         for i in range(len(allTags)):
153             allTags[i] = int(allTags[i][3:-1])
155         allTags.sort()
157         allTags.remove(rev)
159         for rev in allTags:
160             print mypopen("git tag -d p4/%s" % rev).read()
162         print "%s tags removed." % len(allTags)
163         return True
165 class P4Submit(Command):
166     def __init__(self):
167         Command.__init__(self)
168         self.options = [
169                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
170                 optparse.make_option("--origin", dest="origin"),
171                 optparse.make_option("--reset", action="store_true", dest="reset"),
172                 optparse.make_option("--log-substitutions", dest="substFile"),
173                 optparse.make_option("--noninteractive", action="store_false"),
174                 optparse.make_option("--dry-run", action="store_true"),
175         ]
176         self.description = "Submit changes from git to the perforce depot."
177         self.usage += " [name of git branch to submit into perforce depot]"
178         self.firstTime = True
179         self.reset = False
180         self.interactive = True
181         self.dryRun = False
182         self.substFile = ""
183         self.firstTime = True
184         self.origin = ""
186         self.logSubstitutions = {}
187         self.logSubstitutions["<enter description here>"] = "%log%"
188         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
190     def check(self):
191         if len(p4CmdList("opened ...")) > 0:
192             die("You have files opened with perforce! Close them before starting the sync.")
194     def start(self):
195         if len(self.config) > 0 and not self.reset:
196             die("Cannot start sync. Previous sync config found at %s" % self.configFile)
198         commits = []
199         for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
200             commits.append(line[:-1])
201         commits.reverse()
203         self.config["commits"] = commits
205     def prepareLogMessage(self, template, message):
206         result = ""
208         for line in template.split("\n"):
209             if line.startswith("#"):
210                 result += line + "\n"
211                 continue
213             substituted = False
214             for key in self.logSubstitutions.keys():
215                 if line.find(key) != -1:
216                     value = self.logSubstitutions[key]
217                     value = value.replace("%log%", message)
218                     if value != "@remove@":
219                         result += line.replace(key, value) + "\n"
220                     substituted = True
221                     break
223             if not substituted:
224                 result += line + "\n"
226         return result
228     def apply(self, id):
229         print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
230         diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
231         filesToAdd = set()
232         filesToDelete = set()
233         for line in diff:
234             modifier = line[0]
235             path = line[1:].strip()
236             if modifier == "M":
237                 system("p4 edit %s" % path)
238             elif modifier == "A":
239                 filesToAdd.add(path)
240                 if path in filesToDelete:
241                     filesToDelete.remove(path)
242             elif modifier == "D":
243                 filesToDelete.add(path)
244                 if path in filesToAdd:
245                     filesToAdd.remove(path)
246             else:
247                 die("unknown modifier %s for %s" % (modifier, path))
249         diffcmd = "git diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\"" % (id, id)
250         patchcmd = diffcmd + " | patch -p1"
252         if os.system(patchcmd + " --dry-run --silent") != 0:
253             print "Unfortunately applying the change failed!"
254             print "What do you want to do?"
255             response = "x"
256             while response != "s" and response != "a" and response != "w":
257                 response = raw_input("[s]kip this patch / [a]pply the patch forcibly and with .rej files / [w]rite the patch to a file (patch.txt) ")
258             if response == "s":
259                 print "Skipping! Good luck with the next patches..."
260                 return
261             elif response == "a":
262                 os.system(patchcmd)
263                 if len(filesToAdd) > 0:
264                     print "You may also want to call p4 add on the following files:"
265                     print " ".join(filesToAdd)
266                 if len(filesToDelete):
267                     print "The following files should be scheduled for deletion with p4 delete:"
268                     print " ".join(filesToDelete)
269                 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
270             elif response == "w":
271                 system(diffcmd + " > patch.txt")
272                 print "Patch saved to patch.txt in %s !" % self.clientPath
273                 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
275         system(patchcmd)
277         for f in filesToAdd:
278             system("p4 add %s" % f)
279         for f in filesToDelete:
280             system("p4 revert %s" % f)
281             system("p4 delete %s" % f)
283         logMessage = extractLogMessageFromGitCommit(id)
284         logMessage = logMessage.replace("\n", "\n\t")
285         logMessage = logMessage[:-1]
287         template = mypopen("p4 change -o").read()
289         if self.interactive:
290             submitTemplate = self.prepareLogMessage(template, logMessage)
291             diff = mypopen("p4 diff -du ...").read()
293             for newFile in filesToAdd:
294                 diff += "==== new file ====\n"
295                 diff += "--- /dev/null\n"
296                 diff += "+++ %s\n" % newFile
297                 f = open(newFile, "r")
298                 for line in f.readlines():
299                     diff += "+" + line
300                 f.close()
302             separatorLine = "######## everything below this line is just the diff #######\n"
304             response = "e"
305             firstIteration = True
306             while response == "e":
307                 if not firstIteration:
308                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o  ")
309                 firstIteration = False
310                 if response == "e":
311                     [handle, fileName] = tempfile.mkstemp()
312                     tmpFile = os.fdopen(handle, "w+")
313                     tmpFile.write(submitTemplate + separatorLine + diff)
314                     tmpFile.close()
315                     editor = os.environ.get("EDITOR", "vi")
316                     system(editor + " " + fileName)
317                     tmpFile = open(fileName, "r")
318                     message = tmpFile.read()
319                     tmpFile.close()
320                     os.remove(fileName)
321                     submitTemplate = message[:message.index(separatorLine)]
323             if response == "y" or response == "yes":
324                if self.dryRun:
325                    print submitTemplate
326                    raw_input("Press return to continue...")
327                else:
328                     pipe = mypopen("p4 submit -i", "w")
329                     pipe.write(submitTemplate)
330                     pipe.close()
331             else:
332                 print "Not submitting!"
333                 self.interactive = False
334         else:
335             fileName = "submit.txt"
336             file = open(fileName, "w+")
337             file.write(self.prepareLogMessage(template, logMessage))
338             file.close()
339             print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
341     def run(self, args):
342         global gitdir
343         # make gitdir absolute so we can cd out into the perforce checkout
344         gitdir = os.path.abspath(gitdir)
345         os.environ["GIT_DIR"] = gitdir
347         if len(args) == 0:
348             self.master = currentGitBranch()
349             if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
350                 die("Detecting current git branch failed!")
351         elif len(args) == 1:
352             self.master = args[0]
353         else:
354             return False
356         depotPath = ""
357         if gitBranchExists("p4"):
358             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
359         if len(depotPath) == 0 and gitBranchExists("origin"):
360             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
362         if len(depotPath) == 0:
363             print "Internal error: cannot locate perforce depot path from existing branches"
364             sys.exit(128)
366         self.clientPath = p4Where(depotPath)
368         if len(self.clientPath) == 0:
369             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
370             sys.exit(128)
372         print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
373         oldWorkingDirectory = os.getcwd()
374         os.chdir(self.clientPath)
375         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
376         if response == "y" or response == "yes":
377             system("p4 sync ...")
379         if len(self.origin) == 0:
380             if gitBranchExists("p4"):
381                 self.origin = "p4"
382             else:
383                 self.origin = "origin"
385         if self.reset:
386             self.firstTime = True
388         if len(self.substFile) > 0:
389             for line in open(self.substFile, "r").readlines():
390                 tokens = line[:-1].split("=")
391                 self.logSubstitutions[tokens[0]] = tokens[1]
393         self.check()
394         self.configFile = gitdir + "/p4-git-sync.cfg"
395         self.config = shelve.open(self.configFile, writeback=True)
397         if self.firstTime:
398             self.start()
400         commits = self.config.get("commits", [])
402         while len(commits) > 0:
403             self.firstTime = False
404             commit = commits[0]
405             commits = commits[1:]
406             self.config["commits"] = commits
407             self.apply(commit)
408             if not self.interactive:
409                 break
411         self.config.close()
413         if len(commits) == 0:
414             if self.firstTime:
415                 print "No changes found to apply between %s and current HEAD" % self.origin
416             else:
417                 print "All changes applied!"
418                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
419                 if response == "y" or response == "yes":
420                     os.chdir(oldWorkingDirectory)
421                     rebase = P4Rebase()
422                     rebase.run([])
423             os.remove(self.configFile)
425         return True
427 class P4Sync(Command):
428     def __init__(self):
429         Command.__init__(self)
430         self.options = [
431                 optparse.make_option("--branch", dest="branch"),
432                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
433                 optparse.make_option("--changesfile", dest="changesFile"),
434                 optparse.make_option("--silent", dest="silent", action="store_true"),
435                 optparse.make_option("--known-branches", dest="knownBranches"),
436                 optparse.make_option("--data-cache", dest="dataCache", action="store_true"),
437                 optparse.make_option("--command-cache", dest="commandCache", action="store_true"),
438                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true")
439         ]
440         self.description = """Imports from Perforce into a git repository.\n
441     example:
442     //depot/my/project/ -- to import the current head
443     //depot/my/project/@all -- to import everything
444     //depot/my/project/@1,6 -- to import only from revision 1 to 6
446     (a ... is not needed in the path p4 specification, it's added implicitly)"""
448         self.usage += " //depot/path[@revRange]"
450         self.dataCache = False
451         self.commandCache = False
452         self.silent = False
453         self.knownBranches = Set()
454         self.createdBranches = Set()
455         self.committedChanges = Set()
456         self.branch = ""
457         self.detectBranches = False
458         self.detectLabels = False
459         self.changesFile = ""
461     def p4File(self, depotPath):
462         return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
464     def extractFilesFromCommit(self, commit):
465         files = []
466         fnum = 0
467         while commit.has_key("depotFile%s" % fnum):
468             path =  commit["depotFile%s" % fnum]
469             if not path.startswith(self.depotPath):
470     #            if not self.silent:
471     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
472                 fnum = fnum + 1
473                 continue
475             file = {}
476             file["path"] = path
477             file["rev"] = commit["rev%s" % fnum]
478             file["action"] = commit["action%s" % fnum]
479             file["type"] = commit["type%s" % fnum]
480             files.append(file)
481             fnum = fnum + 1
482         return files
484     def isSubPathOf(self, first, second):
485         if not first.startswith(second):
486             return False
487         if first == second:
488             return True
489         return first[len(second)] == "/"
491     def branchesForCommit(self, files):
492         branches = Set()
494         for file in files:
495             relativePath = file["path"][len(self.depotPath):]
496             # strip off the filename
497             relativePath = relativePath[0:relativePath.rfind("/")]
499     #        if len(branches) == 0:
500     #            branches.add(relativePath)
501     #            knownBranches.add(relativePath)
502     #            continue
504             ###### this needs more testing :)
505             knownBranch = False
506             for branch in branches:
507                 if relativePath == branch:
508                     knownBranch = True
509                     break
510     #            if relativePath.startswith(branch):
511                 if self.isSubPathOf(relativePath, branch):
512                     knownBranch = True
513                     break
514     #            if branch.startswith(relativePath):
515                 if self.isSubPathOf(branch, relativePath):
516                     branches.remove(branch)
517                     break
519             if knownBranch:
520                 continue
522             for branch in self.knownBranches:
523                 #if relativePath.startswith(branch):
524                 if self.isSubPathOf(relativePath, branch):
525                     if len(branches) == 0:
526                         relativePath = branch
527                     else:
528                         knownBranch = True
529                     break
531             if knownBranch:
532                 continue
534             branches.add(relativePath)
535             self.knownBranches.add(relativePath)
537         return branches
539     def findBranchParent(self, branchPrefix, files):
540         for file in files:
541             path = file["path"]
542             if not path.startswith(branchPrefix):
543                 continue
544             action = file["action"]
545             if action != "integrate" and action != "branch":
546                 continue
547             rev = file["rev"]
548             depotPath = path + "#" + rev
550             log = p4CmdList("filelog \"%s\"" % depotPath)
551             if len(log) != 1:
552                 print "eek! I got confused by the filelog of %s" % depotPath
553                 sys.exit(1);
555             log = log[0]
556             if log["action0"] != action:
557                 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
558                 sys.exit(1);
560             branchAction = log["how0,0"]
561     #        if branchAction == "branch into" or branchAction == "ignored":
562     #            continue # ignore for branching
564             if not branchAction.endswith(" from"):
565                 continue # ignore for branching
566     #            print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
567     #            sys.exit(1);
569             source = log["file0,0"]
570             if source.startswith(branchPrefix):
571                 continue
573             lastSourceRev = log["erev0,0"]
575             sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
576             if len(sourceLog) != 1:
577                 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
578                 sys.exit(1);
579             sourceLog = sourceLog[0]
581             relPath = source[len(self.depotPath):]
582             # strip off the filename
583             relPath = relPath[0:relPath.rfind("/")]
585             for branch in self.knownBranches:
586                 if self.isSubPathOf(relPath, branch):
587     #                print "determined parent branch branch %s due to change in file %s" % (branch, source)
588                     return branch
589     #            else:
590     #                print "%s is not a subpath of branch %s" % (relPath, branch)
592         return ""
594     def commit(self, details, files, branch, branchPrefix, parent = "", merged = ""):
595         epoch = details["time"]
596         author = details["user"]
598         self.gitStream.write("commit %s\n" % branch)
599     #    gitStream.write("mark :%s\n" % details["change"])
600         self.committedChanges.add(int(details["change"]))
601         committer = ""
602         if author in self.users:
603             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
604         else:
605             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
607         self.gitStream.write("committer %s\n" % committer)
609         self.gitStream.write("data <<EOT\n")
610         self.gitStream.write(details["desc"])
611         self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
612         self.gitStream.write("EOT\n\n")
614         if len(parent) > 0:
615             self.gitStream.write("from %s\n" % parent)
617         if len(merged) > 0:
618             self.gitStream.write("merge %s\n" % merged)
620         for file in files:
621             path = file["path"]
622             if not path.startswith(branchPrefix):
623     #            if not silent:
624     #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
625                 continue
626             rev = file["rev"]
627             depotPath = path + "#" + rev
628             relPath = path[len(branchPrefix):]
629             action = file["action"]
631             if file["type"] == "apple":
632                 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
633                 continue
635             if action == "delete":
636                 self.gitStream.write("D %s\n" % relPath)
637             else:
638                 mode = 644
639                 if file["type"].startswith("x"):
640                     mode = 755
642                 data = self.p4File(depotPath)
644                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
645                 self.gitStream.write("data %s\n" % len(data))
646                 self.gitStream.write(data)
647                 self.gitStream.write("\n")
649         self.gitStream.write("\n")
651         change = int(details["change"])
653         self.lastChange = change
655         if change in self.labels:
656             label = self.labels[change]
657             labelDetails = label[0]
658             labelRevisions = label[1]
660             files = p4CmdList("files %s...@%s" % (branchPrefix, change))
662             if len(files) == len(labelRevisions):
664                 cleanedFiles = {}
665                 for info in files:
666                     if info["action"] == "delete":
667                         continue
668                     cleanedFiles[info["depotFile"]] = info["rev"]
670                 if cleanedFiles == labelRevisions:
671                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
672                     self.gitStream.write("from %s\n" % branch)
674                     owner = labelDetails["Owner"]
675                     tagger = ""
676                     if author in self.users:
677                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
678                     else:
679                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
680                     self.gitStream.write("tagger %s\n" % tagger)
681                     self.gitStream.write("data <<EOT\n")
682                     self.gitStream.write(labelDetails["Description"])
683                     self.gitStream.write("EOT\n\n")
685                 else:
686                     if not self.silent:
687                         print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
689             else:
690                 if not self.silent:
691                     print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
693     def extractFilesInCommitToBranch(self, files, branchPrefix):
694         newFiles = []
696         for file in files:
697             path = file["path"]
698             if path.startswith(branchPrefix):
699                 newFiles.append(file)
701         return newFiles
703     def findBranchSourceHeuristic(self, files, branch, branchPrefix):
704         for file in files:
705             action = file["action"]
706             if action != "integrate" and action != "branch":
707                 continue
708             path = file["path"]
709             rev = file["rev"]
710             depotPath = path + "#" + rev
712             log = p4CmdList("filelog \"%s\"" % depotPath)
713             if len(log) != 1:
714                 print "eek! I got confused by the filelog of %s" % depotPath
715                 sys.exit(1);
717             log = log[0]
718             if log["action0"] != action:
719                 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
720                 sys.exit(1);
722             branchAction = log["how0,0"]
724             if not branchAction.endswith(" from"):
725                 continue # ignore for branching
726     #            print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
727     #            sys.exit(1);
729             source = log["file0,0"]
730             if source.startswith(branchPrefix):
731                 continue
733             lastSourceRev = log["erev0,0"]
735             sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
736             if len(sourceLog) != 1:
737                 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
738                 sys.exit(1);
739             sourceLog = sourceLog[0]
741             relPath = source[len(self.depotPath):]
742             # strip off the filename
743             relPath = relPath[0:relPath.rfind("/")]
745             for candidate in self.knownBranches:
746                 if self.isSubPathOf(relPath, candidate) and candidate != branch:
747                     return candidate
749         return ""
751     def changeIsBranchMerge(self, sourceBranch, destinationBranch, change):
752         sourceFiles = {}
753         for file in p4CmdList("files %s...@%s" % (self.depotPath + sourceBranch + "/", change)):
754             if file["action"] == "delete":
755                 continue
756             sourceFiles[file["depotFile"]] = file
758         destinationFiles = {}
759         for file in p4CmdList("files %s...@%s" % (self.depotPath + destinationBranch + "/", change)):
760             destinationFiles[file["depotFile"]] = file
762         for fileName in sourceFiles.keys():
763             integrations = []
764             deleted = False
765             integrationCount = 0
766             for integration in p4CmdList("integrated \"%s\"" % fileName):
767                 toFile = integration["fromFile"] # yes, it's true, it's fromFile
768                 if not toFile in destinationFiles:
769                     continue
770                 destFile = destinationFiles[toFile]
771                 if destFile["action"] == "delete":
772     #                print "file %s has been deleted in %s" % (fileName, toFile)
773                     deleted = True
774                     break
775                 integrationCount += 1
776                 if integration["how"] == "branch from":
777                     continue
779                 if int(integration["change"]) == change:
780                     integrations.append(integration)
781                     continue
782                 if int(integration["change"]) > change:
783                     continue
785                 destRev = int(destFile["rev"])
787                 startRev = integration["startFromRev"][1:]
788                 if startRev == "none":
789                     startRev = 0
790                 else:
791                     startRev = int(startRev)
793                 endRev = integration["endFromRev"][1:]
794                 if endRev == "none":
795                     endRev = 0
796                 else:
797                     endRev = int(endRev)
799                 initialBranch = (destRev == 1 and integration["how"] != "branch into")
800                 inRange = (destRev >= startRev and destRev <= endRev)
801                 newer = (destRev > startRev and destRev > endRev)
803                 if initialBranch or inRange or newer:
804                     integrations.append(integration)
806             if deleted:
807                 continue
809             if len(integrations) == 0 and integrationCount > 1:
810                 print "file %s was not integrated from %s into %s" % (fileName, sourceBranch, destinationBranch)
811                 return False
813         return True
815     def getUserMap(self):
816         self.users = {}
818         for output in p4CmdList("users"):
819             if not output.has_key("User"):
820                 continue
821             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
823     def getLabels(self):
824         self.labels = {}
826         l = p4CmdList("labels %s..." % self.depotPath)
827         if len(l) > 0 and not self.silent:
828             print "Finding files belonging to labels in %s" % self.depotPath
830         for output in l:
831             label = output["label"]
832             revisions = {}
833             newestChange = 0
834             for file in p4CmdList("files //...@%s" % label):
835                 revisions[file["depotFile"]] = file["rev"]
836                 change = int(file["change"])
837                 if change > newestChange:
838                     newestChange = change
840             self.labels[newestChange] = [output, revisions]
842     def run(self, args):
843         self.depotPath = ""
844         self.changeRange = ""
845         self.initialParent = ""
847         if len(self.branch) == 0:
848             self.branch = "p4"
850         if len(args) == 0:
851             if not gitBranchExists(self.branch) and gitBranchExists("origin"):
852                 if not self.silent:
853                     print "Creating %s branch in git repository based on origin" % self.branch
854                 system("git branch %s origin" % self.branch)
856             [self.previousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.branch))
857             if len(self.previousDepotPath) > 0 and len(p4Change) > 0:
858                 p4Change = int(p4Change) + 1
859                 self.depotPath = self.previousDepotPath
860                 self.changeRange = "@%s,#head" % p4Change
861                 self.initialParent = self.branch
862                 if not self.silent:
863                     print "Performing incremental import into %s git branch" % self.branch
865         self.branch = "refs/heads/" + self.branch
867         if len(self.depotPath) != 0:
868             self.depotPath = self.depotPath[:-1]
870         if len(args) == 0 and len(self.depotPath) != 0:
871             if not self.silent:
872                 print "Depot path: %s" % self.depotPath
873         elif len(args) != 1:
874             return False
875         else:
876             if len(self.depotPath) != 0 and self.depotPath != args[0]:
877                 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
878                 sys.exit(1)
879             self.depotPath = args[0]
881         self.revision = ""
882         self.users = {}
883         self.lastChange = 0
885         if self.depotPath.find("@") != -1:
886             atIdx = self.depotPath.index("@")
887             self.changeRange = self.depotPath[atIdx:]
888             if self.changeRange == "@all":
889                 self.changeRange = ""
890             elif self.changeRange.find(",") == -1:
891                 self.revision = self.changeRange
892                 self.changeRange = ""
893             self.depotPath = self.depotPath[0:atIdx]
894         elif self.depotPath.find("#") != -1:
895             hashIdx = self.depotPath.index("#")
896             self.revision = self.depotPath[hashIdx:]
897             self.depotPath = self.depotPath[0:hashIdx]
898         elif len(self.previousDepotPath) == 0:
899             self.revision = "#head"
901         if self.depotPath.endswith("..."):
902             self.depotPath = self.depotPath[:-3]
904         if not self.depotPath.endswith("/"):
905             self.depotPath += "/"
907         self.getUserMap()
908         self.labels = {}
909         if self.detectLabels:
910             self.getLabels();
912         if len(self.changeRange) == 0:
913             try:
914                 sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % self.branch)
915                 output = sout.read()
916                 if output.endswith("\n"):
917                     output = output[:-1]
918                 tagIdx = output.index(" tags/p4/")
919                 caretIdx = output.find("^")
920                 endPos = len(output)
921                 if caretIdx != -1:
922                     endPos = caretIdx
923                 self.rev = int(output[tagIdx + 9 : endPos]) + 1
924                 self.changeRange = "@%s,#head" % self.rev
925                 self.initialParent = mypopen("git rev-parse %s" % self.branch).read()[:-1]
926             except:
927                 pass
929         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
931         importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
932         self.gitOutput = importProcess.stdout
933         self.gitStream = importProcess.stdin
934         self.gitError = importProcess.stderr
936         if len(self.revision) > 0:
937             print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
939             details = { "user" : "git perforce import user", "time" : int(time.time()) }
940             details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
941             details["change"] = self.revision
942             newestRevision = 0
944             fileCnt = 0
945             for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
946                 change = int(info["change"])
947                 if change > newestRevision:
948                     newestRevision = change
950                 if info["action"] == "delete":
951                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
952                     #fileCnt = fileCnt + 1
953                     continue
955                 for prop in [ "depotFile", "rev", "action", "type" ]:
956                     details["%s%s" % (prop, fileCnt)] = info[prop]
958                 fileCnt = fileCnt + 1
960             details["change"] = newestRevision
962             try:
963                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
964             except IOError:
965                 print "IO error with git fast-import. Is your git version recent enough?"
966                 print self.gitError.read()
968         else:
969             changes = []
971             if len(self.changesFile) > 0:
972                 output = open(self.changesFile).readlines()
973                 changeSet = Set()
974                 for line in output:
975                     changeSet.add(int(line))
977                 for change in changeSet:
978                     changes.append(change)
980                 changes.sort()
981             else:
982                 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
984                 for line in output:
985                     changeNum = line.split(" ")[1]
986                     changes.append(changeNum)
988                 changes.reverse()
990             if len(changes) == 0:
991                 if not self.silent:
992                     print "no changes to import!"
993                 return True
995             cnt = 1
996             for change in changes:
997                 description = p4Cmd("describe %s" % change)
999                 if not self.silent:
1000                     sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1001                     sys.stdout.flush()
1002                 cnt = cnt + 1
1004                 try:
1005                     files = self.extractFilesFromCommit(description)
1006                     if self.detectBranches:
1007                         for branch in self.branchesForCommit(files):
1008                             self.knownBranches.add(branch)
1009                             branchPrefix = self.depotPath + branch + "/"
1011                             filesForCommit = self.extractFilesInCommitToBranch(files, branchPrefix)
1013                             merged = ""
1014                             parent = ""
1015                             ########### remove cnt!!!
1016                             if branch not in self.createdBranches and cnt > 2:
1017                                 self.createdBranches.add(branch)
1018                                 parent = self.findBranchParent(branchPrefix, files)
1019                                 if parent == branch:
1020                                     parent = ""
1021             #                    elif len(parent) > 0:
1022             #                        print "%s branched off of %s" % (branch, parent)
1024                             if len(parent) == 0:
1025                                 merged = self.findBranchSourceHeuristic(filesForCommit, branch, branchPrefix)
1026                                 if len(merged) > 0:
1027                                     print "change %s could be a merge from %s into %s" % (description["change"], merged, branch)
1028                                     if not self.changeIsBranchMerge(merged, branch, int(description["change"])):
1029                                         merged = ""
1031                             branch = "refs/heads/" + branch
1032                             if len(parent) > 0:
1033                                 parent = "refs/heads/" + parent
1034                             if len(merged) > 0:
1035                                 merged = "refs/heads/" + merged
1036                             self.commit(description, files, branch, branchPrefix, parent, merged)
1037                     else:
1038                         self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1039                         self.initialParent = ""
1040                 except IOError:
1041                     print self.gitError.read()
1042                     sys.exit(1)
1044         if not self.silent:
1045             print ""
1048         self.gitStream.close()
1049         self.gitOutput.close()
1050         self.gitError.close()
1051         importProcess.wait()
1053         return True
1055 class P4Rebase(Command):
1056     def __init__(self):
1057         Command.__init__(self)
1058         self.options = [ ]
1059         self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1061     def run(self, args):
1062         sync = P4Sync()
1063         sync.run([])
1064         print "Rebasing the current branch"
1065         oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1066         system("git rebase p4")
1067         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1068         return True
1070 class P4Clone(P4Sync):
1071     def __init__(self):
1072         P4Sync.__init__(self)
1073         self.description = "Creates a new git repository and imports from Perforce into it"
1074         self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1075         self.needsGit = False
1077     def run(self, args):
1078         if len(args) < 1:
1079             return False
1080         depotPath = args[0]
1081         dir = ""
1082         if len(args) == 2:
1083             dir = args[1]
1084         elif len(args) > 2:
1085             return False
1087         if not depotPath.startswith("//"):
1088             return False
1090         if len(dir) == 0:
1091             dir = depotPath
1092             atPos = dir.rfind("@")
1093             if atPos != -1:
1094                 dir = dir[0:atPos]
1095             hashPos = dir.rfind("#")
1096             if hashPos != -1:
1097                 dir = dir[0:hashPos]
1099             if dir.endswith("..."):
1100                 dir = dir[:-3]
1102             if dir.endswith("/"):
1103                dir = dir[:-1]
1105             slashPos = dir.rfind("/")
1106             if slashPos != -1:
1107                 dir = dir[slashPos + 1:]
1109         print "Importing from %s into %s" % (depotPath, dir)
1110         os.makedirs(dir)
1111         os.chdir(dir)
1112         system("git init")
1113         if not P4Sync.run(self, [depotPath]):
1114             return False
1115         if self.branch != "master":
1116             system("git branch master p4")
1117             system("git checkout -f")
1118         return True
1120 class HelpFormatter(optparse.IndentedHelpFormatter):
1121     def __init__(self):
1122         optparse.IndentedHelpFormatter.__init__(self)
1124     def format_description(self, description):
1125         if description:
1126             return description + "\n"
1127         else:
1128             return ""
1130 def printUsage(commands):
1131     print "usage: %s <command> [options]" % sys.argv[0]
1132     print ""
1133     print "valid commands: %s" % ", ".join(commands)
1134     print ""
1135     print "Try %s <command> --help for command specific help." % sys.argv[0]
1136     print ""
1138 commands = {
1139     "debug" : P4Debug(),
1140     "clean-tags" : P4CleanTags(),
1141     "submit" : P4Submit(),
1142     "sync" : P4Sync(),
1143     "rebase" : P4Rebase(),
1144     "clone" : P4Clone()
1147 if len(sys.argv[1:]) == 0:
1148     printUsage(commands.keys())
1149     sys.exit(2)
1151 cmd = ""
1152 cmdName = sys.argv[1]
1153 try:
1154     cmd = commands[cmdName]
1155 except KeyError:
1156     print "unknown command %s" % cmdName
1157     print ""
1158     printUsage(commands.keys())
1159     sys.exit(2)
1161 options = cmd.options
1162 cmd.gitdir = gitdir
1164 args = sys.argv[2:]
1166 if len(options) > 0:
1167     options.append(optparse.make_option("--git-dir", dest="gitdir"))
1169     parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1170                                    options,
1171                                    description = cmd.description,
1172                                    formatter = HelpFormatter())
1174     (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1176 if cmd.needsGit:
1177     gitdir = cmd.gitdir
1178     if len(gitdir) == 0:
1179         gitdir = ".git"
1180         if not isValidGitDir(gitdir):
1181             cdup = mypopen("git rev-parse --show-cdup").read()[:-1]
1182             if isValidGitDir(cdup + "/" + gitdir):
1183                 os.chdir(cdup)
1185     if not isValidGitDir(gitdir):
1186         if isValidGitDir(gitdir + "/.git"):
1187             gitdir += "/.git"
1188         else:
1189             die("fatal: cannot locate git repository at %s" % gitdir)
1191     os.environ["GIT_DIR"] = gitdir
1193 if not cmd.run(args):
1194     parser.print_help()