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