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