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