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