Only get the expensive branch mapping from the p4 server when not
[fast-export/barak.git] / git-p4
blob36fe69a79540029a83f4e31a5b980523e49b96d1
1 #!/usr/bin/env python
3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
7 # 2007 Trolltech ASA
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 import optparse, sys, os, marshal, popen2, subprocess, shelve
12 import tempfile, getopt, sha, os.path, time, platform
13 import re
15 from sets import Set;
17 verbose = False
19 def die(msg):
20 if verbose:
21 raise Exception(msg)
22 else:
23 sys.stderr.write(msg + "\n")
24 sys.exit(1)
26 def write_pipe(c, str):
27 if verbose:
28 sys.stderr.write('Writing pipe: %s\n' % c)
30 pipe = os.popen(c, 'w')
31 val = pipe.write(str)
32 if pipe.close():
33 die('Command failed: %s' % c)
35 return val
37 def read_pipe(c, ignore_error=False):
38 if verbose:
39 sys.stderr.write('Reading pipe: %s\n' % c)
41 pipe = os.popen(c, 'rb')
42 val = pipe.read()
43 if pipe.close() and not ignore_error:
44 die('Command failed: %s' % c)
46 return val
49 def read_pipe_lines(c):
50 if verbose:
51 sys.stderr.write('Reading pipe: %s\n' % c)
52 ## todo: check return status
53 pipe = os.popen(c, 'rb')
54 val = pipe.readlines()
55 if pipe.close():
56 die('Command failed: %s' % c)
58 return val
60 def system(cmd):
61 if verbose:
62 sys.stderr.write("executing %s\n" % cmd)
63 if os.system(cmd) != 0:
64 die("command failed: %s" % cmd)
66 def p4CmdList(cmd):
67 cmd = "p4 -G %s" % cmd
68 if verbose:
69 sys.stderr.write("Opening pipe: %s\n" % cmd)
70 pipe = os.popen(cmd, "rb")
72 result = []
73 try:
74 while True:
75 entry = marshal.load(pipe)
76 result.append(entry)
77 except EOFError:
78 pass
79 exitCode = pipe.close()
80 if exitCode != None:
81 entry = {}
82 entry["p4ExitCode"] = exitCode
83 result.append(entry)
85 return result
87 def p4Cmd(cmd):
88 list = p4CmdList(cmd)
89 result = {}
90 for entry in list:
91 result.update(entry)
92 return result;
94 def p4Where(depotPath):
95 if not depotPath.endswith("/"):
96 depotPath += "/"
97 output = p4Cmd("where %s..." % depotPath)
98 if output["code"] == "error":
99 return ""
100 clientPath = ""
101 if "path" in output:
102 clientPath = output.get("path")
103 elif "data" in output:
104 data = output.get("data")
105 lastSpace = data.rfind(" ")
106 clientPath = data[lastSpace + 1:]
108 if clientPath.endswith("..."):
109 clientPath = clientPath[:-3]
110 return clientPath
112 def currentGitBranch():
113 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
115 def isValidGitDir(path):
116 if (os.path.exists(path + "/HEAD")
117 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
118 return True;
119 return False
121 def parseRevision(ref):
122 return read_pipe("git rev-parse %s" % ref).strip()
124 def extractLogMessageFromGitCommit(commit):
125 logMessage = ""
127 ## fixme: title is first line of commit, not 1st paragraph.
128 foundTitle = False
129 for log in read_pipe_lines("git cat-file commit %s" % commit):
130 if not foundTitle:
131 if len(log) == 1:
132 foundTitle = True
133 continue
135 logMessage += log
136 return logMessage
138 def extractSettingsGitLog(log):
139 values = {}
140 for line in log.split("\n"):
141 line = line.strip()
142 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
143 if not m:
144 continue
146 assignments = m.group(1).split (':')
147 for a in assignments:
148 vals = a.split ('=')
149 key = vals[0].strip()
150 val = ('='.join (vals[1:])).strip()
151 if val.endswith ('\"') and val.startswith('"'):
152 val = val[1:-1]
154 values[key] = val
156 paths = values.get("depot-paths")
157 if not paths:
158 paths = values.get("depot-path")
159 if paths:
160 values['depot-paths'] = paths.split(',')
161 return values
163 def gitBranchExists(branch):
164 proc = subprocess.Popen(["git", "rev-parse", branch],
165 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
166 return proc.wait() == 0;
168 def gitConfig(key):
169 return read_pipe("git config %s" % key, ignore_error=True).strip()
171 class Command:
172 def __init__(self):
173 self.usage = "usage: %prog [options]"
174 self.needsGit = True
176 class P4Debug(Command):
177 def __init__(self):
178 Command.__init__(self)
179 self.options = [
180 optparse.make_option("--verbose", dest="verbose", action="store_true",
181 default=False),
183 self.description = "A tool to debug the output of p4 -G."
184 self.needsGit = False
185 self.verbose = False
187 def run(self, args):
188 j = 0
189 for output in p4CmdList(" ".join(args)):
190 print 'Element: %d' % j
191 j += 1
192 print output
193 return True
195 class P4RollBack(Command):
196 def __init__(self):
197 Command.__init__(self)
198 self.options = [
199 optparse.make_option("--verbose", dest="verbose", action="store_true"),
200 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
202 self.description = "A tool to debug the multi-branch import. Don't use :)"
203 self.verbose = False
204 self.rollbackLocalBranches = False
206 def run(self, args):
207 if len(args) != 1:
208 return False
209 maxChange = int(args[0])
211 if "p4ExitCode" in p4Cmd("changes -m 1"):
212 die("Problems executing p4");
214 if self.rollbackLocalBranches:
215 refPrefix = "refs/heads/"
216 lines = read_pipe_lines("git rev-parse --symbolic --branches")
217 else:
218 refPrefix = "refs/remotes/"
219 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
221 for line in lines:
222 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
223 line = line.strip()
224 ref = refPrefix + line
225 log = extractLogMessageFromGitCommit(ref)
226 settings = extractSettingsGitLog(log)
228 depotPaths = settings['depot-paths']
229 change = settings['change']
231 changed = False
233 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
234 for p in depotPaths]))) == 0:
235 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
236 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
237 continue
239 while change and int(change) > maxChange:
240 changed = True
241 if self.verbose:
242 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
243 system("git update-ref %s \"%s^\"" % (ref, ref))
244 log = extractLogMessageFromGitCommit(ref)
245 settings = extractSettingsGitLog(log)
248 depotPaths = settings['depot-paths']
249 change = settings['change']
251 if changed:
252 print "%s rewound to %s" % (ref, change)
254 return True
256 class P4Submit(Command):
257 def __init__(self):
258 Command.__init__(self)
259 self.options = [
260 optparse.make_option("--continue", action="store_false", dest="firstTime"),
261 optparse.make_option("--verbose", dest="verbose", action="store_true"),
262 optparse.make_option("--origin", dest="origin"),
263 optparse.make_option("--reset", action="store_true", dest="reset"),
264 optparse.make_option("--log-substitutions", dest="substFile"),
265 optparse.make_option("--dry-run", action="store_true"),
266 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
267 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
269 self.description = "Submit changes from git to the perforce depot."
270 self.usage += " [name of git branch to submit into perforce depot]"
271 self.firstTime = True
272 self.reset = False
273 self.interactive = True
274 self.dryRun = False
275 self.substFile = ""
276 self.firstTime = True
277 self.origin = ""
278 self.directSubmit = False
279 self.trustMeLikeAFool = False
280 self.verbose = False
281 self.isWindows = (platform.system() == "Windows")
283 self.logSubstitutions = {}
284 self.logSubstitutions["<enter description here>"] = "%log%"
285 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
287 def check(self):
288 if len(p4CmdList("opened ...")) > 0:
289 die("You have files opened with perforce! Close them before starting the sync.")
291 def start(self):
292 if len(self.config) > 0 and not self.reset:
293 die("Cannot start sync. Previous sync config found at %s\n"
294 "If you want to start submitting again from scratch "
295 "maybe you want to call git-p4 submit --reset" % self.configFile)
297 commits = []
298 if self.directSubmit:
299 commits.append("0")
300 else:
301 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
302 commits.append(line.strip())
303 commits.reverse()
305 self.config["commits"] = commits
307 def prepareLogMessage(self, template, message):
308 result = ""
310 for line in template.split("\n"):
311 if line.startswith("#"):
312 result += line + "\n"
313 continue
315 substituted = False
316 for key in self.logSubstitutions.keys():
317 if line.find(key) != -1:
318 value = self.logSubstitutions[key]
319 value = value.replace("%log%", message)
320 if value != "@remove@":
321 result += line.replace(key, value) + "\n"
322 substituted = True
323 break
325 if not substituted:
326 result += line + "\n"
328 return result
330 def applyCommit(self, id):
331 if self.directSubmit:
332 print "Applying local change in working directory/index"
333 diff = self.diffStatus
334 else:
335 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
336 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
337 filesToAdd = set()
338 filesToDelete = set()
339 editedFiles = set()
340 for line in diff:
341 modifier = line[0]
342 path = line[1:].strip()
343 if modifier == "M":
344 system("p4 edit \"%s\"" % path)
345 editedFiles.add(path)
346 elif modifier == "A":
347 filesToAdd.add(path)
348 if path in filesToDelete:
349 filesToDelete.remove(path)
350 elif modifier == "D":
351 filesToDelete.add(path)
352 if path in filesToAdd:
353 filesToAdd.remove(path)
354 else:
355 die("unknown modifier %s for %s" % (modifier, path))
357 if self.directSubmit:
358 diffcmd = "cat \"%s\"" % self.diffFile
359 else:
360 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
361 patchcmd = diffcmd + " | git apply "
362 tryPatchCmd = patchcmd + "--check -"
363 applyPatchCmd = patchcmd + "--check --apply -"
365 if os.system(tryPatchCmd) != 0:
366 print "Unfortunately applying the change failed!"
367 print "What do you want to do?"
368 response = "x"
369 while response != "s" and response != "a" and response != "w":
370 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
371 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
372 if response == "s":
373 print "Skipping! Good luck with the next patches..."
374 return
375 elif response == "a":
376 os.system(applyPatchCmd)
377 if len(filesToAdd) > 0:
378 print "You may also want to call p4 add on the following files:"
379 print " ".join(filesToAdd)
380 if len(filesToDelete):
381 print "The following files should be scheduled for deletion with p4 delete:"
382 print " ".join(filesToDelete)
383 die("Please resolve and submit the conflict manually and "
384 + "continue afterwards with git-p4 submit --continue")
385 elif response == "w":
386 system(diffcmd + " > patch.txt")
387 print "Patch saved to patch.txt in %s !" % self.clientPath
388 die("Please resolve and submit the conflict manually and "
389 "continue afterwards with git-p4 submit --continue")
391 system(applyPatchCmd)
393 for f in filesToAdd:
394 system("p4 add %s" % f)
395 for f in filesToDelete:
396 system("p4 revert %s" % f)
397 system("p4 delete %s" % f)
399 logMessage = ""
400 if not self.directSubmit:
401 logMessage = extractLogMessageFromGitCommit(id)
402 logMessage = logMessage.replace("\n", "\n\t")
403 if self.isWindows:
404 logMessage = logMessage.replace("\n", "\r\n")
405 logMessage = logMessage.strip()
407 template = read_pipe("p4 change -o")
409 if self.interactive:
410 submitTemplate = self.prepareLogMessage(template, logMessage)
411 diff = read_pipe("p4 diff -du ...")
413 for newFile in filesToAdd:
414 diff += "==== new file ====\n"
415 diff += "--- /dev/null\n"
416 diff += "+++ %s\n" % newFile
417 f = open(newFile, "r")
418 for line in f.readlines():
419 diff += "+" + line
420 f.close()
422 separatorLine = "######## everything below this line is just the diff #######"
423 if platform.system() == "Windows":
424 separatorLine += "\r"
425 separatorLine += "\n"
427 response = "e"
428 if self.trustMeLikeAFool:
429 response = "y"
431 firstIteration = True
432 while response == "e":
433 if not firstIteration:
434 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
435 firstIteration = False
436 if response == "e":
437 [handle, fileName] = tempfile.mkstemp()
438 tmpFile = os.fdopen(handle, "w+")
439 tmpFile.write(submitTemplate + separatorLine + diff)
440 tmpFile.close()
441 defaultEditor = "vi"
442 if platform.system() == "Windows":
443 defaultEditor = "notepad"
444 editor = os.environ.get("EDITOR", defaultEditor);
445 system(editor + " " + fileName)
446 tmpFile = open(fileName, "rb")
447 message = tmpFile.read()
448 tmpFile.close()
449 os.remove(fileName)
450 submitTemplate = message[:message.index(separatorLine)]
451 if self.isWindows:
452 submitTemplate = submitTemplate.replace("\r\n", "\n")
454 if response == "y" or response == "yes":
455 if self.dryRun:
456 print submitTemplate
457 raw_input("Press return to continue...")
458 else:
459 if self.directSubmit:
460 print "Submitting to git first"
461 os.chdir(self.oldWorkingDirectory)
462 write_pipe("git commit -a -F -", submitTemplate)
463 os.chdir(self.clientPath)
465 write_pipe("p4 submit -i", submitTemplate)
466 elif response == "s":
467 for f in editedFiles:
468 system("p4 revert \"%s\"" % f);
469 for f in filesToAdd:
470 system("p4 revert \"%s\"" % f);
471 system("rm %s" %f)
472 for f in filesToDelete:
473 system("p4 delete \"%s\"" % f);
474 return
475 else:
476 print "Not submitting!"
477 self.interactive = False
478 else:
479 fileName = "submit.txt"
480 file = open(fileName, "w+")
481 file.write(self.prepareLogMessage(template, logMessage))
482 file.close()
483 print ("Perforce submit template written as %s. "
484 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
485 % (fileName, fileName))
487 def run(self, args):
488 if len(args) == 0:
489 self.master = currentGitBranch()
490 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
491 die("Detecting current git branch failed!")
492 elif len(args) == 1:
493 self.master = args[0]
494 else:
495 return False
497 depotPath = ""
498 parent = 0
499 while parent < 65535:
500 commit = "HEAD~%s" % parent
501 log = extractLogMessageFromGitCommit(commit)
502 settings = extractSettingsGitLog(log)
503 if not settings.has_key("depot-paths"):
504 parent = parent + 1
505 continue
507 depotPath = settings['depot-paths'][0]
509 if len(self.origin) == 0:
510 names = read_pipe_lines("git name-rev '--refs=refs/remotes/p4/*' '%s'" % commit)
511 if len(names) > 0:
512 # strip away the beginning of 'HEAD~42 refs/remotes/p4/foo'
513 self.origin = names[0].strip()[len(commit) + 1:]
515 break
517 if self.verbose:
518 print "Origin branch is " + self.origin
520 if len(depotPath) == 0:
521 print "Internal error: cannot locate perforce depot path from existing branches"
522 sys.exit(128)
524 self.clientPath = p4Where(depotPath)
526 if len(self.clientPath) == 0:
527 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
528 sys.exit(128)
530 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
531 self.oldWorkingDirectory = os.getcwd()
533 if self.directSubmit:
534 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
535 if len(self.diffStatus) == 0:
536 print "No changes in working directory to submit."
537 return True
538 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
539 self.diffFile = self.gitdir + "/p4-git-diff"
540 f = open(self.diffFile, "wb")
541 f.write(patch)
542 f.close();
544 os.chdir(self.clientPath)
545 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
546 if response == "y" or response == "yes":
547 system("p4 sync ...")
549 if self.reset:
550 self.firstTime = True
552 if len(self.substFile) > 0:
553 for line in open(self.substFile, "r").readlines():
554 tokens = line.strip().split("=")
555 self.logSubstitutions[tokens[0]] = tokens[1]
557 self.check()
558 self.configFile = self.gitdir + "/p4-git-sync.cfg"
559 self.config = shelve.open(self.configFile, writeback=True)
561 if self.firstTime:
562 self.start()
564 commits = self.config.get("commits", [])
566 while len(commits) > 0:
567 self.firstTime = False
568 commit = commits[0]
569 commits = commits[1:]
570 self.config["commits"] = commits
571 self.applyCommit(commit)
572 if not self.interactive:
573 break
575 self.config.close()
577 if self.directSubmit:
578 os.remove(self.diffFile)
580 if len(commits) == 0:
581 if self.firstTime:
582 print "No changes found to apply between %s and current HEAD" % self.origin
583 else:
584 print "All changes applied!"
585 os.chdir(self.oldWorkingDirectory)
586 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
587 if response == "y" or response == "yes":
588 rebase = P4Rebase()
589 rebase.run([])
590 os.remove(self.configFile)
592 return True
594 class P4Sync(Command):
595 def __init__(self):
596 Command.__init__(self)
597 self.options = [
598 optparse.make_option("--branch", dest="branch"),
599 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
600 optparse.make_option("--changesfile", dest="changesFile"),
601 optparse.make_option("--silent", dest="silent", action="store_true"),
602 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
603 optparse.make_option("--verbose", dest="verbose", action="store_true"),
604 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
605 help="Import into refs/heads/ , not refs/remotes"),
606 optparse.make_option("--max-changes", dest="maxChanges"),
607 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
608 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
610 self.description = """Imports from Perforce into a git repository.\n
611 example:
612 //depot/my/project/ -- to import the current head
613 //depot/my/project/@all -- to import everything
614 //depot/my/project/@1,6 -- to import only from revision 1 to 6
616 (a ... is not needed in the path p4 specification, it's added implicitly)"""
618 self.usage += " //depot/path[@revRange]"
619 self.silent = False
620 self.createdBranches = Set()
621 self.committedChanges = Set()
622 self.branch = ""
623 self.detectBranches = False
624 self.detectLabels = False
625 self.changesFile = ""
626 self.syncWithOrigin = True
627 self.verbose = False
628 self.importIntoRemotes = True
629 self.maxChanges = ""
630 self.isWindows = (platform.system() == "Windows")
631 self.keepRepoPath = False
632 self.depotPaths = None
634 if gitConfig("git-p4.syncFromOrigin") == "false":
635 self.syncWithOrigin = False
637 def extractFilesFromCommit(self, commit):
638 files = []
639 fnum = 0
640 while commit.has_key("depotFile%s" % fnum):
641 path = commit["depotFile%s" % fnum]
643 found = [p for p in self.depotPaths
644 if path.startswith (p)]
645 if not found:
646 fnum = fnum + 1
647 continue
649 file = {}
650 file["path"] = path
651 file["rev"] = commit["rev%s" % fnum]
652 file["action"] = commit["action%s" % fnum]
653 file["type"] = commit["type%s" % fnum]
654 files.append(file)
655 fnum = fnum + 1
656 return files
658 def stripRepoPath(self, path, prefixes):
659 if self.keepRepoPath:
660 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
662 for p in prefixes:
663 if path.startswith(p):
664 path = path[len(p):]
666 return path
668 def splitFilesIntoBranches(self, commit):
669 branches = {}
670 fnum = 0
671 while commit.has_key("depotFile%s" % fnum):
672 path = commit["depotFile%s" % fnum]
673 found = [p for p in self.depotPaths
674 if path.startswith (p)]
675 if not found:
676 fnum = fnum + 1
677 continue
679 file = {}
680 file["path"] = path
681 file["rev"] = commit["rev%s" % fnum]
682 file["action"] = commit["action%s" % fnum]
683 file["type"] = commit["type%s" % fnum]
684 fnum = fnum + 1
686 relPath = self.stripRepoPath(path, self.depotPaths)
688 for branch in self.knownBranches.keys():
690 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
691 if relPath.startswith(branch + "/"):
692 if branch not in branches:
693 branches[branch] = []
694 branches[branch].append(file)
696 return branches
698 ## Should move this out, doesn't use SELF.
699 def readP4Files(self, files):
700 files = [f for f in files
701 if f['action'] != 'delete']
703 if not files:
704 return
706 filedata = p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f['path'],
707 f['rev'])
708 for f in files]))
710 j = 0;
711 contents = {}
712 while j < len(filedata):
713 stat = filedata[j]
714 j += 1
715 text = ''
716 while j < len(filedata) and filedata[j]['code'] in ('text',
717 'binary'):
718 text += filedata[j]['data']
719 j += 1
721 contents[stat['depotFile']] = text
723 for f in files:
724 assert not f.has_key('data')
725 f['data'] = contents[f['path']]
727 def commit(self, details, files, branch, branchPrefixes, parent = ""):
728 epoch = details["time"]
729 author = details["user"]
731 if self.verbose:
732 print "commit into %s" % branch
734 # start with reading files; if that fails, we should not
735 # create a commit.
736 new_files = []
737 for f in files:
738 if [p for p in branchPrefixes if f['path'].startswith(p)]:
739 new_files.append (f)
740 else:
741 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
742 files = new_files
743 self.readP4Files(files)
748 self.gitStream.write("commit %s\n" % branch)
749 # gitStream.write("mark :%s\n" % details["change"])
750 self.committedChanges.add(int(details["change"]))
751 committer = ""
752 if author not in self.users:
753 self.getUserMapFromPerforceServer()
754 if author in self.users:
755 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
756 else:
757 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
759 self.gitStream.write("committer %s\n" % committer)
761 self.gitStream.write("data <<EOT\n")
762 self.gitStream.write(details["desc"])
763 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
764 "options = %s]\n"
765 % (','.join (branchPrefixes), details["change"],
766 details['options']
768 self.gitStream.write("EOT\n\n")
770 if len(parent) > 0:
771 if self.verbose:
772 print "parent %s" % parent
773 self.gitStream.write("from %s\n" % parent)
775 for file in files:
776 if file["type"] == "apple":
777 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
778 continue
780 relPath = self.stripRepoPath(file['path'], branchPrefixes)
781 if file["action"] == "delete":
782 self.gitStream.write("D %s\n" % relPath)
783 else:
784 mode = 644
785 if file["type"].startswith("x"):
786 mode = 755
788 data = file['data']
790 if self.isWindows and file["type"].endswith("text"):
791 data = data.replace("\r\n", "\n")
793 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
794 self.gitStream.write("data %s\n" % len(data))
795 self.gitStream.write(data)
796 self.gitStream.write("\n")
798 self.gitStream.write("\n")
800 change = int(details["change"])
802 if self.labels.has_key(change):
803 label = self.labels[change]
804 labelDetails = label[0]
805 labelRevisions = label[1]
806 if self.verbose:
807 print "Change %s is labelled %s" % (change, labelDetails)
809 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
810 for p in branchPrefixes]))
812 if len(files) == len(labelRevisions):
814 cleanedFiles = {}
815 for info in files:
816 if info["action"] == "delete":
817 continue
818 cleanedFiles[info["depotFile"]] = info["rev"]
820 if cleanedFiles == labelRevisions:
821 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
822 self.gitStream.write("from %s\n" % branch)
824 owner = labelDetails["Owner"]
825 tagger = ""
826 if author in self.users:
827 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
828 else:
829 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
830 self.gitStream.write("tagger %s\n" % tagger)
831 self.gitStream.write("data <<EOT\n")
832 self.gitStream.write(labelDetails["Description"])
833 self.gitStream.write("EOT\n\n")
835 else:
836 if not self.silent:
837 print ("Tag %s does not match with change %s: files do not match."
838 % (labelDetails["label"], change))
840 else:
841 if not self.silent:
842 print ("Tag %s does not match with change %s: file count is different."
843 % (labelDetails["label"], change))
845 def getUserCacheFilename(self):
846 return os.environ["HOME"] + "/.gitp4-usercache.txt"
848 def getUserMapFromPerforceServer(self):
849 if self.userMapFromPerforceServer:
850 return
851 self.users = {}
853 for output in p4CmdList("users"):
854 if not output.has_key("User"):
855 continue
856 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
859 s = ''
860 for (key, val) in self.users.items():
861 s += "%s\t%s\n" % (key, val)
863 open(self.getUserCacheFilename(), "wb").write(s)
864 self.userMapFromPerforceServer = True
866 def loadUserMapFromCache(self):
867 self.users = {}
868 self.userMapFromPerforceServer = False
869 try:
870 cache = open(self.getUserCacheFilename(), "rb")
871 lines = cache.readlines()
872 cache.close()
873 for line in lines:
874 entry = line.strip().split("\t")
875 self.users[entry[0]] = entry[1]
876 except IOError:
877 self.getUserMapFromPerforceServer()
879 def getLabels(self):
880 self.labels = {}
882 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
883 if len(l) > 0 and not self.silent:
884 print "Finding files belonging to labels in %s" % `self.depotPath`
886 for output in l:
887 label = output["label"]
888 revisions = {}
889 newestChange = 0
890 if self.verbose:
891 print "Querying files for label %s" % label
892 for file in p4CmdList("files "
893 + ' '.join (["%s...@%s" % (p, label)
894 for p in self.depotPaths])):
895 revisions[file["depotFile"]] = file["rev"]
896 change = int(file["change"])
897 if change > newestChange:
898 newestChange = change
900 self.labels[newestChange] = [output, revisions]
902 if self.verbose:
903 print "Label changes: %s" % self.labels.keys()
905 def guessProjectName(self):
906 for p in self.depotPaths:
907 return p [p.strip().rfind("/") + 1:]
909 def getBranchMapping(self):
910 for info in p4CmdList("branches"):
911 details = p4Cmd("branch -o %s" % info["branch"])
912 viewIdx = 0
913 while details.has_key("View%s" % viewIdx):
914 paths = details["View%s" % viewIdx].split(" ")
915 viewIdx = viewIdx + 1
916 # require standard //depot/foo/... //depot/bar/... mapping
917 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
918 continue
919 source = paths[0]
920 destination = paths[1]
921 ## HACK
922 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
923 source = source[len(self.depotPaths[0]):-4]
924 destination = destination[len(self.depotPaths[0]):-4]
925 if destination not in self.knownBranches:
926 self.knownBranches[destination] = source
927 if source not in self.knownBranches:
928 self.knownBranches[source] = source
930 def listExistingP4GitBranches(self):
931 self.p4BranchesInGit = []
933 cmdline = "git rev-parse --symbolic "
934 if self.importIntoRemotes:
935 cmdline += " --remotes"
936 else:
937 cmdline += " --branches"
939 for line in read_pipe_lines(cmdline):
940 line = line.strip()
942 ## only import to p4/
943 if not line.startswith('p4/') or line == "p4/HEAD":
944 continue
945 branch = line
946 if self.importIntoRemotes:
947 # strip off p4
948 branch = re.sub ("^p4/", "", line)
950 self.p4BranchesInGit.append(branch)
951 self.initialParents[self.refPrefix + branch] = parseRevision(line)
953 def createOrUpdateBranchesFromOrigin(self):
954 if not self.silent:
955 print ("Creating/updating branch(es) in %s based on origin branch(es)"
956 % self.refPrefix)
958 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
959 line = line.strip()
960 if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
961 continue
963 headName = line[len("origin/"):]
964 remoteHead = self.refPrefix + headName
965 originHead = "origin/" + headName
967 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
968 if (not original.has_key('depot-paths')
969 or not original.has_key('change')):
970 continue
972 update = False
973 if not gitBranchExists(remoteHead):
974 if self.verbose:
975 print "creating %s" % remoteHead
976 update = True
977 else:
978 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
979 if settings.has_key('change') > 0:
980 if settings['depot-paths'] == original['depot-paths']:
981 originP4Change = int(original['change'])
982 p4Change = int(settings['change'])
983 if originP4Change > p4Change:
984 print ("%s (%s) is newer than %s (%s). "
985 "Updating p4 branch from origin."
986 % (originHead, originP4Change,
987 remoteHead, p4Change))
988 update = True
989 else:
990 print ("Ignoring: %s was imported from %s while "
991 "%s was imported from %s"
992 % (originHead, ','.join(original['depot-paths']),
993 remoteHead, ','.join(settings['depot-paths'])))
995 if update:
996 system("git update-ref %s %s" % (remoteHead, originHead))
998 def updateOptionDict(self, d):
999 option_keys = {}
1000 if self.keepRepoPath:
1001 option_keys['keepRepoPath'] = 1
1003 d["options"] = ' '.join(sorted(option_keys.keys()))
1005 def readOptions(self, d):
1006 self.keepRepoPath = (d.has_key('options')
1007 and ('keepRepoPath' in d['options']))
1009 def run(self, args):
1010 self.depotPaths = []
1011 self.changeRange = ""
1012 self.initialParent = ""
1013 self.previousDepotPaths = []
1015 # map from branch depot path to parent branch
1016 self.knownBranches = {}
1017 self.initialParents = {}
1018 self.hasOrigin = gitBranchExists("origin")
1020 if self.importIntoRemotes:
1021 self.refPrefix = "refs/remotes/p4/"
1022 else:
1023 self.refPrefix = "refs/heads/p4/"
1025 if self.syncWithOrigin and self.hasOrigin:
1026 if not self.silent:
1027 print "Syncing with origin first by calling git fetch origin"
1028 system("git fetch origin")
1030 if len(self.branch) == 0:
1031 self.branch = self.refPrefix + "master"
1032 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
1033 system("git update-ref %s refs/heads/p4" % self.branch)
1034 system("git branch -D p4");
1035 # create it /after/ importing, when master exists
1036 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
1037 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
1039 # TODO: should always look at previous commits,
1040 # merge with previous imports, if possible.
1041 if args == []:
1042 if self.hasOrigin:
1043 self.createOrUpdateBranchesFromOrigin()
1044 self.listExistingP4GitBranches()
1046 if len(self.p4BranchesInGit) > 1:
1047 if not self.silent:
1048 print "Importing from/into multiple branches"
1049 self.detectBranches = True
1051 if self.verbose:
1052 print "branches: %s" % self.p4BranchesInGit
1054 p4Change = 0
1055 for branch in self.p4BranchesInGit:
1056 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
1058 settings = extractSettingsGitLog(logMsg)
1060 self.readOptions(settings)
1061 if (settings.has_key('depot-paths')
1062 and settings.has_key ('change')):
1063 change = int(settings['change']) + 1
1064 p4Change = max(p4Change, change)
1066 depotPaths = sorted(settings['depot-paths'])
1067 if self.previousDepotPaths == []:
1068 self.previousDepotPaths = depotPaths
1069 else:
1070 paths = []
1071 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
1072 for i in range(0, min(len(cur), len(prev))):
1073 if cur[i] <> prev[i]:
1074 i = i - 1
1075 break
1077 paths.append (cur[:i + 1])
1079 self.previousDepotPaths = paths
1081 if p4Change > 0:
1082 self.depotPaths = sorted(self.previousDepotPaths)
1083 self.changeRange = "@%s,#head" % p4Change
1084 if not self.detectBranches:
1085 self.initialParent = parseRevision(self.branch)
1086 if not self.silent and not self.detectBranches:
1087 print "Performing incremental import into %s git branch" % self.branch
1089 if not self.branch.startswith("refs/"):
1090 self.branch = "refs/heads/" + self.branch
1092 if len(args) == 0 and self.depotPaths:
1093 if not self.silent:
1094 print "Depot paths: %s" % ' '.join(self.depotPaths)
1095 else:
1096 if self.depotPaths and self.depotPaths != args:
1097 print ("previous import used depot path %s and now %s was specified. "
1098 "This doesn't work!" % (' '.join (self.depotPaths),
1099 ' '.join (args)))
1100 sys.exit(1)
1102 self.depotPaths = sorted(args)
1104 self.revision = ""
1105 self.users = {}
1107 newPaths = []
1108 for p in self.depotPaths:
1109 if p.find("@") != -1:
1110 atIdx = p.index("@")
1111 self.changeRange = p[atIdx:]
1112 if self.changeRange == "@all":
1113 self.changeRange = ""
1114 elif ',' not in self.changeRange:
1115 self.revision = self.changeRange
1116 self.changeRange = ""
1117 p = p[0:atIdx]
1118 elif p.find("#") != -1:
1119 hashIdx = p.index("#")
1120 self.revision = p[hashIdx:]
1121 p = p[0:hashIdx]
1122 elif self.previousDepotPaths == []:
1123 self.revision = "#head"
1125 p = re.sub ("\.\.\.$", "", p)
1126 if not p.endswith("/"):
1127 p += "/"
1129 newPaths.append(p)
1131 self.depotPaths = newPaths
1134 self.loadUserMapFromCache()
1135 self.labels = {}
1136 if self.detectLabels:
1137 self.getLabels();
1139 if self.detectBranches:
1140 ## FIXME - what's a P4 projectName ?
1141 self.projectName = self.guessProjectName()
1143 if not self.hasOrigin:
1144 self.getBranchMapping();
1145 if self.verbose:
1146 print "p4-git branches: %s" % self.p4BranchesInGit
1147 print "initial parents: %s" % self.initialParents
1148 for b in self.p4BranchesInGit:
1149 if b != "master":
1151 ## FIXME
1152 b = b[len(self.projectName):]
1153 self.createdBranches.add(b)
1155 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
1157 importProcess = subprocess.Popen(["git", "fast-import"],
1158 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1159 stderr=subprocess.PIPE);
1160 self.gitOutput = importProcess.stdout
1161 self.gitStream = importProcess.stdin
1162 self.gitError = importProcess.stderr
1164 if self.revision:
1165 print "Doing initial import of %s from revision %s" % (' '.join(self.depotPaths), self.revision)
1167 details = { "user" : "git perforce import user", "time" : int(time.time()) }
1168 details["desc"] = ("Initial import of %s from the state at revision %s"
1169 % (' '.join(self.depotPaths), self.revision))
1170 details["change"] = self.revision
1171 newestRevision = 0
1173 fileCnt = 0
1174 for info in p4CmdList("files "
1175 + ' '.join(["%s...%s"
1176 % (p, self.revision)
1177 for p in self.depotPaths])):
1179 if info['code'] == 'error':
1180 sys.stderr.write("p4 returned an error: %s\n"
1181 % info['data'])
1182 sys.exit(1)
1185 change = int(info["change"])
1186 if change > newestRevision:
1187 newestRevision = change
1189 if info["action"] == "delete":
1190 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1191 #fileCnt = fileCnt + 1
1192 continue
1194 for prop in ["depotFile", "rev", "action", "type" ]:
1195 details["%s%s" % (prop, fileCnt)] = info[prop]
1197 fileCnt = fileCnt + 1
1199 details["change"] = newestRevision
1200 self.updateOptionDict(details)
1201 try:
1202 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1203 except IOError:
1204 print "IO error with git fast-import. Is your git version recent enough?"
1205 print self.gitError.read()
1207 else:
1208 changes = []
1210 if len(self.changesFile) > 0:
1211 output = open(self.changesFile).readlines()
1212 changeSet = Set()
1213 for line in output:
1214 changeSet.add(int(line))
1216 for change in changeSet:
1217 changes.append(change)
1219 changes.sort()
1220 else:
1221 if self.verbose:
1222 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
1223 self.changeRange)
1224 assert self.depotPaths
1225 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1226 for p in self.depotPaths]))
1228 for line in output:
1229 changeNum = line.split(" ")[1]
1230 changes.append(changeNum)
1232 changes.reverse()
1234 if len(self.maxChanges) > 0:
1235 changes = changes[0:min(int(self.maxChanges), len(changes))]
1237 if len(changes) == 0:
1238 if not self.silent:
1239 print "No changes to import!"
1240 return True
1242 self.updatedBranches = set()
1244 cnt = 1
1245 for change in changes:
1246 description = p4Cmd("describe %s" % change)
1247 self.updateOptionDict(description)
1249 if not self.silent:
1250 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1251 sys.stdout.flush()
1252 cnt = cnt + 1
1254 try:
1255 if self.detectBranches:
1256 branches = self.splitFilesIntoBranches(description)
1257 for branch in branches.keys():
1258 ## HACK --hwn
1259 branchPrefix = self.depotPaths[0] + branch + "/"
1261 parent = ""
1263 filesForCommit = branches[branch]
1265 if self.verbose:
1266 print "branch is %s" % branch
1268 self.updatedBranches.add(branch)
1270 if branch not in self.createdBranches:
1271 self.createdBranches.add(branch)
1272 parent = self.knownBranches[branch]
1273 if parent == branch:
1274 parent = ""
1275 elif self.verbose:
1276 print "parent determined through known branches: %s" % parent
1278 # main branch? use master
1279 if branch == "main":
1280 branch = "master"
1281 else:
1283 ## FIXME
1284 branch = self.projectName + branch
1286 if parent == "main":
1287 parent = "master"
1288 elif len(parent) > 0:
1289 ## FIXME
1290 parent = self.projectName + parent
1292 branch = self.refPrefix + branch
1293 if len(parent) > 0:
1294 parent = self.refPrefix + parent
1296 if self.verbose:
1297 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1299 if len(parent) == 0 and branch in self.initialParents:
1300 parent = self.initialParents[branch]
1301 del self.initialParents[branch]
1303 self.commit(description, filesForCommit, branch, branchPrefix, parent)
1304 else:
1305 files = self.extractFilesFromCommit(description)
1306 self.commit(description, files, self.branch, self.depotPaths,
1307 self.initialParent)
1308 self.initialParent = ""
1309 except IOError:
1310 print self.gitError.read()
1311 sys.exit(1)
1313 if not self.silent:
1314 print ""
1315 if len(self.updatedBranches) > 0:
1316 sys.stdout.write("Updated branches: ")
1317 for b in self.updatedBranches:
1318 sys.stdout.write("%s " % b)
1319 sys.stdout.write("\n")
1322 self.gitStream.close()
1323 if importProcess.wait() != 0:
1324 die("fast-import failed: %s" % self.gitError.read())
1325 self.gitOutput.close()
1326 self.gitError.close()
1328 return True
1330 class P4Rebase(Command):
1331 def __init__(self):
1332 Command.__init__(self)
1333 self.options = [ ]
1334 self.description = ("Fetches the latest revision from perforce and "
1335 + "rebases the current work (branch) against it")
1336 self.verbose = False
1338 def run(self, args):
1339 sync = P4Sync()
1340 sync.run([])
1341 print "Rebasing the current branch"
1342 oldHead = read_pipe("git rev-parse HEAD").strip()
1343 system("git rebase p4")
1344 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1345 return True
1347 class P4Clone(P4Sync):
1348 def __init__(self):
1349 P4Sync.__init__(self)
1350 self.description = "Creates a new git repository and imports from Perforce into it"
1351 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1352 self.options.append(
1353 optparse.make_option("--destination", dest="cloneDestination",
1354 action='store', default=None,
1355 help="where to leave result of the clone"))
1356 self.cloneDestination = None
1357 self.needsGit = False
1359 def defaultDestination(self, args):
1360 ## TODO: use common prefix of args?
1361 depotPath = args[0]
1362 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1363 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1364 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1365 depotDir = re.sub(r"/$", "", depotDir)
1366 return os.path.split(depotDir)[1]
1368 def run(self, args):
1369 if len(args) < 1:
1370 return False
1372 if self.keepRepoPath and not self.cloneDestination:
1373 sys.stderr.write("Must specify destination for --keep-path\n")
1374 sys.exit(1)
1376 depotPaths = args
1378 if not self.cloneDestination and len(depotPaths) > 1:
1379 self.cloneDestination = depotPaths[-1]
1380 depotPaths = depotPaths[:-1]
1382 for p in depotPaths:
1383 if not p.startswith("//"):
1384 return False
1386 if not self.cloneDestination:
1387 self.cloneDestination = self.defaultDestination(args)
1389 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
1390 os.makedirs(self.cloneDestination)
1391 os.chdir(self.cloneDestination)
1392 system("git init")
1393 self.gitdir = os.getcwd() + "/.git"
1394 if not P4Sync.run(self, depotPaths):
1395 return False
1396 if self.branch != "master":
1397 if gitBranchExists("refs/remotes/p4/master"):
1398 system("git branch master refs/remotes/p4/master")
1399 system("git checkout -f")
1400 else:
1401 print "Could not detect main branch. No checkout/master branch created."
1403 return True
1405 class HelpFormatter(optparse.IndentedHelpFormatter):
1406 def __init__(self):
1407 optparse.IndentedHelpFormatter.__init__(self)
1409 def format_description(self, description):
1410 if description:
1411 return description + "\n"
1412 else:
1413 return ""
1415 def printUsage(commands):
1416 print "usage: %s <command> [options]" % sys.argv[0]
1417 print ""
1418 print "valid commands: %s" % ", ".join(commands)
1419 print ""
1420 print "Try %s <command> --help for command specific help." % sys.argv[0]
1421 print ""
1423 commands = {
1424 "debug" : P4Debug,
1425 "submit" : P4Submit,
1426 "sync" : P4Sync,
1427 "rebase" : P4Rebase,
1428 "clone" : P4Clone,
1429 "rollback" : P4RollBack
1433 def main():
1434 if len(sys.argv[1:]) == 0:
1435 printUsage(commands.keys())
1436 sys.exit(2)
1438 cmd = ""
1439 cmdName = sys.argv[1]
1440 try:
1441 klass = commands[cmdName]
1442 cmd = klass()
1443 except KeyError:
1444 print "unknown command %s" % cmdName
1445 print ""
1446 printUsage(commands.keys())
1447 sys.exit(2)
1449 options = cmd.options
1450 cmd.gitdir = os.environ.get("GIT_DIR", None)
1452 args = sys.argv[2:]
1454 if len(options) > 0:
1455 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1457 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1458 options,
1459 description = cmd.description,
1460 formatter = HelpFormatter())
1462 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1463 global verbose
1464 verbose = cmd.verbose
1465 if cmd.needsGit:
1466 if cmd.gitdir == None:
1467 cmd.gitdir = os.path.abspath(".git")
1468 if not isValidGitDir(cmd.gitdir):
1469 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1470 if os.path.exists(cmd.gitdir):
1471 cdup = read_pipe("git rev-parse --show-cdup").strip()
1472 if len(cdup) > 0:
1473 os.chdir(cdup);
1475 if not isValidGitDir(cmd.gitdir):
1476 if isValidGitDir(cmd.gitdir + "/.git"):
1477 cmd.gitdir += "/.git"
1478 else:
1479 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
1481 os.environ["GIT_DIR"] = cmd.gitdir
1483 if not cmd.run(args):
1484 parser.print_help()
1487 if __name__ == '__main__':
1488 main()