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