Don't make len(p4Cmd("p4 changes -m 1 //foo/...")) == 0 succeed when the p4 command...
[jelmer/fast-export.git] / 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 #
10 # TODO: * Consider making --with-origin the default, assuming that the git
11 #         protocol is always more efficient. (needs manual testing first :)
12 #
13
14 import optparse, sys, os, marshal, popen2, subprocess, shelve
15 import tempfile, getopt, sha, os.path, time, platform
16 from sets import Set;
17
18 gitdir = os.environ.get("GIT_DIR", "")
19
20 def mypopen(command):
21     return os.popen(command, "rb");
22
23 def p4CmdList(cmd):
24     cmd = "p4 -G %s" % cmd
25     pipe = os.popen(cmd, "rb")
26
27     result = []
28     try:
29         while True:
30             entry = marshal.load(pipe)
31             result.append(entry)
32     except EOFError:
33         pass
34     exitCode = pipe.close()
35     if exitCode != None:
36         result["p4ExitCode"] = exitCode
37
38     return result
39
40 def p4Cmd(cmd):
41     list = p4CmdList(cmd)
42     result = {}
43     for entry in list:
44         result.update(entry)
45     return result;
46
47 def p4Where(depotPath):
48     if not depotPath.endswith("/"):
49         depotPath += "/"
50     output = p4Cmd("where %s..." % depotPath)
51     if output["code"] == "error":
52         return ""
53     clientPath = ""
54     if "path" in output:
55         clientPath = output.get("path")
56     elif "data" in output:
57         data = output.get("data")
58         lastSpace = data.rfind(" ")
59         clientPath = data[lastSpace + 1:]
60
61     if clientPath.endswith("..."):
62         clientPath = clientPath[:-3]
63     return clientPath
64
65 def die(msg):
66     sys.stderr.write(msg + "\n")
67     sys.exit(1)
68
69 def currentGitBranch():
70     return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
71
72 def isValidGitDir(path):
73     if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
74         return True;
75     return False
76
77 def parseRevision(ref):
78     return mypopen("git rev-parse %s" % ref).read()[:-1]
79
80 def system(cmd):
81     if os.system(cmd) != 0:
82         die("command failed: %s" % cmd)
83
84 def extractLogMessageFromGitCommit(commit):
85     logMessage = ""
86     foundTitle = False
87     for log in mypopen("git cat-file commit %s" % commit).readlines():
88        if not foundTitle:
89            if len(log) == 1:
90                foundTitle = True
91            continue
92
93        logMessage += log
94     return logMessage
95
96 def extractDepotPathAndChangeFromGitLog(log):
97     values = {}
98     for line in log.split("\n"):
99         line = line.strip()
100         if line.startswith("[git-p4:") and line.endswith("]"):
101             line = line[8:-1].strip()
102             for assignment in line.split(":"):
103                 variable = assignment.strip()
104                 value = ""
105                 equalPos = assignment.find("=")
106                 if equalPos != -1:
107                     variable = assignment[:equalPos].strip()
108                     value = assignment[equalPos + 1:].strip()
109                     if value.startswith("\"") and value.endswith("\""):
110                         value = value[1:-1]
111                 values[variable] = value
112
113     return values.get("depot-path"), values.get("change")
114
115 def gitBranchExists(branch):
116     proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
117     return proc.wait() == 0;
118
119 class Command:
120     def __init__(self):
121         self.usage = "usage: %prog [options]"
122         self.needsGit = True
123
124 class P4Debug(Command):
125     def __init__(self):
126         Command.__init__(self)
127         self.options = [
128         ]
129         self.description = "A tool to debug the output of p4 -G."
130         self.needsGit = False
131
132     def run(self, args):
133         for output in p4CmdList(" ".join(args)):
134             print output
135         return True
136
137 class P4RollBack(Command):
138     def __init__(self):
139         Command.__init__(self)
140         self.options = [
141             optparse.make_option("--verbose", dest="verbose", action="store_true"),
142             optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
143         ]
144         self.description = "A tool to debug the multi-branch import. Don't use :)"
145         self.verbose = False
146         self.rollbackLocalBranches = False
147
148     def run(self, args):
149         if len(args) != 1:
150             return False
151         maxChange = int(args[0])
152
153         if self.rollbackLocalBranches:
154             refPrefix = "refs/heads/"
155             lines = mypopen("git rev-parse --symbolic --branches").readlines()
156         else:
157             refPrefix = "refs/remotes/"
158             lines = mypopen("git rev-parse --symbolic --remotes").readlines()
159
160         for line in lines:
161             if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
162                 ref = refPrefix + line[:-1]
163                 log = extractLogMessageFromGitCommit(ref)
164                 depotPath, change = extractDepotPathAndChangeFromGitLog(log)
165                 changed = False
166
167                 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath, maxChange))) == 0:
168                     print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
169                     system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
170                     continue
171
172                 while len(change) > 0 and int(change) > maxChange:
173                     changed = True
174                     if self.verbose:
175                         print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
176                     system("git update-ref %s \"%s^\"" % (ref, ref))
177                     log = extractLogMessageFromGitCommit(ref)
178                     depotPath, change = extractDepotPathAndChangeFromGitLog(log)
179
180                 if changed:
181                     print "%s rewound to %s" % (ref, change)
182
183         return True
184
185 class P4Submit(Command):
186     def __init__(self):
187         Command.__init__(self)
188         self.options = [
189                 optparse.make_option("--continue", action="store_false", dest="firstTime"),
190                 optparse.make_option("--origin", dest="origin"),
191                 optparse.make_option("--reset", action="store_true", dest="reset"),
192                 optparse.make_option("--log-substitutions", dest="substFile"),
193                 optparse.make_option("--noninteractive", action="store_false"),
194                 optparse.make_option("--dry-run", action="store_true"),
195                 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
196         ]
197         self.description = "Submit changes from git to the perforce depot."
198         self.usage += " [name of git branch to submit into perforce depot]"
199         self.firstTime = True
200         self.reset = False
201         self.interactive = True
202         self.dryRun = False
203         self.substFile = ""
204         self.firstTime = True
205         self.origin = ""
206         self.directSubmit = False
207
208         self.logSubstitutions = {}
209         self.logSubstitutions["<enter description here>"] = "%log%"
210         self.logSubstitutions["\tDetails:"] = "\tDetails:  %log%"
211
212     def check(self):
213         if len(p4CmdList("opened ...")) > 0:
214             die("You have files opened with perforce! Close them before starting the sync.")
215
216     def start(self):
217         if len(self.config) > 0 and not self.reset:
218             die("Cannot start sync. Previous sync config found at %s\nIf you want to start submitting again from scratch maybe you want to call git-p4 submit --reset" % self.configFile)
219
220         commits = []
221         if self.directSubmit:
222             commits.append("0")
223         else:
224             for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
225                 commits.append(line[:-1])
226             commits.reverse()
227
228         self.config["commits"] = commits
229
230     def prepareLogMessage(self, template, message):
231         result = ""
232
233         for line in template.split("\n"):
234             if line.startswith("#"):
235                 result += line + "\n"
236                 continue
237
238             substituted = False
239             for key in self.logSubstitutions.keys():
240                 if line.find(key) != -1:
241                     value = self.logSubstitutions[key]
242                     value = value.replace("%log%", message)
243                     if value != "@remove@":
244                         result += line.replace(key, value) + "\n"
245                     substituted = True
246                     break
247
248             if not substituted:
249                 result += line + "\n"
250
251         return result
252
253     def apply(self, id):
254         if self.directSubmit:
255             print "Applying local change in working directory/index"
256             diff = self.diffStatus
257         else:
258             print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
259             diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
260         filesToAdd = set()
261         filesToDelete = set()
262         editedFiles = set()
263         for line in diff:
264             modifier = line[0]
265             path = line[1:].strip()
266             if modifier == "M":
267                 system("p4 edit \"%s\"" % path)
268                 editedFiles.add(path)
269             elif modifier == "A":
270                 filesToAdd.add(path)
271                 if path in filesToDelete:
272                     filesToDelete.remove(path)
273             elif modifier == "D":
274                 filesToDelete.add(path)
275                 if path in filesToAdd:
276                     filesToAdd.remove(path)
277             else:
278                 die("unknown modifier %s for %s" % (modifier, path))
279
280         if self.directSubmit:
281             diffcmd = "cat \"%s\"" % self.diffFile
282         else:
283             diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
284         patchcmd = diffcmd + " | git apply "
285         tryPatchCmd = patchcmd + "--check -"
286         applyPatchCmd = patchcmd + "--check --apply -"
287
288         if os.system(tryPatchCmd) != 0:
289             print "Unfortunately applying the change failed!"
290             print "What do you want to do?"
291             response = "x"
292             while response != "s" and response != "a" and response != "w":
293                 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) ")
294             if response == "s":
295                 print "Skipping! Good luck with the next patches..."
296                 return
297             elif response == "a":
298                 os.system(applyPatchCmd)
299                 if len(filesToAdd) > 0:
300                     print "You may also want to call p4 add on the following files:"
301                     print " ".join(filesToAdd)
302                 if len(filesToDelete):
303                     print "The following files should be scheduled for deletion with p4 delete:"
304                     print " ".join(filesToDelete)
305                 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
306             elif response == "w":
307                 system(diffcmd + " > patch.txt")
308                 print "Patch saved to patch.txt in %s !" % self.clientPath
309                 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
310
311         system(applyPatchCmd)
312
313         for f in filesToAdd:
314             system("p4 add %s" % f)
315         for f in filesToDelete:
316             system("p4 revert %s" % f)
317             system("p4 delete %s" % f)
318
319         logMessage = ""
320         if not self.directSubmit:
321             logMessage = extractLogMessageFromGitCommit(id)
322             logMessage = logMessage.replace("\n", "\n\t")
323             logMessage = logMessage[:-1]
324
325         template = mypopen("p4 change -o").read()
326
327         if self.interactive:
328             submitTemplate = self.prepareLogMessage(template, logMessage)
329             diff = mypopen("p4 diff -du ...").read()
330
331             for newFile in filesToAdd:
332                 diff += "==== new file ====\n"
333                 diff += "--- /dev/null\n"
334                 diff += "+++ %s\n" % newFile
335                 f = open(newFile, "r")
336                 for line in f.readlines():
337                     diff += "+" + line
338                 f.close()
339
340             separatorLine = "######## everything below this line is just the diff #######"
341             if platform.system() == "Windows":
342                 separatorLine += "\r"
343             separatorLine += "\n"
344
345             response = "e"
346             firstIteration = True
347             while response == "e":
348                 if not firstIteration:
349                     response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
350                 firstIteration = False
351                 if response == "e":
352                     [handle, fileName] = tempfile.mkstemp()
353                     tmpFile = os.fdopen(handle, "w+")
354                     tmpFile.write(submitTemplate + separatorLine + diff)
355                     tmpFile.close()
356                     defaultEditor = "vi"
357                     if platform.system() == "Windows":
358                         defaultEditor = "notepad"
359                     editor = os.environ.get("EDITOR", defaultEditor);
360                     system(editor + " " + fileName)
361                     tmpFile = open(fileName, "rb")
362                     message = tmpFile.read()
363                     tmpFile.close()
364                     os.remove(fileName)
365                     submitTemplate = message[:message.index(separatorLine)]
366
367             if response == "y" or response == "yes":
368                if self.dryRun:
369                    print submitTemplate
370                    raw_input("Press return to continue...")
371                else:
372                    if self.directSubmit:
373                        print "Submitting to git first"
374                        os.chdir(self.oldWorkingDirectory)
375                        pipe = os.popen("git commit -a -F -", "wb")
376                        pipe.write(submitTemplate)
377                        pipe.close()
378                        os.chdir(self.clientPath)
379
380                    pipe = os.popen("p4 submit -i", "wb")
381                    pipe.write(submitTemplate)
382                    pipe.close()
383             elif response == "s":
384                 for f in editedFiles:
385                     system("p4 revert \"%s\"" % f);
386                 for f in filesToAdd:
387                     system("p4 revert \"%s\"" % f);
388                     system("rm %s" %f)
389                 for f in filesToDelete:
390                     system("p4 delete \"%s\"" % f);
391                 return
392             else:
393                 print "Not submitting!"
394                 self.interactive = False
395         else:
396             fileName = "submit.txt"
397             file = open(fileName, "w+")
398             file.write(self.prepareLogMessage(template, logMessage))
399             file.close()
400             print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
401
402     def run(self, args):
403         global gitdir
404         # make gitdir absolute so we can cd out into the perforce checkout
405         gitdir = os.path.abspath(gitdir)
406         os.environ["GIT_DIR"] = gitdir
407
408         if len(args) == 0:
409             self.master = currentGitBranch()
410             if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
411                 die("Detecting current git branch failed!")
412         elif len(args) == 1:
413             self.master = args[0]
414         else:
415             return False
416
417         depotPath = ""
418         if gitBranchExists("p4"):
419             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
420         if len(depotPath) == 0 and gitBranchExists("origin"):
421             [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
422
423         if len(depotPath) == 0:
424             print "Internal error: cannot locate perforce depot path from existing branches"
425             sys.exit(128)
426
427         self.clientPath = p4Where(depotPath)
428
429         if len(self.clientPath) == 0:
430             print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
431             sys.exit(128)
432
433         print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
434         self.oldWorkingDirectory = os.getcwd()
435
436         if self.directSubmit:
437             self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
438             if len(self.diffStatus) == 0:
439                 print "No changes in working directory to submit."
440                 return True
441             patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
442             self.diffFile = gitdir + "/p4-git-diff"
443             f = open(self.diffFile, "wb")
444             f.write(patch)
445             f.close();
446
447         os.chdir(self.clientPath)
448         response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
449         if response == "y" or response == "yes":
450             system("p4 sync ...")
451
452         if len(self.origin) == 0:
453             if gitBranchExists("p4"):
454                 self.origin = "p4"
455             else:
456                 self.origin = "origin"
457
458         if self.reset:
459             self.firstTime = True
460
461         if len(self.substFile) > 0:
462             for line in open(self.substFile, "r").readlines():
463                 tokens = line[:-1].split("=")
464                 self.logSubstitutions[tokens[0]] = tokens[1]
465
466         self.check()
467         self.configFile = gitdir + "/p4-git-sync.cfg"
468         self.config = shelve.open(self.configFile, writeback=True)
469
470         if self.firstTime:
471             self.start()
472
473         commits = self.config.get("commits", [])
474
475         while len(commits) > 0:
476             self.firstTime = False
477             commit = commits[0]
478             commits = commits[1:]
479             self.config["commits"] = commits
480             self.apply(commit)
481             if not self.interactive:
482                 break
483
484         self.config.close()
485
486         if self.directSubmit:
487             os.remove(self.diffFile)
488
489         if len(commits) == 0:
490             if self.firstTime:
491                 print "No changes found to apply between %s and current HEAD" % self.origin
492             else:
493                 print "All changes applied!"
494                 os.chdir(self.oldWorkingDirectory)
495                 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
496                 if response == "y" or response == "yes":
497                     rebase = P4Rebase()
498                     rebase.run([])
499             os.remove(self.configFile)
500
501         return True
502
503 class P4Sync(Command):
504     def __init__(self):
505         Command.__init__(self)
506         self.options = [
507                 optparse.make_option("--branch", dest="branch"),
508                 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
509                 optparse.make_option("--changesfile", dest="changesFile"),
510                 optparse.make_option("--silent", dest="silent", action="store_true"),
511                 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
512                 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
513                 optparse.make_option("--verbose", dest="verbose", action="store_true"),
514                 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
515                 optparse.make_option("--max-changes", dest="maxChanges")
516         ]
517         self.description = """Imports from Perforce into a git repository.\n
518     example:
519     //depot/my/project/ -- to import the current head
520     //depot/my/project/@all -- to import everything
521     //depot/my/project/@1,6 -- to import only from revision 1 to 6
522
523     (a ... is not needed in the path p4 specification, it's added implicitly)"""
524
525         self.usage += " //depot/path[@revRange]"
526
527         self.silent = False
528         self.createdBranches = Set()
529         self.committedChanges = Set()
530         self.branch = ""
531         self.detectBranches = False
532         self.detectLabels = False
533         self.changesFile = ""
534         self.syncWithOrigin = False
535         self.verbose = False
536         self.importIntoRemotes = True
537         self.maxChanges = ""
538
539     def p4File(self, depotPath):
540         return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
541
542     def extractFilesFromCommit(self, commit):
543         files = []
544         fnum = 0
545         while commit.has_key("depotFile%s" % fnum):
546             path =  commit["depotFile%s" % fnum]
547             if not path.startswith(self.depotPath):
548     #            if not self.silent:
549     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
550                 fnum = fnum + 1
551                 continue
552
553             file = {}
554             file["path"] = path
555             file["rev"] = commit["rev%s" % fnum]
556             file["action"] = commit["action%s" % fnum]
557             file["type"] = commit["type%s" % fnum]
558             files.append(file)
559             fnum = fnum + 1
560         return files
561
562     def splitFilesIntoBranches(self, commit):
563         branches = {}
564
565         fnum = 0
566         while commit.has_key("depotFile%s" % fnum):
567             path =  commit["depotFile%s" % fnum]
568             if not path.startswith(self.depotPath):
569     #            if not self.silent:
570     #                print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
571                 fnum = fnum + 1
572                 continue
573
574             file = {}
575             file["path"] = path
576             file["rev"] = commit["rev%s" % fnum]
577             file["action"] = commit["action%s" % fnum]
578             file["type"] = commit["type%s" % fnum]
579             fnum = fnum + 1
580
581             relPath = path[len(self.depotPath):]
582
583             for branch in self.knownBranches.keys():
584                 if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
585                     if branch not in branches:
586                         branches[branch] = []
587                     branches[branch].append(file)
588
589         return branches
590
591     def commit(self, details, files, branch, branchPrefix, parent = ""):
592         epoch = details["time"]
593         author = details["user"]
594
595         if self.verbose:
596             print "commit into %s" % branch
597
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 not in self.users:
603             self.getUserMapFromPerforceServer()
604         if author in self.users:
605             committer = "%s %s %s" % (self.users[author], epoch, self.tz)
606         else:
607             committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
608
609         self.gitStream.write("committer %s\n" % committer)
610
611         self.gitStream.write("data <<EOT\n")
612         self.gitStream.write(details["desc"])
613         self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
614         self.gitStream.write("EOT\n\n")
615
616         if len(parent) > 0:
617             if self.verbose:
618                 print "parent %s" % parent
619             self.gitStream.write("from %s\n" % parent)
620
621         for file in files:
622             path = file["path"]
623             if not path.startswith(branchPrefix):
624     #            if not silent:
625     #                print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
626                 continue
627             rev = file["rev"]
628             depotPath = path + "#" + rev
629             relPath = path[len(branchPrefix):]
630             action = file["action"]
631
632             if file["type"] == "apple":
633                 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
634                 continue
635
636             if action == "delete":
637                 self.gitStream.write("D %s\n" % relPath)
638             else:
639                 mode = 644
640                 if file["type"].startswith("x"):
641                     mode = 755
642
643                 data = self.p4File(depotPath)
644
645                 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
646                 self.gitStream.write("data %s\n" % len(data))
647                 self.gitStream.write(data)
648                 self.gitStream.write("\n")
649
650         self.gitStream.write("\n")
651
652         change = int(details["change"])
653
654         if self.labels.has_key(change):
655             label = self.labels[change]
656             labelDetails = label[0]
657             labelRevisions = label[1]
658             if self.verbose:
659                 print "Change %s is labelled %s" % (change, labelDetails)
660
661             files = p4CmdList("files %s...@%s" % (branchPrefix, change))
662
663             if len(files) == len(labelRevisions):
664
665                 cleanedFiles = {}
666                 for info in files:
667                     if info["action"] == "delete":
668                         continue
669                     cleanedFiles[info["depotFile"]] = info["rev"]
670
671                 if cleanedFiles == labelRevisions:
672                     self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
673                     self.gitStream.write("from %s\n" % branch)
674
675                     owner = labelDetails["Owner"]
676                     tagger = ""
677                     if author in self.users:
678                         tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
679                     else:
680                         tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
681                     self.gitStream.write("tagger %s\n" % tagger)
682                     self.gitStream.write("data <<EOT\n")
683                     self.gitStream.write(labelDetails["Description"])
684                     self.gitStream.write("EOT\n\n")
685
686                 else:
687                     if not self.silent:
688                         print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
689
690             else:
691                 if not self.silent:
692                     print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
693
694     def getUserMapFromPerforceServer(self):
695         self.users = {}
696
697         for output in p4CmdList("users"):
698             if not output.has_key("User"):
699                 continue
700             self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
701
702         cache = open(gitdir + "/p4-usercache.txt", "wb")
703         for user in self.users.keys():
704             cache.write("%s\t%s\n" % (user, self.users[user]))
705         cache.close();
706
707     def loadUserMapFromCache(self):
708         self.users = {}
709         try:
710             cache = open(gitdir + "/p4-usercache.txt", "rb")
711             lines = cache.readlines()
712             cache.close()
713             for line in lines:
714                 entry = line[:-1].split("\t")
715                 self.users[entry[0]] = entry[1]
716         except IOError:
717             self.getUserMapFromPerforceServer()
718
719     def getLabels(self):
720         self.labels = {}
721
722         l = p4CmdList("labels %s..." % self.depotPath)
723         if len(l) > 0 and not self.silent:
724             print "Finding files belonging to labels in %s" % self.depotPath
725
726         for output in l:
727             label = output["label"]
728             revisions = {}
729             newestChange = 0
730             if self.verbose:
731                 print "Querying files for label %s" % label
732             for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
733                 revisions[file["depotFile"]] = file["rev"]
734                 change = int(file["change"])
735                 if change > newestChange:
736                     newestChange = change
737
738             self.labels[newestChange] = [output, revisions]
739
740         if self.verbose:
741             print "Label changes: %s" % self.labels.keys()
742
743     def getBranchMapping(self):
744         self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
745
746         for info in p4CmdList("branches"):
747             details = p4Cmd("branch -o %s" % info["branch"])
748             viewIdx = 0
749             while details.has_key("View%s" % viewIdx):
750                 paths = details["View%s" % viewIdx].split(" ")
751                 viewIdx = viewIdx + 1
752                 # require standard //depot/foo/... //depot/bar/... mapping
753                 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
754                     continue
755                 source = paths[0]
756                 destination = paths[1]
757                 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
758                     source = source[len(self.depotPath):-4]
759                     destination = destination[len(self.depotPath):-4]
760                     if destination not in self.knownBranches:
761                         self.knownBranches[destination] = source
762                     if source not in self.knownBranches:
763                         self.knownBranches[source] = source
764
765     def listExistingP4GitBranches(self):
766         self.p4BranchesInGit = []
767
768         cmdline = "git rev-parse --symbolic "
769         if self.importIntoRemotes:
770             cmdline += " --remotes"
771         else:
772             cmdline += " --branches"
773
774         for line in mypopen(cmdline).readlines():
775             if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
776                 continue
777             if self.importIntoRemotes:
778                 # strip off p4
779                 branch = line[3:-1]
780             else:
781                 branch = line[:-1]
782             self.p4BranchesInGit.append(branch)
783             self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
784
785     def run(self, args):
786         self.depotPath = ""
787         self.changeRange = ""
788         self.initialParent = ""
789         self.previousDepotPath = ""
790         # map from branch depot path to parent branch
791         self.knownBranches = {}
792         self.initialParents = {}
793
794         if self.importIntoRemotes:
795             self.refPrefix = "refs/remotes/p4/"
796         else:
797             self.refPrefix = "refs/heads/"
798
799         createP4HeadRef = False;
800
801         if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists(self.refPrefix + "master") and not self.detectBranches and self.importIntoRemotes:
802             ### needs to be ported to multi branch import
803
804             print "Syncing with origin first as requested by calling git fetch origin"
805             system("git fetch origin")
806             [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
807             [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
808             if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
809                 if originPreviousDepotPath == p4PreviousDepotPath:
810                     originP4Change = int(originP4Change)
811                     p4Change = int(p4Change)
812                     if originP4Change > p4Change:
813                         print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
814                         system("git update-ref " + self.refPrefix + "master origin");
815                 else:
816                     print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
817
818         if len(self.branch) == 0:
819             self.branch = self.refPrefix + "master"
820             if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
821                 system("git update-ref %s refs/heads/p4" % self.branch)
822                 system("git branch -D p4");
823             # create it /after/ importing, when master exists
824             if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
825                 createP4HeadRef = True
826
827         # this needs to be called after the conversion from heads/p4 to remotes/p4/master
828         self.listExistingP4GitBranches()
829         if len(self.p4BranchesInGit) > 1 and not self.silent:
830             print "Importing from/into multiple branches"
831             self.detectBranches = True
832
833         if len(args) == 0:
834             if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
835                 ### needs to be ported to multi branch import
836                 if not self.silent:
837                     print "Creating %s branch in git repository based on origin" % self.branch
838                 branch = self.branch
839                 if not branch.startswith("refs"):
840                     branch = "refs/heads/" + branch
841                 system("git update-ref %s origin" % branch)
842
843             if self.verbose:
844                 print "branches: %s" % self.p4BranchesInGit
845
846             p4Change = 0
847             for branch in self.p4BranchesInGit:
848                 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.refPrefix + branch))
849
850                 if self.verbose:
851                     print "path %s change %s" % (depotPath, change)
852
853                 if len(depotPath) > 0 and len(change) > 0:
854                     change = int(change) + 1
855                     p4Change = max(p4Change, change)
856
857                     if len(self.previousDepotPath) == 0:
858                         self.previousDepotPath = depotPath
859                     else:
860                         i = 0
861                         l = min(len(self.previousDepotPath), len(depotPath))
862                         while i < l and self.previousDepotPath[i] == depotPath[i]:
863                             i = i + 1
864                         self.previousDepotPath = self.previousDepotPath[:i]
865
866             if p4Change > 0:
867                 self.depotPath = self.previousDepotPath
868                 self.changeRange = "@%s,#head" % p4Change
869                 self.initialParent = parseRevision(self.branch)
870                 if not self.silent and not self.detectBranches:
871                     print "Performing incremental import into %s git branch" % self.branch
872
873         if not self.branch.startswith("refs/"):
874             self.branch = "refs/heads/" + self.branch
875
876         if len(self.depotPath) != 0:
877             self.depotPath = self.depotPath[:-1]
878
879         if len(args) == 0 and len(self.depotPath) != 0:
880             if not self.silent:
881                 print "Depot path: %s" % self.depotPath
882         elif len(args) != 1:
883             return False
884         else:
885             if len(self.depotPath) != 0 and self.depotPath != args[0]:
886                 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
887                 sys.exit(1)
888             self.depotPath = args[0]
889
890         self.revision = ""
891         self.users = {}
892
893         if self.depotPath.find("@") != -1:
894             atIdx = self.depotPath.index("@")
895             self.changeRange = self.depotPath[atIdx:]
896             if self.changeRange == "@all":
897                 self.changeRange = ""
898             elif self.changeRange.find(",") == -1:
899                 self.revision = self.changeRange
900                 self.changeRange = ""
901             self.depotPath = self.depotPath[0:atIdx]
902         elif self.depotPath.find("#") != -1:
903             hashIdx = self.depotPath.index("#")
904             self.revision = self.depotPath[hashIdx:]
905             self.depotPath = self.depotPath[0:hashIdx]
906         elif len(self.previousDepotPath) == 0:
907             self.revision = "#head"
908
909         if self.depotPath.endswith("..."):
910             self.depotPath = self.depotPath[:-3]
911
912         if not self.depotPath.endswith("/"):
913             self.depotPath += "/"
914
915         self.loadUserMapFromCache()
916         self.labels = {}
917         if self.detectLabels:
918             self.getLabels();
919
920         if self.detectBranches:
921             self.getBranchMapping();
922             if self.verbose:
923                 print "p4-git branches: %s" % self.p4BranchesInGit
924                 print "initial parents: %s" % self.initialParents
925             for b in self.p4BranchesInGit:
926                 if b != "master":
927                     b = b[len(self.projectName):]
928                 self.createdBranches.add(b)
929
930         self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
931
932         importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
933         self.gitOutput = importProcess.stdout
934         self.gitStream = importProcess.stdin
935         self.gitError = importProcess.stderr
936
937         if len(self.revision) > 0:
938             print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
939
940             details = { "user" : "git perforce import user", "time" : int(time.time()) }
941             details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
942             details["change"] = self.revision
943             newestRevision = 0
944
945             fileCnt = 0
946             for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
947                 change = int(info["change"])
948                 if change > newestRevision:
949                     newestRevision = change
950
951                 if info["action"] == "delete":
952                     # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
953                     #fileCnt = fileCnt + 1
954                     continue
955
956                 for prop in [ "depotFile", "rev", "action", "type" ]:
957                     details["%s%s" % (prop, fileCnt)] = info[prop]
958
959                 fileCnt = fileCnt + 1
960
961             details["change"] = newestRevision
962
963             try:
964                 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
965             except IOError:
966                 print "IO error with git fast-import. Is your git version recent enough?"
967                 print self.gitError.read()
968
969         else:
970             changes = []
971
972             if len(self.changesFile) > 0:
973                 output = open(self.changesFile).readlines()
974                 changeSet = Set()
975                 for line in output:
976                     changeSet.add(int(line))
977
978                 for change in changeSet:
979                     changes.append(change)
980
981                 changes.sort()
982             else:
983                 if self.verbose:
984                     print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
985                 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
986
987                 for line in output:
988                     changeNum = line.split(" ")[1]
989                     changes.append(changeNum)
990
991                 changes.reverse()
992
993                 if len(self.maxChanges) > 0:
994                     changes = changes[0:min(int(self.maxChanges), len(changes))]
995
996             if len(changes) == 0:
997                 if not self.silent:
998                     print "No changes to import!"
999                 return True
1000
1001             self.updatedBranches = set()
1002
1003             cnt = 1
1004             for change in changes:
1005                 description = p4Cmd("describe %s" % change)
1006
1007                 if not self.silent:
1008                     sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1009                     sys.stdout.flush()
1010                 cnt = cnt + 1
1011
1012                 try:
1013                     if self.detectBranches:
1014                         branches = self.splitFilesIntoBranches(description)
1015                         for branch in branches.keys():
1016                             branchPrefix = self.depotPath + branch + "/"
1017
1018                             parent = ""
1019
1020                             filesForCommit = branches[branch]
1021
1022                             if self.verbose:
1023                                 print "branch is %s" % branch
1024
1025                             self.updatedBranches.add(branch)
1026
1027                             if branch not in self.createdBranches:
1028                                 self.createdBranches.add(branch)
1029                                 parent = self.knownBranches[branch]
1030                                 if parent == branch:
1031                                     parent = ""
1032                                 elif self.verbose:
1033                                     print "parent determined through known branches: %s" % parent
1034
1035                             # main branch? use master
1036                             if branch == "main":
1037                                 branch = "master"
1038                             else:
1039                                 branch = self.projectName + branch
1040
1041                             if parent == "main":
1042                                 parent = "master"
1043                             elif len(parent) > 0:
1044                                 parent = self.projectName + parent
1045
1046                             branch = self.refPrefix + branch
1047                             if len(parent) > 0:
1048                                 parent = self.refPrefix + parent
1049
1050                             if self.verbose:
1051                                 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1052
1053                             if len(parent) == 0 and branch in self.initialParents:
1054                                 parent = self.initialParents[branch]
1055                                 del self.initialParents[branch]
1056
1057                             self.commit(description, filesForCommit, branch, branchPrefix, parent)
1058                     else:
1059                         files = self.extractFilesFromCommit(description)
1060                         self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1061                         self.initialParent = ""
1062                 except IOError:
1063                     print self.gitError.read()
1064                     sys.exit(1)
1065
1066             if not self.silent:
1067                 print ""
1068                 if len(self.updatedBranches) > 0:
1069                     sys.stdout.write("Updated branches: ")
1070                     for b in self.updatedBranches:
1071                         sys.stdout.write("%s " % b)
1072                     sys.stdout.write("\n")
1073
1074
1075         self.gitStream.close()
1076         if importProcess.wait() != 0:
1077             die("fast-import failed: %s" % self.gitError.read())
1078         self.gitOutput.close()
1079         self.gitError.close()
1080
1081         if createP4HeadRef:
1082             system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1083
1084         return True
1085
1086 class P4Rebase(Command):
1087     def __init__(self):
1088         Command.__init__(self)
1089         self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
1090         self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1091         self.syncWithOrigin = False
1092
1093     def run(self, args):
1094         sync = P4Sync()
1095         sync.syncWithOrigin = self.syncWithOrigin
1096         sync.run([])
1097         print "Rebasing the current branch"
1098         oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1099         system("git rebase p4")
1100         system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1101         return True
1102
1103 class P4Clone(P4Sync):
1104     def __init__(self):
1105         P4Sync.__init__(self)
1106         self.description = "Creates a new git repository and imports from Perforce into it"
1107         self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1108         self.needsGit = False
1109
1110     def run(self, args):
1111         global gitdir
1112
1113         if len(args) < 1:
1114             return False
1115         depotPath = args[0]
1116         dir = ""
1117         if len(args) == 2:
1118             dir = args[1]
1119         elif len(args) > 2:
1120             return False
1121
1122         if not depotPath.startswith("//"):
1123             return False
1124
1125         if len(dir) == 0:
1126             dir = depotPath
1127             atPos = dir.rfind("@")
1128             if atPos != -1:
1129                 dir = dir[0:atPos]
1130             hashPos = dir.rfind("#")
1131             if hashPos != -1:
1132                 dir = dir[0:hashPos]
1133
1134             if dir.endswith("..."):
1135                 dir = dir[:-3]
1136
1137             if dir.endswith("/"):
1138                dir = dir[:-1]
1139
1140             slashPos = dir.rfind("/")
1141             if slashPos != -1:
1142                 dir = dir[slashPos + 1:]
1143
1144         print "Importing from %s into %s" % (depotPath, dir)
1145         os.makedirs(dir)
1146         os.chdir(dir)
1147         system("git init")
1148         gitdir = os.getcwd() + "/.git"
1149         if not P4Sync.run(self, [depotPath]):
1150             return False
1151         if self.branch != "master":
1152             if gitBranchExists("refs/remotes/p4/master"):
1153                 system("git branch master refs/remotes/p4/master")
1154                 system("git checkout -f")
1155             else:
1156                 print "Could not detect main branch. No checkout/master branch created."
1157         return True
1158
1159 class HelpFormatter(optparse.IndentedHelpFormatter):
1160     def __init__(self):
1161         optparse.IndentedHelpFormatter.__init__(self)
1162
1163     def format_description(self, description):
1164         if description:
1165             return description + "\n"
1166         else:
1167             return ""
1168
1169 def printUsage(commands):
1170     print "usage: %s <command> [options]" % sys.argv[0]
1171     print ""
1172     print "valid commands: %s" % ", ".join(commands)
1173     print ""
1174     print "Try %s <command> --help for command specific help." % sys.argv[0]
1175     print ""
1176
1177 commands = {
1178     "debug" : P4Debug(),
1179     "submit" : P4Submit(),
1180     "sync" : P4Sync(),
1181     "rebase" : P4Rebase(),
1182     "clone" : P4Clone(),
1183     "rollback" : P4RollBack()
1184 }
1185
1186 if len(sys.argv[1:]) == 0:
1187     printUsage(commands.keys())
1188     sys.exit(2)
1189
1190 cmd = ""
1191 cmdName = sys.argv[1]
1192 try:
1193     cmd = commands[cmdName]
1194 except KeyError:
1195     print "unknown command %s" % cmdName
1196     print ""
1197     printUsage(commands.keys())
1198     sys.exit(2)
1199
1200 options = cmd.options
1201 cmd.gitdir = gitdir
1202
1203 args = sys.argv[2:]
1204
1205 if len(options) > 0:
1206     options.append(optparse.make_option("--git-dir", dest="gitdir"))
1207
1208     parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1209                                    options,
1210                                    description = cmd.description,
1211                                    formatter = HelpFormatter())
1212
1213     (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1214
1215 if cmd.needsGit:
1216     gitdir = cmd.gitdir
1217     if len(gitdir) == 0:
1218         gitdir = ".git"
1219         if not isValidGitDir(gitdir):
1220             gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1221             if os.path.exists(gitdir):
1222                 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1223                 if len(cdup) > 0:
1224                     os.chdir(cdup);
1225
1226     if not isValidGitDir(gitdir):
1227         if isValidGitDir(gitdir + "/.git"):
1228             gitdir += "/.git"
1229         else:
1230             die("fatal: cannot locate git repository at %s" % gitdir)
1231
1232     os.environ["GIT_DIR"] = gitdir
1233
1234 if not cmd.run(args):
1235     parser.print_help()
1236