Code

b21dee31997e96f1a6f5e141db007fe2f1838ae9
[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, shelve
12 import tempfile, getopt, sha, os.path, time
13 from sets import Set;
15 gitdir = os.environ.get("GIT_DIR", "")
17 def p4CmdList(cmd):
18     cmd = "p4 -G %s" % cmd
19     pipe = os.popen(cmd, "rb")
21     result = []
22     try:
23         while True:
24             entry = marshal.load(pipe)
25             result.append(entry)
26     except EOFError:
27         pass
28     pipe.close()
30     return result
32 def p4Cmd(cmd):
33     list = p4CmdList(cmd)
34     result = {}
35     for entry in list:
36         result.update(entry)
37     return result;
39 def die(msg):
40     sys.stderr.write(msg + "\n")
41     sys.exit(1)
43 def currentGitBranch():
44     return os.popen("git-name-rev HEAD").read().split(" ")[1][:-1]
46 def isValidGitDir(path):
47     if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
48         return True;
49     return False
51 def system(cmd):
52     if os.system(cmd) != 0:
53         die("command failed: %s" % cmd)
55 def extractLogMessageFromGitCommit(commit):
56     logMessage = ""
57     foundTitle = False
58     for log in os.popen("git-cat-file commit %s" % commit).readlines():
59        if not foundTitle:
60            if len(log) == 1:
61                foundTitle = 1
62            continue
64        logMessage += log
65     return logMessage
67 def extractDepotPathAndChangeFromGitLog(log):
68     values = {}
69     for line in log.split("\n"):
70         line = line.strip()
71         if line.startswith("[git-p4:") and line.endswith("]"):
72             line = line[8:-1].strip()
73             for assignment in line.split(":"):
74                 variable = assignment.strip()
75                 value = ""
76                 equalPos = assignment.find("=")
77                 if equalPos != -1:
78                     variable = assignment[:equalPos].strip()
79                     value = assignment[equalPos + 1:].strip()
80                     if value.startswith("\"") and value.endswith("\""):
81                         value = value[1:-1]
82                 values[variable] = value
84     return values.get("depot-path"), values.get("change")
86 def gitBranchExists(branch):
87     return os.system("git-rev-parse %s 2>/dev/null >/dev/null") == 0
89 class Command:
90     def __init__(self):
91         self.usage = "usage: %prog [options]"
93 class P4Debug(Command):
94     def __init__(self):
95         Command.__init__(self)
96         self.options = [
97         ]
98         self.description = "A tool to debug the output of p4 -G."
100     def run(self, args):
101         for output in p4CmdList(" ".join(args)):
102             print output
103         return True
105 class P4CleanTags(Command):
106     def __init__(self):
107         Command.__init__(self)
108         self.options = [
109 #                optparse.make_option("--branch", dest="branch", default="refs/heads/master")
110         ]
111         self.description = "A tool to remove stale unused tags from incremental perforce imports."
112     def run(self, args):
113         branch = currentGitBranch()
114         print "Cleaning out stale p4 import tags..."
115         sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
116         output = sout.read()
117         try:
118             tagIdx = output.index(" tags/p4/")
119         except:
120             print "Cannot find any p4/* tag. Nothing to do."
121             sys.exit(0)
123         try:
124             caretIdx = output.index("^")
125         except:
126             caretIdx = len(output) - 1
127         rev = int(output[tagIdx + 9 : caretIdx])
129         allTags = os.popen("git tag -l p4/").readlines()
130         for i in range(len(allTags)):
131             allTags[i] = int(allTags[i][3:-1])
133         allTags.sort()
135         allTags.remove(rev)
137         for rev in allTags:
138             print os.popen("git tag -d p4/%s" % rev).read()
140         print "%s tags removed." % len(allTags)
141         return True
143 class P4Sync(Command):
144     def __init__(self):
145         Command.__init__(self)
146         self.options = [
147                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
148                 optparse.make_option("--origin", dest="origin"),
149                 optparse.make_option("--reset", action="store_true", dest="reset"),
150                 optparse.make_option("--master", dest="master"),
151                 optparse.make_option("--log-substitutions", dest="substFile"),
152                 optparse.make_option("--noninteractive", action="store_false"),
153                 optparse.make_option("--dry-run", action="store_true"),
154                 optparse.make_option("--apply-as-patch", action="store_true", dest="applyAsPatch")
155         ]
156         self.description = "Submit changes from git to the perforce depot."
157         self.firstTime = True
158         self.reset = False
159         self.interactive = True
160         self.dryRun = False
161         self.substFile = ""
162         self.firstTime = True
163         self.origin = "origin"
164         self.master = ""
165         self.applyAsPatch = True
167         self.logSubstitutions = {}
168         self.logSubstitutions["<enter description here>"] = "%log%"
169         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
171     def check(self):
172         if len(p4CmdList("opened ...")) > 0:
173             die("You have files opened with perforce! Close them before starting the sync.")
175     def start(self):
176         if len(self.config) > 0 and not self.reset:
177             die("Cannot start sync. Previous sync config found at %s" % self.configFile)
179         commits = []
180         for line in os.popen("git-rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
181             commits.append(line[:-1])
182         commits.reverse()
184         self.config["commits"] = commits
186         if not self.applyAsPatch:
187             print "Creating temporary p4-sync branch from %s ..." % self.origin
188             system("git checkout -f -b p4-sync %s" % self.origin)
190     def prepareLogMessage(self, template, message):
191         result = ""
193         for line in template.split("\n"):
194             if line.startswith("#"):
195                 result += line + "\n"
196                 continue
198             substituted = False
199             for key in self.logSubstitutions.keys():
200                 if line.find(key) != -1:
201                     value = self.logSubstitutions[key]
202                     value = value.replace("%log%", message)
203                     if value != "@remove@":
204                         result += line.replace(key, value) + "\n"
205                     substituted = True
206                     break
208             if not substituted:
209                 result += line + "\n"
211         return result
213     def apply(self, id):
214         print "Applying %s" % (os.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
215         diff = os.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
216         filesToAdd = set()
217         filesToDelete = set()
218         for line in diff:
219             modifier = line[0]
220             path = line[1:].strip()
221             if modifier == "M":
222                 system("p4 edit %s" % path)
223             elif modifier == "A":
224                 filesToAdd.add(path)
225                 if path in filesToDelete:
226                     filesToDelete.remove(path)
227             elif modifier == "D":
228                 filesToDelete.add(path)
229                 if path in filesToAdd:
230                     filesToAdd.remove(path)
231             else:
232                 die("unknown modifier %s for %s" % (modifier, path))
234         if self.applyAsPatch:
235             system("git-diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\" | patch -p1" % (id, id))
236         else:
237             system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
238             system("git cherry-pick --no-commit \"%s\"" % id)
240         for f in filesToAdd:
241             system("p4 add %s" % f)
242         for f in filesToDelete:
243             system("p4 revert %s" % f)
244             system("p4 delete %s" % f)
246         logMessage = extractLogMessageFromGitCommit(id)
247         logMessage = logMessage.replace("\n", "\n\t")
248         logMessage = logMessage[:-1]
250         template = os.popen("p4 change -o").read()
252         if self.interactive:
253             submitTemplate = self.prepareLogMessage(template, logMessage)
254             diff = os.popen("p4 diff -du ...").read()
256             for newFile in filesToAdd:
257                 diff += "==== new file ====\n"
258                 diff += "--- /dev/null\n"
259                 diff += "+++ %s\n" % newFile
260                 f = open(newFile, "r")
261                 for line in f.readlines():
262                     diff += "+" + line
263                 f.close()
265             separatorLine = "######## everything below this line is just the diff #######\n"
267             response = "e"
268             firstIteration = True
269             while response == "e":
270                 if not firstIteration:
271                     response = raw_input("Do you want to submit this change (y/e/n)? ")
272                 firstIteration = False
273                 if response == "e":
274                     [handle, fileName] = tempfile.mkstemp()
275                     tmpFile = os.fdopen(handle, "w+")
276                     tmpFile.write(submitTemplate + separatorLine + diff)
277                     tmpFile.close()
278                     editor = os.environ.get("EDITOR", "vi")
279                     system(editor + " " + fileName)
280                     tmpFile = open(fileName, "r")
281                     message = tmpFile.read()
282                     tmpFile.close()
283                     os.remove(fileName)
284                     submitTemplate = message[:message.index(separatorLine)]
286             if response == "y" or response == "yes":
287                if self.dryRun:
288                    print submitTemplate
289                    raw_input("Press return to continue...")
290                else:
291                     pipe = os.popen("p4 submit -i", "w")
292                     pipe.write(submitTemplate)
293                     pipe.close()
294             else:
295                 print "Not submitting!"
296                 self.interactive = False
297         else:
298             fileName = "submit.txt"
299             file = open(fileName, "w+")
300             file.write(self.prepareLogMessage(template, logMessage))
301             file.close()
302             print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
304     def run(self, args):
305         if self.reset:
306             self.firstTime = True
308         if len(self.substFile) > 0:
309             for line in open(self.substFile, "r").readlines():
310                 tokens = line[:-1].split("=")
311                 self.logSubstitutions[tokens[0]] = tokens[1]
313         if len(self.master) == 0:
314             self.master = currentGitBranch()
315             if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
316                 die("Detecting current git branch failed!")
318         self.check()
319         self.configFile = gitdir + "/p4-git-sync.cfg"
320         self.config = shelve.open(self.configFile, writeback=True)
322         if self.firstTime:
323             self.start()
325         commits = self.config.get("commits", [])
327         while len(commits) > 0:
328             self.firstTime = False
329             commit = commits[0]
330             commits = commits[1:]
331             self.config["commits"] = commits
332             self.apply(commit)
333             if not self.interactive:
334                 break
336         self.config.close()
338         if len(commits) == 0:
339             if self.firstTime:
340                 print "No changes found to apply between %s and current HEAD" % self.origin
341             else:
342                 print "All changes applied!"
343                 if not self.applyAsPatch:
344                     print "Deleting temporary p4-sync branch and going back to %s" % self.master
345                     system("git checkout %s" % self.master)
346                     system("git branch -D p4-sync")
347                     print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
348                     system("p4 edit ... >/dev/null")
349                     system("p4 revert ... >/dev/null")
350             os.remove(self.configFile)
352         return True
354 class GitSync(Command):
355     def __init__(self):
356         Command.__init__(self)
357         self.options = [
358                 optparse.make_option("--branch", dest="branch"),
359                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
360                 optparse.make_option("--changesfile", dest="changesFile"),
361                 optparse.make_option("--silent", dest="silent", action="store_true"),
362                 optparse.make_option("--known-branches", dest="knownBranches"),
363                 optparse.make_option("--cache", dest="doCache", action="store_true"),
364                 optparse.make_option("--command-cache", dest="commandCache", action="store_true")
365         ]
366         self.description = """Imports from Perforce into a git repository.\n
367     example:
368     //depot/my/project/ -- to import the current head
369     //depot/my/project/@all -- to import everything
370     //depot/my/project/@1,6 -- to import only from revision 1 to 6
372     (a ... is not needed in the path p4 specification, it's added implicitly)"""
374         self.usage += " //depot/path[@revRange]"
376         self.dataCache = False
377         self.commandCache = False
378         self.silent = False
379         self.knownBranches = Set()
380         self.createdBranches = Set()
381         self.committedChanges = Set()
382         self.branch = "p4"
383         self.detectBranches = False
384         self.changesFile = ""
386     def p4File(self, depotPath):
387         return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
389     def extractFilesFromCommit(self, commit):
390         files = []
391         fnum = 0
392         while commit.has_key("depotFile%s" % fnum):
393             path =  commit["depotFile%s" % fnum]
394             if not path.startswith(self.globalPrefix):
395     #            if not self.silent:
396     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
397                 fnum = fnum + 1
398                 continue
400             file = {}
401             file["path"] = path
402             file["rev"] = commit["rev%s" % fnum]
403             file["action"] = commit["action%s" % fnum]
404             file["type"] = commit["type%s" % fnum]
405             files.append(file)
406             fnum = fnum + 1
407         return files
409     def isSubPathOf(self, first, second):
410         if not first.startswith(second):
411             return False
412         if first == second:
413             return True
414         return first[len(second)] == "/"
416     def branchesForCommit(self, files):
417         branches = Set()
419         for file in files:
420             relativePath = file["path"][len(self.globalPrefix):]
421             # strip off the filename
422             relativePath = relativePath[0:relativePath.rfind("/")]
424     #        if len(branches) == 0:
425     #            branches.add(relativePath)
426     #            knownBranches.add(relativePath)
427     #            continue
429             ###### this needs more testing :)
430             knownBranch = False
431             for branch in branches:
432                 if relativePath == branch:
433                     knownBranch = True
434                     break
435     #            if relativePath.startswith(branch):
436                 if self.isSubPathOf(relativePath, branch):
437                     knownBranch = True
438                     break
439     #            if branch.startswith(relativePath):
440                 if self.isSubPathOf(branch, relativePath):
441                     branches.remove(branch)
442                     break
444             if knownBranch:
445                 continue
447             for branch in knownBranches:
448                 #if relativePath.startswith(branch):
449                 if self.isSubPathOf(relativePath, branch):
450                     if len(branches) == 0:
451                         relativePath = branch
452                     else:
453                         knownBranch = True
454                     break
456             if knownBranch:
457                 continue
459             branches.add(relativePath)
460             self.knownBranches.add(relativePath)
462         return branches
464     def findBranchParent(self, branchPrefix, files):
465         for file in files:
466             path = file["path"]
467             if not path.startswith(branchPrefix):
468                 continue
469             action = file["action"]
470             if action != "integrate" and action != "branch":
471                 continue
472             rev = file["rev"]
473             depotPath = path + "#" + rev
475             log = p4CmdList("filelog \"%s\"" % depotPath)
476             if len(log) != 1:
477                 print "eek! I got confused by the filelog of %s" % depotPath
478                 sys.exit(1);
480             log = log[0]
481             if log["action0"] != action:
482                 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
483                 sys.exit(1);
485             branchAction = log["how0,0"]
486     #        if branchAction == "branch into" or branchAction == "ignored":
487     #            continue # ignore for branching
489             if not branchAction.endswith(" from"):
490                 continue # ignore for branching
491     #            print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
492     #            sys.exit(1);
494             source = log["file0,0"]
495             if source.startswith(branchPrefix):
496                 continue
498             lastSourceRev = log["erev0,0"]
500             sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
501             if len(sourceLog) != 1:
502                 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
503                 sys.exit(1);
504             sourceLog = sourceLog[0]
506             relPath = source[len(self.globalPrefix):]
507             # strip off the filename
508             relPath = relPath[0:relPath.rfind("/")]
510             for branch in self.knownBranches:
511                 if self.isSubPathOf(relPath, branch):
512     #                print "determined parent branch branch %s due to change in file %s" % (branch, source)
513                     return branch
514     #            else:
515     #                print "%s is not a subpath of branch %s" % (relPath, branch)
517         return ""
519     def commit(self, details, files, branch, branchPrefix, parent = "", merged = ""):
520         epoch = details["time"]
521         author = details["user"]
523         self.gitStream.write("commit %s\n" % branch)
524     #    gitStream.write("mark :%s\n" % details["change"])
525         self.committedChanges.add(int(details["change"]))
526         committer = ""
527         if author in self.users:
528             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
529         else:
530             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
532         self.gitStream.write("committer %s\n" % committer)
534         self.gitStream.write("data <<EOT\n")
535         self.gitStream.write(details["desc"])
536         self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
537         self.gitStream.write("EOT\n\n")
539         if len(parent) > 0:
540             self.gitStream.write("from %s\n" % parent)
542         if len(merged) > 0:
543             self.gitStream.write("merge %s\n" % merged)
545         for file in files:
546             path = file["path"]
547             if not path.startswith(branchPrefix):
548     #            if not silent:
549     #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
550                 continue
551             rev = file["rev"]
552             depotPath = path + "#" + rev
553             relPath = path[len(branchPrefix):]
554             action = file["action"]
556             if file["type"] == "apple":
557                 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
558                 continue
560             if action == "delete":
561                 self.gitStream.write("D %s\n" % relPath)
562             else:
563                 mode = 644
564                 if file["type"].startswith("x"):
565                     mode = 755
567                 data = self.p4File(depotPath)
569                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
570                 self.gitStream.write("data %s\n" % len(data))
571                 self.gitStream.write(data)
572                 self.gitStream.write("\n")
574         self.gitStream.write("\n")
576         self.lastChange = int(details["change"])
578     def extractFilesInCommitToBranch(self, files, branchPrefix):
579         newFiles = []
581         for file in files:
582             path = file["path"]
583             if path.startswith(branchPrefix):
584                 newFiles.append(file)
586         return newFiles
588     def findBranchSourceHeuristic(self, files, branch, branchPrefix):
589         for file in files:
590             action = file["action"]
591             if action != "integrate" and action != "branch":
592                 continue
593             path = file["path"]
594             rev = file["rev"]
595             depotPath = path + "#" + rev
597             log = p4CmdList("filelog \"%s\"" % depotPath)
598             if len(log) != 1:
599                 print "eek! I got confused by the filelog of %s" % depotPath
600                 sys.exit(1);
602             log = log[0]
603             if log["action0"] != action:
604                 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
605                 sys.exit(1);
607             branchAction = log["how0,0"]
609             if not branchAction.endswith(" from"):
610                 continue # ignore for branching
611     #            print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
612     #            sys.exit(1);
614             source = log["file0,0"]
615             if source.startswith(branchPrefix):
616                 continue
618             lastSourceRev = log["erev0,0"]
620             sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
621             if len(sourceLog) != 1:
622                 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
623                 sys.exit(1);
624             sourceLog = sourceLog[0]
626             relPath = source[len(self.globalPrefix):]
627             # strip off the filename
628             relPath = relPath[0:relPath.rfind("/")]
630             for candidate in self.knownBranches:
631                 if self.isSubPathOf(relPath, candidate) and candidate != branch:
632                     return candidate
634         return ""
636     def changeIsBranchMerge(self, sourceBranch, destinationBranch, change):
637         sourceFiles = {}
638         for file in p4CmdList("files %s...@%s" % (self.globalPrefix + sourceBranch + "/", change)):
639             if file["action"] == "delete":
640                 continue
641             sourceFiles[file["depotFile"]] = file
643         destinationFiles = {}
644         for file in p4CmdList("files %s...@%s" % (self.globalPrefix + destinationBranch + "/", change)):
645             destinationFiles[file["depotFile"]] = file
647         for fileName in sourceFiles.keys():
648             integrations = []
649             deleted = False
650             integrationCount = 0
651             for integration in p4CmdList("integrated \"%s\"" % fileName):
652                 toFile = integration["fromFile"] # yes, it's true, it's fromFile
653                 if not toFile in destinationFiles:
654                     continue
655                 destFile = destinationFiles[toFile]
656                 if destFile["action"] == "delete":
657     #                print "file %s has been deleted in %s" % (fileName, toFile)
658                     deleted = True
659                     break
660                 integrationCount += 1
661                 if integration["how"] == "branch from":
662                     continue
664                 if int(integration["change"]) == change:
665                     integrations.append(integration)
666                     continue
667                 if int(integration["change"]) > change:
668                     continue
670                 destRev = int(destFile["rev"])
672                 startRev = integration["startFromRev"][1:]
673                 if startRev == "none":
674                     startRev = 0
675                 else:
676                     startRev = int(startRev)
678                 endRev = integration["endFromRev"][1:]
679                 if endRev == "none":
680                     endRev = 0
681                 else:
682                     endRev = int(endRev)
684                 initialBranch = (destRev == 1 and integration["how"] != "branch into")
685                 inRange = (destRev >= startRev and destRev <= endRev)
686                 newer = (destRev > startRev and destRev > endRev)
688                 if initialBranch or inRange or newer:
689                     integrations.append(integration)
691             if deleted:
692                 continue
694             if len(integrations) == 0 and integrationCount > 1:
695                 print "file %s was not integrated from %s into %s" % (fileName, sourceBranch, destinationBranch)
696                 return False
698         return True
700     def getUserMap(self):
701         self.users = {}
703         for output in p4CmdList("users"):
704             if not output.has_key("User"):
705                 continue
706             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
708     def run(self, args):
709         self.branch = "refs/heads/" + self.branch
710         self.globalPrefix = self.previousDepotPath = os.popen("git-repo-config --get p4.depotpath").read()
711         if len(self.globalPrefix) != 0:
712             self.globalPrefix = self.globalPrefix[:-1]
714         if len(args) == 0 and len(self.globalPrefix) != 0:
715             if not self.silent:
716                 print "[using previously specified depot path %s]" % self.globalPrefix
717         elif len(args) != 1:
718             return False
719         else:
720             if len(self.globalPrefix) != 0 and self.globalPrefix != args[0]:
721                 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.globalPrefix, args[0])
722                 sys.exit(1)
723             self.globalPrefix = args[0]
725         self.changeRange = ""
726         self.revision = ""
727         self.users = {}
728         self.initialParent = ""
729         self.lastChange = 0
730         self.initialTag = ""
732         if self.globalPrefix.find("@") != -1:
733             atIdx = self.globalPrefix.index("@")
734             self.changeRange = self.globalPrefix[atIdx:]
735             if self.changeRange == "@all":
736                 self.changeRange = ""
737             elif self.changeRange.find(",") == -1:
738                 self.revision = self.changeRange
739                 self.changeRange = ""
740             self.globalPrefix = self.globalPrefix[0:atIdx]
741         elif self.globalPrefix.find("#") != -1:
742             hashIdx = self.globalPrefix.index("#")
743             self.revision = self.globalPrefix[hashIdx:]
744             self.globalPrefix = self.globalPrefix[0:hashIdx]
745         elif len(self.previousDepotPath) == 0:
746             self.revision = "#head"
748         if self.globalPrefix.endswith("..."):
749             self.globalPrefix = self.globalPrefix[:-3]
751         if not self.globalPrefix.endswith("/"):
752             self.globalPrefix += "/"
754         self.getUserMap()
756         if len(self.changeRange) == 0:
757             try:
758                 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % self.branch)
759                 output = sout.read()
760                 if output.endswith("\n"):
761                     output = output[:-1]
762                 tagIdx = output.index(" tags/p4/")
763                 caretIdx = output.find("^")
764                 endPos = len(output)
765                 if caretIdx != -1:
766                     endPos = caretIdx
767                 self.rev = int(output[tagIdx + 9 : endPos]) + 1
768                 self.changeRange = "@%s,#head" % self.rev
769                 self.initialParent = os.popen("git-rev-parse %s" % self.branch).read()[:-1]
770                 self.initialTag = "p4/%s" % (int(self.rev) - 1)
771             except:
772                 pass
774         self.tz = - time.timezone / 36
775         tzsign = ("%s" % self.tz)[0]
776         if tzsign != '+' and tzsign != '-':
777             self.tz = "+" + ("%s" % self.tz)
779         self.gitOutput, self.gitStream, self.gitError = popen2.popen3("git-fast-import")
781         if len(self.revision) > 0:
782             print "Doing initial import of %s from revision %s" % (self.globalPrefix, self.revision)
784             details = { "user" : "git perforce import user", "time" : int(time.time()) }
785             details["desc"] = "Initial import of %s from the state at revision %s" % (self.globalPrefix, self.revision)
786             details["change"] = self.revision
787             newestRevision = 0
789             fileCnt = 0
790             for info in p4CmdList("files %s...%s" % (self.globalPrefix, self.revision)):
791                 change = int(info["change"])
792                 if change > newestRevision:
793                     newestRevision = change
795                 if info["action"] == "delete":
796                     fileCnt = fileCnt + 1
797                     continue
799                 for prop in [ "depotFile", "rev", "action", "type" ]:
800                     details["%s%s" % (prop, fileCnt)] = info[prop]
802                 fileCnt = fileCnt + 1
804             details["change"] = newestRevision
806             try:
807                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.globalPrefix)
808             except IOError:
809                 print self.gitError.read()
811         else:
812             changes = []
814             if len(self.changesFile) > 0:
815                 output = open(self.changesFile).readlines()
816                 changeSet = Set()
817                 for line in output:
818                     changeSet.add(int(line))
820                 for change in changeSet:
821                     changes.append(change)
823                 changes.sort()
824             else:
825                 output = os.popen("p4 changes %s...%s" % (self.globalPrefix, self.changeRange)).readlines()
827                 for line in output:
828                     changeNum = line.split(" ")[1]
829                     changes.append(changeNum)
831                 changes.reverse()
833             if len(changes) == 0:
834                 if not self.silent:
835                     print "no changes to import!"
836                 sys.exit(1)
838             cnt = 1
839             for change in changes:
840                 description = p4Cmd("describe %s" % change)
842                 if not self.silent:
843                     sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
844                     sys.stdout.flush()
845                 cnt = cnt + 1
847                 try:
848                     files = self.extractFilesFromCommit(description)
849                     if self.detectBranches:
850                         for branch in self.branchesForCommit(files):
851                             self.knownBranches.add(branch)
852                             branchPrefix = self.globalPrefix + branch + "/"
854                             filesForCommit = self.extractFilesInCommitToBranch(files, branchPrefix)
856                             merged = ""
857                             parent = ""
858                             ########### remove cnt!!!
859                             if branch not in self.createdBranches and cnt > 2:
860                                 self.createdBranches.add(branch)
861                                 parent = self.findBranchParent(branchPrefix, files)
862                                 if parent == branch:
863                                     parent = ""
864             #                    elif len(parent) > 0:
865             #                        print "%s branched off of %s" % (branch, parent)
867                             if len(parent) == 0:
868                                 merged = self.findBranchSourceHeuristic(filesForCommit, branch, branchPrefix)
869                                 if len(merged) > 0:
870                                     print "change %s could be a merge from %s into %s" % (description["change"], merged, branch)
871                                     if not self.changeIsBranchMerge(merged, branch, int(description["change"])):
872                                         merged = ""
874                             branch = "refs/heads/" + branch
875                             if len(parent) > 0:
876                                 parent = "refs/heads/" + parent
877                             if len(merged) > 0:
878                                 merged = "refs/heads/" + merged
879                             self.commit(description, files, branch, branchPrefix, parent, merged)
880                     else:
881                         self.commit(description, files, self.branch, self.globalPrefix, self.initialParent)
882                         self.initialParent = ""
883                 except IOError:
884                     print self.gitError.read()
885                     sys.exit(1)
887         if not self.silent:
888             print ""
890         self.gitStream.write("reset refs/tags/p4/%s\n" % self.lastChange)
891         self.gitStream.write("from %s\n\n" % self.branch);
894         self.gitStream.close()
895         self.gitOutput.close()
896         self.gitError.close()
898         os.popen("git-repo-config p4.depotpath %s" % self.globalPrefix).read()
899         if len(self.initialTag) > 0:
900             os.popen("git tag -d %s" % self.initialTag).read()
902         return True
904 class HelpFormatter(optparse.IndentedHelpFormatter):
905     def __init__(self):
906         optparse.IndentedHelpFormatter.__init__(self)
908     def format_description(self, description):
909         if description:
910             return description + "\n"
911         else:
912             return ""
914 def printUsage(commands):
915     print "usage: %s <command> [options]" % sys.argv[0]
916     print ""
917     print "valid commands: %s" % ", ".join(commands)
918     print ""
919     print "Try %s <command> --help for command specific help." % sys.argv[0]
920     print ""
922 commands = {
923     "debug" : P4Debug(),
924     "clean-tags" : P4CleanTags(),
925     "submit" : P4Sync(),
926     "sync" : GitSync()
929 if len(sys.argv[1:]) == 0:
930     printUsage(commands.keys())
931     sys.exit(2)
933 cmd = ""
934 cmdName = sys.argv[1]
935 try:
936     cmd = commands[cmdName]
937 except KeyError:
938     print "unknown command %s" % cmdName
939     print ""
940     printUsage(commands.keys())
941     sys.exit(2)
943 options = cmd.options
944 cmd.gitdir = gitdir
945 options.append(optparse.make_option("--git-dir", dest="gitdir"))
947 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
948                                options,
949                                description = cmd.description,
950                                formatter = HelpFormatter())
952 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
954 gitdir = cmd.gitdir
955 if len(gitdir) == 0:
956     gitdir = ".git"
957     if not isValidGitDir(gitdir):
958         cdup = os.popen("git-rev-parse --show-cdup").read()[:-1]
959         if isValidGitDir(cdup + "/" + gitdir):
960             os.chdir(cdup)
962 if not isValidGitDir(gitdir):
963     if isValidGitDir(gitdir + "/.git"):
964         gitdir += "/.git"
965     else:
966         die("fatal: cannot locate git repository at %s" % gitdir)
968 os.environ["GIT_DIR"] = gitdir
970 if not cmd.run(args):
971     parser.print_help()