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