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