git-p4: After submission to p4 always synchronize from p4 again (into refs/remotes...
[git.git] / contrib / fast-import / git-p4
blob16e0a7bc81124c024f1149ae752ab508c76085c5
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, stdin=None, stdin_mode='w+b'):
67 cmd = "p4 -G %s" % cmd
68 if verbose:
69 sys.stderr.write("Opening pipe: %s\n" % cmd)
71 # Use a temporary file to avoid deadlocks without
72 # subprocess.communicate(), which would put another copy
73 # of stdout into memory.
74 stdin_file = None
75 if stdin is not None:
76 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
77 stdin_file.write(stdin)
78 stdin_file.flush()
79 stdin_file.seek(0)
81 p4 = subprocess.Popen(cmd, shell=True,
82 stdin=stdin_file,
83 stdout=subprocess.PIPE)
85 result = []
86 try:
87 while True:
88 entry = marshal.load(p4.stdout)
89 result.append(entry)
90 except EOFError:
91 pass
92 exitCode = p4.wait()
93 if exitCode != 0:
94 entry = {}
95 entry["p4ExitCode"] = exitCode
96 result.append(entry)
98 return result
100 def p4Cmd(cmd):
101 list = p4CmdList(cmd)
102 result = {}
103 for entry in list:
104 result.update(entry)
105 return result;
107 def p4Where(depotPath):
108 if not depotPath.endswith("/"):
109 depotPath += "/"
110 output = p4Cmd("where %s..." % depotPath)
111 if output["code"] == "error":
112 return ""
113 clientPath = ""
114 if "path" in output:
115 clientPath = output.get("path")
116 elif "data" in output:
117 data = output.get("data")
118 lastSpace = data.rfind(" ")
119 clientPath = data[lastSpace + 1:]
121 if clientPath.endswith("..."):
122 clientPath = clientPath[:-3]
123 return clientPath
125 def currentGitBranch():
126 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
128 def isValidGitDir(path):
129 if (os.path.exists(path + "/HEAD")
130 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
131 return True;
132 return False
134 def parseRevision(ref):
135 return read_pipe("git rev-parse %s" % ref).strip()
137 def extractLogMessageFromGitCommit(commit):
138 logMessage = ""
140 ## fixme: title is first line of commit, not 1st paragraph.
141 foundTitle = False
142 for log in read_pipe_lines("git cat-file commit %s" % commit):
143 if not foundTitle:
144 if len(log) == 1:
145 foundTitle = True
146 continue
148 logMessage += log
149 return logMessage
151 def extractSettingsGitLog(log):
152 values = {}
153 for line in log.split("\n"):
154 line = line.strip()
155 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
156 if not m:
157 continue
159 assignments = m.group(1).split (':')
160 for a in assignments:
161 vals = a.split ('=')
162 key = vals[0].strip()
163 val = ('='.join (vals[1:])).strip()
164 if val.endswith ('\"') and val.startswith('"'):
165 val = val[1:-1]
167 values[key] = val
169 paths = values.get("depot-paths")
170 if not paths:
171 paths = values.get("depot-path")
172 if paths:
173 values['depot-paths'] = paths.split(',')
174 return values
176 def gitBranchExists(branch):
177 proc = subprocess.Popen(["git", "rev-parse", branch],
178 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
179 return proc.wait() == 0;
181 def gitConfig(key):
182 return read_pipe("git config %s" % key, ignore_error=True).strip()
184 def p4BranchesInGit(branchesAreInRemotes = True):
185 branches = {}
187 cmdline = "git rev-parse --symbolic "
188 if branchesAreInRemotes:
189 cmdline += " --remotes"
190 else:
191 cmdline += " --branches"
193 for line in read_pipe_lines(cmdline):
194 line = line.strip()
196 ## only import to p4/
197 if not line.startswith('p4/') or line == "p4/HEAD":
198 continue
199 branch = line
201 # strip off p4
202 branch = re.sub ("^p4/", "", line)
204 branches[branch] = parseRevision(line)
205 return branches
207 def findUpstreamBranchPoint(head = "HEAD"):
208 branches = p4BranchesInGit()
209 # map from depot-path to branch name
210 branchByDepotPath = {}
211 for branch in branches.keys():
212 tip = branches[branch]
213 log = extractLogMessageFromGitCommit(tip)
214 settings = extractSettingsGitLog(log)
215 if settings.has_key("depot-paths"):
216 paths = ",".join(settings["depot-paths"])
217 branchByDepotPath[paths] = "remotes/p4/" + branch
219 settings = None
220 parent = 0
221 while parent < 65535:
222 commit = head + "~%s" % parent
223 log = extractLogMessageFromGitCommit(commit)
224 settings = extractSettingsGitLog(log)
225 if settings.has_key("depot-paths"):
226 paths = ",".join(settings["depot-paths"])
227 if branchByDepotPath.has_key(paths):
228 return [branchByDepotPath[paths], settings]
230 parent = parent + 1
232 return ["", settings]
234 def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
235 if not silent:
236 print ("Creating/updating branch(es) in %s based on origin branch(es)"
237 % localRefPrefix)
239 originPrefix = "origin/p4/"
241 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
242 line = line.strip()
243 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
244 continue
246 headName = line[len(originPrefix):]
247 remoteHead = localRefPrefix + headName
248 originHead = line
250 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
251 if (not original.has_key('depot-paths')
252 or not original.has_key('change')):
253 continue
255 update = False
256 if not gitBranchExists(remoteHead):
257 if verbose:
258 print "creating %s" % remoteHead
259 update = True
260 else:
261 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
262 if settings.has_key('change') > 0:
263 if settings['depot-paths'] == original['depot-paths']:
264 originP4Change = int(original['change'])
265 p4Change = int(settings['change'])
266 if originP4Change > p4Change:
267 print ("%s (%s) is newer than %s (%s). "
268 "Updating p4 branch from origin."
269 % (originHead, originP4Change,
270 remoteHead, p4Change))
271 update = True
272 else:
273 print ("Ignoring: %s was imported from %s while "
274 "%s was imported from %s"
275 % (originHead, ','.join(original['depot-paths']),
276 remoteHead, ','.join(settings['depot-paths'])))
278 if update:
279 system("git update-ref %s %s" % (remoteHead, originHead))
281 def originP4BranchesExist():
282 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
284 class Command:
285 def __init__(self):
286 self.usage = "usage: %prog [options]"
287 self.needsGit = True
289 class P4Debug(Command):
290 def __init__(self):
291 Command.__init__(self)
292 self.options = [
293 optparse.make_option("--verbose", dest="verbose", action="store_true",
294 default=False),
296 self.description = "A tool to debug the output of p4 -G."
297 self.needsGit = False
298 self.verbose = False
300 def run(self, args):
301 j = 0
302 for output in p4CmdList(" ".join(args)):
303 print 'Element: %d' % j
304 j += 1
305 print output
306 return True
308 class P4RollBack(Command):
309 def __init__(self):
310 Command.__init__(self)
311 self.options = [
312 optparse.make_option("--verbose", dest="verbose", action="store_true"),
313 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
315 self.description = "A tool to debug the multi-branch import. Don't use :)"
316 self.verbose = False
317 self.rollbackLocalBranches = False
319 def run(self, args):
320 if len(args) != 1:
321 return False
322 maxChange = int(args[0])
324 if "p4ExitCode" in p4Cmd("changes -m 1"):
325 die("Problems executing p4");
327 if self.rollbackLocalBranches:
328 refPrefix = "refs/heads/"
329 lines = read_pipe_lines("git rev-parse --symbolic --branches")
330 else:
331 refPrefix = "refs/remotes/"
332 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
334 for line in lines:
335 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
336 line = line.strip()
337 ref = refPrefix + line
338 log = extractLogMessageFromGitCommit(ref)
339 settings = extractSettingsGitLog(log)
341 depotPaths = settings['depot-paths']
342 change = settings['change']
344 changed = False
346 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
347 for p in depotPaths]))) == 0:
348 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
349 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
350 continue
352 while change and int(change) > maxChange:
353 changed = True
354 if self.verbose:
355 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
356 system("git update-ref %s \"%s^\"" % (ref, ref))
357 log = extractLogMessageFromGitCommit(ref)
358 settings = extractSettingsGitLog(log)
361 depotPaths = settings['depot-paths']
362 change = settings['change']
364 if changed:
365 print "%s rewound to %s" % (ref, change)
367 return True
369 class P4Submit(Command):
370 def __init__(self):
371 Command.__init__(self)
372 self.options = [
373 optparse.make_option("--continue", action="store_false", dest="firstTime"),
374 optparse.make_option("--verbose", dest="verbose", action="store_true"),
375 optparse.make_option("--origin", dest="origin"),
376 optparse.make_option("--reset", action="store_true", dest="reset"),
377 optparse.make_option("--log-substitutions", dest="substFile"),
378 optparse.make_option("--dry-run", action="store_true"),
379 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
380 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
382 self.description = "Submit changes from git to the perforce depot."
383 self.usage += " [name of git branch to submit into perforce depot]"
384 self.firstTime = True
385 self.reset = False
386 self.interactive = True
387 self.dryRun = False
388 self.substFile = ""
389 self.firstTime = True
390 self.origin = ""
391 self.directSubmit = False
392 self.trustMeLikeAFool = False
393 self.verbose = False
394 self.isWindows = (platform.system() == "Windows")
396 self.logSubstitutions = {}
397 self.logSubstitutions["<enter description here>"] = "%log%"
398 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
400 def check(self):
401 if len(p4CmdList("opened ...")) > 0:
402 die("You have files opened with perforce! Close them before starting the sync.")
404 def start(self):
405 if len(self.config) > 0 and not self.reset:
406 die("Cannot start sync. Previous sync config found at %s\n"
407 "If you want to start submitting again from scratch "
408 "maybe you want to call git-p4 submit --reset" % self.configFile)
410 commits = []
411 if self.directSubmit:
412 commits.append("0")
413 else:
414 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
415 commits.append(line.strip())
416 commits.reverse()
418 self.config["commits"] = commits
420 def prepareLogMessage(self, template, message):
421 result = ""
423 for line in template.split("\n"):
424 if line.startswith("#"):
425 result += line + "\n"
426 continue
428 substituted = False
429 for key in self.logSubstitutions.keys():
430 if line.find(key) != -1:
431 value = self.logSubstitutions[key]
432 value = value.replace("%log%", message)
433 if value != "@remove@":
434 result += line.replace(key, value) + "\n"
435 substituted = True
436 break
438 if not substituted:
439 result += line + "\n"
441 return result
443 def prepareSubmitTemplate(self):
444 # remove lines in the Files section that show changes to files outside the depot path we're committing into
445 template = ""
446 inFilesSection = False
447 for line in read_pipe_lines("p4 change -o"):
448 if inFilesSection:
449 if line.startswith("\t"):
450 # path starts and ends with a tab
451 path = line[1:]
452 lastTab = path.rfind("\t")
453 if lastTab != -1:
454 path = path[:lastTab]
455 if not path.startswith(self.depotPath):
456 continue
457 else:
458 inFilesSection = False
459 else:
460 if line.startswith("Files:"):
461 inFilesSection = True
463 template += line
465 return template
467 def applyCommit(self, id):
468 if self.directSubmit:
469 print "Applying local change in working directory/index"
470 diff = self.diffStatus
471 else:
472 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
473 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
474 filesToAdd = set()
475 filesToDelete = set()
476 editedFiles = set()
477 for line in diff:
478 modifier = line[0]
479 path = line[1:].strip()
480 if modifier == "M":
481 system("p4 edit \"%s\"" % path)
482 editedFiles.add(path)
483 elif modifier == "A":
484 filesToAdd.add(path)
485 if path in filesToDelete:
486 filesToDelete.remove(path)
487 elif modifier == "D":
488 filesToDelete.add(path)
489 if path in filesToAdd:
490 filesToAdd.remove(path)
491 else:
492 die("unknown modifier %s for %s" % (modifier, path))
494 if self.directSubmit:
495 diffcmd = "cat \"%s\"" % self.diffFile
496 else:
497 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
498 patchcmd = diffcmd + " | git apply "
499 tryPatchCmd = patchcmd + "--check -"
500 applyPatchCmd = patchcmd + "--check --apply -"
502 if os.system(tryPatchCmd) != 0:
503 print "Unfortunately applying the change failed!"
504 print "What do you want to do?"
505 response = "x"
506 while response != "s" and response != "a" and response != "w":
507 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
508 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
509 if response == "s":
510 print "Skipping! Good luck with the next patches..."
511 return
512 elif response == "a":
513 os.system(applyPatchCmd)
514 if len(filesToAdd) > 0:
515 print "You may also want to call p4 add on the following files:"
516 print " ".join(filesToAdd)
517 if len(filesToDelete):
518 print "The following files should be scheduled for deletion with p4 delete:"
519 print " ".join(filesToDelete)
520 die("Please resolve and submit the conflict manually and "
521 + "continue afterwards with git-p4 submit --continue")
522 elif response == "w":
523 system(diffcmd + " > patch.txt")
524 print "Patch saved to patch.txt in %s !" % self.clientPath
525 die("Please resolve and submit the conflict manually and "
526 "continue afterwards with git-p4 submit --continue")
528 system(applyPatchCmd)
530 for f in filesToAdd:
531 system("p4 add \"%s\"" % f)
532 for f in filesToDelete:
533 system("p4 revert \"%s\"" % f)
534 system("p4 delete \"%s\"" % f)
536 logMessage = ""
537 if not self.directSubmit:
538 logMessage = extractLogMessageFromGitCommit(id)
539 logMessage = logMessage.replace("\n", "\n\t")
540 if self.isWindows:
541 logMessage = logMessage.replace("\n", "\r\n")
542 logMessage = logMessage.strip()
544 template = self.prepareSubmitTemplate()
546 if self.interactive:
547 submitTemplate = self.prepareLogMessage(template, logMessage)
548 diff = read_pipe("p4 diff -du ...")
550 for newFile in filesToAdd:
551 diff += "==== new file ====\n"
552 diff += "--- /dev/null\n"
553 diff += "+++ %s\n" % newFile
554 f = open(newFile, "r")
555 for line in f.readlines():
556 diff += "+" + line
557 f.close()
559 separatorLine = "######## everything below this line is just the diff #######"
560 if platform.system() == "Windows":
561 separatorLine += "\r"
562 separatorLine += "\n"
564 response = "e"
565 if self.trustMeLikeAFool:
566 response = "y"
568 firstIteration = True
569 while response == "e":
570 if not firstIteration:
571 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
572 firstIteration = False
573 if response == "e":
574 [handle, fileName] = tempfile.mkstemp()
575 tmpFile = os.fdopen(handle, "w+")
576 tmpFile.write(submitTemplate + separatorLine + diff)
577 tmpFile.close()
578 defaultEditor = "vi"
579 if platform.system() == "Windows":
580 defaultEditor = "notepad"
581 editor = os.environ.get("EDITOR", defaultEditor);
582 system(editor + " " + fileName)
583 tmpFile = open(fileName, "rb")
584 message = tmpFile.read()
585 tmpFile.close()
586 os.remove(fileName)
587 submitTemplate = message[:message.index(separatorLine)]
588 if self.isWindows:
589 submitTemplate = submitTemplate.replace("\r\n", "\n")
591 if response == "y" or response == "yes":
592 if self.dryRun:
593 print submitTemplate
594 raw_input("Press return to continue...")
595 else:
596 if self.directSubmit:
597 print "Submitting to git first"
598 os.chdir(self.oldWorkingDirectory)
599 write_pipe("git commit -a -F -", submitTemplate)
600 os.chdir(self.clientPath)
602 write_pipe("p4 submit -i", submitTemplate)
603 elif response == "s":
604 for f in editedFiles:
605 system("p4 revert \"%s\"" % f);
606 for f in filesToAdd:
607 system("p4 revert \"%s\"" % f);
608 system("rm %s" %f)
609 for f in filesToDelete:
610 system("p4 delete \"%s\"" % f);
611 return
612 else:
613 print "Not submitting!"
614 self.interactive = False
615 else:
616 fileName = "submit.txt"
617 file = open(fileName, "w+")
618 file.write(self.prepareLogMessage(template, logMessage))
619 file.close()
620 print ("Perforce submit template written as %s. "
621 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
622 % (fileName, fileName))
624 def run(self, args):
625 if len(args) == 0:
626 self.master = currentGitBranch()
627 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
628 die("Detecting current git branch failed!")
629 elif len(args) == 1:
630 self.master = args[0]
631 else:
632 return False
634 [upstream, settings] = findUpstreamBranchPoint()
635 self.depotPath = settings['depot-paths'][0]
636 if len(self.origin) == 0:
637 self.origin = upstream
639 if self.verbose:
640 print "Origin branch is " + self.origin
642 if len(self.depotPath) == 0:
643 print "Internal error: cannot locate perforce depot path from existing branches"
644 sys.exit(128)
646 self.clientPath = p4Where(self.depotPath)
648 if len(self.clientPath) == 0:
649 print "Error: Cannot locate perforce checkout of %s in client view" % self.depotPath
650 sys.exit(128)
652 print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
653 self.oldWorkingDirectory = os.getcwd()
655 if self.directSubmit:
656 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
657 if len(self.diffStatus) == 0:
658 print "No changes in working directory to submit."
659 return True
660 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
661 self.diffFile = self.gitdir + "/p4-git-diff"
662 f = open(self.diffFile, "wb")
663 f.write(patch)
664 f.close();
666 os.chdir(self.clientPath)
667 print "Syncronizing p4 checkout..."
668 system("p4 sync ...")
670 if self.reset:
671 self.firstTime = True
673 if len(self.substFile) > 0:
674 for line in open(self.substFile, "r").readlines():
675 tokens = line.strip().split("=")
676 self.logSubstitutions[tokens[0]] = tokens[1]
678 self.check()
679 self.configFile = self.gitdir + "/p4-git-sync.cfg"
680 self.config = shelve.open(self.configFile, writeback=True)
682 if self.firstTime:
683 self.start()
685 commits = self.config.get("commits", [])
687 while len(commits) > 0:
688 self.firstTime = False
689 commit = commits[0]
690 commits = commits[1:]
691 self.config["commits"] = commits
692 self.applyCommit(commit)
693 if not self.interactive:
694 break
696 self.config.close()
698 if self.directSubmit:
699 os.remove(self.diffFile)
701 if len(commits) == 0:
702 if self.firstTime:
703 print "No changes found to apply between %s and current HEAD" % self.origin
704 else:
705 print "All changes applied!"
706 os.chdir(self.oldWorkingDirectory)
708 sync = P4Sync()
709 sync.run([])
711 response = raw_input("Do you want to rebase current HEAD from Perforce now using git-p4 rebase? [y]es/[n]o ")
712 if response == "y" or response == "yes":
713 rebase = P4Rebase()
714 rebase.rebase()
715 os.remove(self.configFile)
717 return True
719 class P4Sync(Command):
720 def __init__(self):
721 Command.__init__(self)
722 self.options = [
723 optparse.make_option("--branch", dest="branch"),
724 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
725 optparse.make_option("--changesfile", dest="changesFile"),
726 optparse.make_option("--silent", dest="silent", action="store_true"),
727 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
728 optparse.make_option("--verbose", dest="verbose", action="store_true"),
729 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
730 help="Import into refs/heads/ , not refs/remotes"),
731 optparse.make_option("--max-changes", dest="maxChanges"),
732 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
733 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
735 self.description = """Imports from Perforce into a git repository.\n
736 example:
737 //depot/my/project/ -- to import the current head
738 //depot/my/project/@all -- to import everything
739 //depot/my/project/@1,6 -- to import only from revision 1 to 6
741 (a ... is not needed in the path p4 specification, it's added implicitly)"""
743 self.usage += " //depot/path[@revRange]"
744 self.silent = False
745 self.createdBranches = Set()
746 self.committedChanges = Set()
747 self.branch = ""
748 self.detectBranches = False
749 self.detectLabels = False
750 self.changesFile = ""
751 self.syncWithOrigin = True
752 self.verbose = False
753 self.importIntoRemotes = True
754 self.maxChanges = ""
755 self.isWindows = (platform.system() == "Windows")
756 self.keepRepoPath = False
757 self.depotPaths = None
758 self.p4BranchesInGit = []
760 if gitConfig("git-p4.syncFromOrigin") == "false":
761 self.syncWithOrigin = False
763 def extractFilesFromCommit(self, commit):
764 files = []
765 fnum = 0
766 while commit.has_key("depotFile%s" % fnum):
767 path = commit["depotFile%s" % fnum]
769 found = [p for p in self.depotPaths
770 if path.startswith (p)]
771 if not found:
772 fnum = fnum + 1
773 continue
775 file = {}
776 file["path"] = path
777 file["rev"] = commit["rev%s" % fnum]
778 file["action"] = commit["action%s" % fnum]
779 file["type"] = commit["type%s" % fnum]
780 files.append(file)
781 fnum = fnum + 1
782 return files
784 def stripRepoPath(self, path, prefixes):
785 if self.keepRepoPath:
786 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
788 for p in prefixes:
789 if path.startswith(p):
790 path = path[len(p):]
792 return path
794 def splitFilesIntoBranches(self, commit):
795 branches = {}
796 fnum = 0
797 while commit.has_key("depotFile%s" % fnum):
798 path = commit["depotFile%s" % fnum]
799 found = [p for p in self.depotPaths
800 if path.startswith (p)]
801 if not found:
802 fnum = fnum + 1
803 continue
805 file = {}
806 file["path"] = path
807 file["rev"] = commit["rev%s" % fnum]
808 file["action"] = commit["action%s" % fnum]
809 file["type"] = commit["type%s" % fnum]
810 fnum = fnum + 1
812 relPath = self.stripRepoPath(path, self.depotPaths)
814 for branch in self.knownBranches.keys():
816 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
817 if relPath.startswith(branch + "/"):
818 if branch not in branches:
819 branches[branch] = []
820 branches[branch].append(file)
821 break
823 return branches
825 ## Should move this out, doesn't use SELF.
826 def readP4Files(self, files):
827 files = [f for f in files
828 if f['action'] != 'delete']
830 if not files:
831 return
833 filedata = p4CmdList('-x - print',
834 stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
835 for f in files]),
836 stdin_mode='w+')
837 if "p4ExitCode" in filedata[0]:
838 die("Problems executing p4. Error: [%d]."
839 % (filedata[0]['p4ExitCode']));
841 j = 0;
842 contents = {}
843 while j < len(filedata):
844 stat = filedata[j]
845 j += 1
846 text = ''
847 while j < len(filedata) and filedata[j]['code'] in ('text',
848 'binary'):
849 text += filedata[j]['data']
850 j += 1
853 if not stat.has_key('depotFile'):
854 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
855 continue
857 contents[stat['depotFile']] = text
859 for f in files:
860 assert not f.has_key('data')
861 f['data'] = contents[f['path']]
863 def commit(self, details, files, branch, branchPrefixes, parent = ""):
864 epoch = details["time"]
865 author = details["user"]
867 if self.verbose:
868 print "commit into %s" % branch
870 # start with reading files; if that fails, we should not
871 # create a commit.
872 new_files = []
873 for f in files:
874 if [p for p in branchPrefixes if f['path'].startswith(p)]:
875 new_files.append (f)
876 else:
877 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
878 files = new_files
879 self.readP4Files(files)
884 self.gitStream.write("commit %s\n" % branch)
885 # gitStream.write("mark :%s\n" % details["change"])
886 self.committedChanges.add(int(details["change"]))
887 committer = ""
888 if author not in self.users:
889 self.getUserMapFromPerforceServer()
890 if author in self.users:
891 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
892 else:
893 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
895 self.gitStream.write("committer %s\n" % committer)
897 self.gitStream.write("data <<EOT\n")
898 self.gitStream.write(details["desc"])
899 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
900 % (','.join (branchPrefixes), details["change"]))
901 if len(details['options']) > 0:
902 self.gitStream.write(": options = %s" % details['options'])
903 self.gitStream.write("]\nEOT\n\n")
905 if len(parent) > 0:
906 if self.verbose:
907 print "parent %s" % parent
908 self.gitStream.write("from %s\n" % parent)
910 for file in files:
911 if file["type"] == "apple":
912 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
913 continue
915 relPath = self.stripRepoPath(file['path'], branchPrefixes)
916 if file["action"] == "delete":
917 self.gitStream.write("D %s\n" % relPath)
918 else:
919 data = file['data']
921 mode = "644"
922 if file["type"].startswith("x"):
923 mode = "755"
924 elif file["type"] == "symlink":
925 mode = "120000"
926 # p4 print on a symlink contains "target\n", so strip it off
927 data = data[:-1]
929 if self.isWindows and file["type"].endswith("text"):
930 data = data.replace("\r\n", "\n")
932 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
933 self.gitStream.write("data %s\n" % len(data))
934 self.gitStream.write(data)
935 self.gitStream.write("\n")
937 self.gitStream.write("\n")
939 change = int(details["change"])
941 if self.labels.has_key(change):
942 label = self.labels[change]
943 labelDetails = label[0]
944 labelRevisions = label[1]
945 if self.verbose:
946 print "Change %s is labelled %s" % (change, labelDetails)
948 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
949 for p in branchPrefixes]))
951 if len(files) == len(labelRevisions):
953 cleanedFiles = {}
954 for info in files:
955 if info["action"] == "delete":
956 continue
957 cleanedFiles[info["depotFile"]] = info["rev"]
959 if cleanedFiles == labelRevisions:
960 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
961 self.gitStream.write("from %s\n" % branch)
963 owner = labelDetails["Owner"]
964 tagger = ""
965 if author in self.users:
966 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
967 else:
968 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
969 self.gitStream.write("tagger %s\n" % tagger)
970 self.gitStream.write("data <<EOT\n")
971 self.gitStream.write(labelDetails["Description"])
972 self.gitStream.write("EOT\n\n")
974 else:
975 if not self.silent:
976 print ("Tag %s does not match with change %s: files do not match."
977 % (labelDetails["label"], change))
979 else:
980 if not self.silent:
981 print ("Tag %s does not match with change %s: file count is different."
982 % (labelDetails["label"], change))
984 def getUserCacheFilename(self):
985 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
986 return home + "/.gitp4-usercache.txt"
988 def getUserMapFromPerforceServer(self):
989 if self.userMapFromPerforceServer:
990 return
991 self.users = {}
993 for output in p4CmdList("users"):
994 if not output.has_key("User"):
995 continue
996 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
999 s = ''
1000 for (key, val) in self.users.items():
1001 s += "%s\t%s\n" % (key, val)
1003 open(self.getUserCacheFilename(), "wb").write(s)
1004 self.userMapFromPerforceServer = True
1006 def loadUserMapFromCache(self):
1007 self.users = {}
1008 self.userMapFromPerforceServer = False
1009 try:
1010 cache = open(self.getUserCacheFilename(), "rb")
1011 lines = cache.readlines()
1012 cache.close()
1013 for line in lines:
1014 entry = line.strip().split("\t")
1015 self.users[entry[0]] = entry[1]
1016 except IOError:
1017 self.getUserMapFromPerforceServer()
1019 def getLabels(self):
1020 self.labels = {}
1022 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
1023 if len(l) > 0 and not self.silent:
1024 print "Finding files belonging to labels in %s" % `self.depotPath`
1026 for output in l:
1027 label = output["label"]
1028 revisions = {}
1029 newestChange = 0
1030 if self.verbose:
1031 print "Querying files for label %s" % label
1032 for file in p4CmdList("files "
1033 + ' '.join (["%s...@%s" % (p, label)
1034 for p in self.depotPaths])):
1035 revisions[file["depotFile"]] = file["rev"]
1036 change = int(file["change"])
1037 if change > newestChange:
1038 newestChange = change
1040 self.labels[newestChange] = [output, revisions]
1042 if self.verbose:
1043 print "Label changes: %s" % self.labels.keys()
1045 def guessProjectName(self):
1046 for p in self.depotPaths:
1047 if p.endswith("/"):
1048 p = p[:-1]
1049 p = p[p.strip().rfind("/") + 1:]
1050 if not p.endswith("/"):
1051 p += "/"
1052 return p
1054 def getBranchMapping(self):
1055 lostAndFoundBranches = set()
1057 for info in p4CmdList("branches"):
1058 details = p4Cmd("branch -o %s" % info["branch"])
1059 viewIdx = 0
1060 while details.has_key("View%s" % viewIdx):
1061 paths = details["View%s" % viewIdx].split(" ")
1062 viewIdx = viewIdx + 1
1063 # require standard //depot/foo/... //depot/bar/... mapping
1064 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
1065 continue
1066 source = paths[0]
1067 destination = paths[1]
1068 ## HACK
1069 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
1070 source = source[len(self.depotPaths[0]):-4]
1071 destination = destination[len(self.depotPaths[0]):-4]
1073 if destination in self.knownBranches:
1074 if not self.silent:
1075 print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
1076 print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
1077 continue
1079 self.knownBranches[destination] = source
1081 lostAndFoundBranches.discard(destination)
1083 if source not in self.knownBranches:
1084 lostAndFoundBranches.add(source)
1087 for branch in lostAndFoundBranches:
1088 self.knownBranches[branch] = branch
1090 def listExistingP4GitBranches(self):
1091 # branches holds mapping from name to commit
1092 branches = p4BranchesInGit(self.importIntoRemotes)
1093 self.p4BranchesInGit = branches.keys()
1094 for branch in branches.keys():
1095 self.initialParents[self.refPrefix + branch] = branches[branch]
1097 def updateOptionDict(self, d):
1098 option_keys = {}
1099 if self.keepRepoPath:
1100 option_keys['keepRepoPath'] = 1
1102 d["options"] = ' '.join(sorted(option_keys.keys()))
1104 def readOptions(self, d):
1105 self.keepRepoPath = (d.has_key('options')
1106 and ('keepRepoPath' in d['options']))
1108 def run(self, args):
1109 self.depotPaths = []
1110 self.changeRange = ""
1111 self.initialParent = ""
1112 self.previousDepotPaths = []
1114 # map from branch depot path to parent branch
1115 self.knownBranches = {}
1116 self.initialParents = {}
1117 self.hasOrigin = originP4BranchesExist()
1118 if not self.syncWithOrigin:
1119 self.hasOrigin = False
1121 if self.importIntoRemotes:
1122 self.refPrefix = "refs/remotes/p4/"
1123 else:
1124 self.refPrefix = "refs/heads/p4/"
1126 if self.syncWithOrigin and self.hasOrigin:
1127 if not self.silent:
1128 print "Syncing with origin first by calling git fetch origin"
1129 system("git fetch origin")
1131 if len(self.branch) == 0:
1132 self.branch = self.refPrefix + "master"
1133 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1134 system("git update-ref %s refs/heads/p4" % self.branch)
1135 system("git branch -D p4");
1136 # create it /after/ importing, when master exists
1137 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes and gitBranchExists(self.branch):
1138 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1140 # TODO: should always look at previous commits,
1141 # merge with previous imports, if possible.
1142 if args == []:
1143 if self.hasOrigin:
1144 createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
1145 self.listExistingP4GitBranches()
1147 if len(self.p4BranchesInGit) > 1:
1148 if not self.silent:
1149 print "Importing from/into multiple branches"
1150 self.detectBranches = True
1152 if self.verbose:
1153 print "branches: %s" % self.p4BranchesInGit
1155 p4Change = 0
1156 for branch in self.p4BranchesInGit:
1157 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
1159 settings = extractSettingsGitLog(logMsg)
1161 self.readOptions(settings)
1162 if (settings.has_key('depot-paths')
1163 and settings.has_key ('change')):
1164 change = int(settings['change']) + 1
1165 p4Change = max(p4Change, change)
1167 depotPaths = sorted(settings['depot-paths'])
1168 if self.previousDepotPaths == []:
1169 self.previousDepotPaths = depotPaths
1170 else:
1171 paths = []
1172 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1173 for i in range(0, min(len(cur), len(prev))):
1174 if cur[i] <> prev[i]:
1175 i = i - 1
1176 break
1178 paths.append (cur[:i + 1])
1180 self.previousDepotPaths = paths
1182 if p4Change > 0:
1183 self.depotPaths = sorted(self.previousDepotPaths)
1184 self.changeRange = "@%s,#head" % p4Change
1185 if not self.detectBranches:
1186 self.initialParent = parseRevision(self.branch)
1187 if not self.silent and not self.detectBranches:
1188 print "Performing incremental import into %s git branch" % self.branch
1190 if not self.branch.startswith("refs/"):
1191 self.branch = "refs/heads/" + self.branch
1193 if len(args) == 0 and self.depotPaths:
1194 if not self.silent:
1195 print "Depot paths: %s" % ' '.join(self.depotPaths)
1196 else:
1197 if self.depotPaths and self.depotPaths != args:
1198 print ("previous import used depot path %s and now %s was specified. "
1199 "This doesn't work!" % (' '.join (self.depotPaths),
1200 ' '.join (args)))
1201 sys.exit(1)
1203 self.depotPaths = sorted(args)
1205 self.revision = ""
1206 self.users = {}
1208 newPaths = []
1209 for p in self.depotPaths:
1210 if p.find("@") != -1:
1211 atIdx = p.index("@")
1212 self.changeRange = p[atIdx:]
1213 if self.changeRange == "@all":
1214 self.changeRange = ""
1215 elif ',' not in self.changeRange:
1216 self.revision = self.changeRange
1217 self.changeRange = ""
1218 p = p[:atIdx]
1219 elif p.find("#") != -1:
1220 hashIdx = p.index("#")
1221 self.revision = p[hashIdx:]
1222 p = p[:hashIdx]
1223 elif self.previousDepotPaths == []:
1224 self.revision = "#head"
1226 p = re.sub ("\.\.\.$", "", p)
1227 if not p.endswith("/"):
1228 p += "/"
1230 newPaths.append(p)
1232 self.depotPaths = newPaths
1235 self.loadUserMapFromCache()
1236 self.labels = {}
1237 if self.detectLabels:
1238 self.getLabels();
1240 if self.detectBranches:
1241 ## FIXME - what's a P4 projectName ?
1242 self.projectName = self.guessProjectName()
1244 if not self.hasOrigin:
1245 self.getBranchMapping();
1246 if self.verbose:
1247 print "p4-git branches: %s" % self.p4BranchesInGit
1248 print "initial parents: %s" % self.initialParents
1249 for b in self.p4BranchesInGit:
1250 if b != "master":
1252 ## FIXME
1253 b = b[len(self.projectName):]
1254 self.createdBranches.add(b)
1256 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1258 importProcess = subprocess.Popen(["git", "fast-import"],
1259 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1260 stderr=subprocess.PIPE);
1261 self.gitOutput = importProcess.stdout
1262 self.gitStream = importProcess.stdin
1263 self.gitError = importProcess.stderr
1265 if self.revision:
1266 print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), self.revision, self.branch)
1268 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1269 details["desc"] = ("Initial import of %s from the state at revision %s"
1270 % (' '.join(self.depotPaths), self.revision))
1271 details["change"] = self.revision
1272 newestRevision = 0
1274 fileCnt = 0
1275 for info in p4CmdList("files "
1276 + ' '.join(["%s...%s"
1277 % (p, self.revision)
1278 for p in self.depotPaths])):
1280 if info['code'] == 'error':
1281 sys.stderr.write("p4 returned an error: %s\n"
1282 % info['data'])
1283 sys.exit(1)
1286 change = int(info["change"])
1287 if change > newestRevision:
1288 newestRevision = change
1290 if info["action"] == "delete":
1291 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1292 #fileCnt = fileCnt + 1
1293 continue
1295 for prop in ["depotFile", "rev", "action", "type" ]:
1296 details["%s%s" % (prop, fileCnt)] = info[prop]
1298 fileCnt = fileCnt + 1
1300 details["change"] = newestRevision
1301 self.updateOptionDict(details)
1302 try:
1303 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1304 except IOError:
1305 print "IO error with git fast-import. Is your git version recent enough?"
1306 print self.gitError.read()
1308 else:
1309 changes = []
1311 if len(self.changesFile) > 0:
1312 output = open(self.changesFile).readlines()
1313 changeSet = Set()
1314 for line in output:
1315 changeSet.add(int(line))
1317 for change in changeSet:
1318 changes.append(change)
1320 changes.sort()
1321 else:
1322 if self.verbose:
1323 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1324 self.changeRange)
1325 assert self.depotPaths
1326 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1327 for p in self.depotPaths]))
1329 for line in output:
1330 changeNum = line.split(" ")[1]
1331 changes.append(int(changeNum))
1333 changes.sort()
1335 if len(self.maxChanges) > 0:
1336 changes = changes[:min(int(self.maxChanges), len(changes))]
1338 if len(changes) == 0:
1339 if not self.silent:
1340 print "No changes to import!"
1341 return True
1343 if not self.silent and not self.detectBranches:
1344 print "Import destination: %s" % self.branch
1346 self.updatedBranches = set()
1348 cnt = 1
1349 for change in changes:
1350 description = p4Cmd("describe %s" % change)
1351 self.updateOptionDict(description)
1353 if not self.silent:
1354 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1355 sys.stdout.flush()
1356 cnt = cnt + 1
1358 try:
1359 if self.detectBranches:
1360 branches = self.splitFilesIntoBranches(description)
1361 for branch in branches.keys():
1362 ## HACK --hwn
1363 branchPrefix = self.depotPaths[0] + branch + "/"
1365 parent = ""
1367 filesForCommit = branches[branch]
1369 if self.verbose:
1370 print "branch is %s" % branch
1372 self.updatedBranches.add(branch)
1374 if branch not in self.createdBranches:
1375 self.createdBranches.add(branch)
1376 parent = self.knownBranches[branch]
1377 if parent == branch:
1378 parent = ""
1379 elif self.verbose:
1380 print "parent determined through known branches: %s" % parent
1382 # main branch? use master
1383 if branch == "main":
1384 branch = "master"
1385 else:
1387 ## FIXME
1388 branch = self.projectName + branch
1390 if parent == "main":
1391 parent = "master"
1392 elif len(parent) > 0:
1393 ## FIXME
1394 parent = self.projectName + parent
1396 branch = self.refPrefix + branch
1397 if len(parent) > 0:
1398 parent = self.refPrefix + parent
1400 if self.verbose:
1401 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1403 if len(parent) == 0 and branch in self.initialParents:
1404 parent = self.initialParents[branch]
1405 del self.initialParents[branch]
1407 self.commit(description, filesForCommit, branch, [branchPrefix], parent)
1408 else:
1409 files = self.extractFilesFromCommit(description)
1410 self.commit(description, files, self.branch, self.depotPaths,
1411 self.initialParent)
1412 self.initialParent = ""
1413 except IOError:
1414 print self.gitError.read()
1415 sys.exit(1)
1417 if not self.silent:
1418 print ""
1419 if len(self.updatedBranches) > 0:
1420 sys.stdout.write("Updated branches: ")
1421 for b in self.updatedBranches:
1422 sys.stdout.write("%s " % b)
1423 sys.stdout.write("\n")
1426 self.gitStream.close()
1427 if importProcess.wait() != 0:
1428 die("fast-import failed: %s" % self.gitError.read())
1429 self.gitOutput.close()
1430 self.gitError.close()
1432 return True
1434 class P4Rebase(Command):
1435 def __init__(self):
1436 Command.__init__(self)
1437 self.options = [ ]
1438 self.description = ("Fetches the latest revision from perforce and "
1439 + "rebases the current work (branch) against it")
1440 self.verbose = False
1442 def run(self, args):
1443 sync = P4Sync()
1444 sync.run([])
1446 return self.rebase()
1448 def rebase(self):
1449 [upstream, settings] = findUpstreamBranchPoint()
1450 if len(upstream) == 0:
1451 die("Cannot find upstream branchpoint for rebase")
1453 # the branchpoint may be p4/foo~3, so strip off the parent
1454 upstream = re.sub("~[0-9]+$", "", upstream)
1456 print "Rebasing the current branch onto %s" % upstream
1457 oldHead = read_pipe("git rev-parse HEAD").strip()
1458 system("git rebase %s" % upstream)
1459 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1460 return True
1462 class P4Clone(P4Sync):
1463 def __init__(self):
1464 P4Sync.__init__(self)
1465 self.description = "Creates a new git repository and imports from Perforce into it"
1466 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1467 self.options.append(
1468 optparse.make_option("--destination", dest="cloneDestination",
1469 action='store', default=None,
1470 help="where to leave result of the clone"))
1471 self.cloneDestination = None
1472 self.needsGit = False
1474 def defaultDestination(self, args):
1475 ## TODO: use common prefix of args?
1476 depotPath = args[0]
1477 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1478 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1479 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1480 depotDir = re.sub(r"/$", "", depotDir)
1481 return os.path.split(depotDir)[1]
1483 def run(self, args):
1484 if len(args) < 1:
1485 return False
1487 if self.keepRepoPath and not self.cloneDestination:
1488 sys.stderr.write("Must specify destination for --keep-path\n")
1489 sys.exit(1)
1491 depotPaths = args
1493 if not self.cloneDestination and len(depotPaths) > 1:
1494 self.cloneDestination = depotPaths[-1]
1495 depotPaths = depotPaths[:-1]
1497 for p in depotPaths:
1498 if not p.startswith("//"):
1499 return False
1501 if not self.cloneDestination:
1502 self.cloneDestination = self.defaultDestination(args)
1504 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1505 if not os.path.exists(self.cloneDestination):
1506 os.makedirs(self.cloneDestination)
1507 os.chdir(self.cloneDestination)
1508 system("git init")
1509 self.gitdir = os.getcwd() + "/.git"
1510 if not P4Sync.run(self, depotPaths):
1511 return False
1512 if self.branch != "master":
1513 if gitBranchExists("refs/remotes/p4/master"):
1514 system("git branch master refs/remotes/p4/master")
1515 system("git checkout -f")
1516 else:
1517 print "Could not detect main branch. No checkout/master branch created."
1519 return True
1521 class P4Branches(Command):
1522 def __init__(self):
1523 Command.__init__(self)
1524 self.options = [ ]
1525 self.description = ("Shows the git branches that hold imports and their "
1526 + "corresponding perforce depot paths")
1527 self.verbose = False
1529 def run(self, args):
1530 if originP4BranchesExist():
1531 createOrUpdateBranchesFromOrigin()
1533 cmdline = "git rev-parse --symbolic "
1534 cmdline += " --remotes"
1536 for line in read_pipe_lines(cmdline):
1537 line = line.strip()
1539 if not line.startswith('p4/') or line == "p4/HEAD":
1540 continue
1541 branch = line
1543 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
1544 settings = extractSettingsGitLog(log)
1546 print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
1547 return True
1549 class HelpFormatter(optparse.IndentedHelpFormatter):
1550 def __init__(self):
1551 optparse.IndentedHelpFormatter.__init__(self)
1553 def format_description(self, description):
1554 if description:
1555 return description + "\n"
1556 else:
1557 return ""
1559 def printUsage(commands):
1560 print "usage: %s <command> [options]" % sys.argv[0]
1561 print ""
1562 print "valid commands: %s" % ", ".join(commands)
1563 print ""
1564 print "Try %s <command> --help for command specific help." % sys.argv[0]
1565 print ""
1567 commands = {
1568 "debug" : P4Debug,
1569 "submit" : P4Submit,
1570 "sync" : P4Sync,
1571 "rebase" : P4Rebase,
1572 "clone" : P4Clone,
1573 "rollback" : P4RollBack,
1574 "branches" : P4Branches
1578 def main():
1579 if len(sys.argv[1:]) == 0:
1580 printUsage(commands.keys())
1581 sys.exit(2)
1583 cmd = ""
1584 cmdName = sys.argv[1]
1585 try:
1586 klass = commands[cmdName]
1587 cmd = klass()
1588 except KeyError:
1589 print "unknown command %s" % cmdName
1590 print ""
1591 printUsage(commands.keys())
1592 sys.exit(2)
1594 options = cmd.options
1595 cmd.gitdir = os.environ.get("GIT_DIR", None)
1597 args = sys.argv[2:]
1599 if len(options) > 0:
1600 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1602 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1603 options,
1604 description = cmd.description,
1605 formatter = HelpFormatter())
1607 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1608 global verbose
1609 verbose = cmd.verbose
1610 if cmd.needsGit:
1611 if cmd.gitdir == None:
1612 cmd.gitdir = os.path.abspath(".git")
1613 if not isValidGitDir(cmd.gitdir):
1614 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1615 if os.path.exists(cmd.gitdir):
1616 cdup = read_pipe("git rev-parse --show-cdup").strip()
1617 if len(cdup) > 0:
1618 os.chdir(cdup);
1620 if not isValidGitDir(cmd.gitdir):
1621 if isValidGitDir(cmd.gitdir + "/.git"):
1622 cmd.gitdir += "/.git"
1623 else:
1624 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1626 os.environ["GIT_DIR"] = cmd.gitdir
1628 if not cmd.run(args):
1629 parser.print_help()
1632 if __name__ == '__main__':
1633 main()