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