Fix error detection with git-p4 submit when the requested depot path is not in the...
[fast-export/barak.git] / git-p4
blob73da5d2b27bd8455446f47da1386bbf575dd518f
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: * implement git-p4 rollback <perforce change number> for debugging
11 # to roll back all p4 remote branches to a commit older or equal to
12 # the specified change.
13 # * for git-p4 submit --direct it would be nice to still create a
14 # git commit without updating HEAD before submitting to perforce.
15 # With the commit sha1 printed (or recoded in a .git/foo file?)
16 # it's possible to recover if anything goes wrong instead of potentially
17 # loosing a change entirely because it was never comitted to git and
18 # the p4 submit failed (or resulted in lots of conflicts, etc.)
19 # * Consider making --with-origin the default, assuming that the git
20 # protocol is always more efficient. (needs manual testing first :)
23 import optparse, sys, os, marshal, popen2, subprocess, shelve
24 import tempfile, getopt, sha, os.path, time, platform
25 from sets import Set;
27 gitdir = os.environ.get("GIT_DIR", "")
29 def mypopen(command):
30 return os.popen(command, "rb");
32 def p4CmdList(cmd):
33 cmd = "p4 -G %s" % cmd
34 pipe = os.popen(cmd, "rb")
36 result = []
37 try:
38 while True:
39 entry = marshal.load(pipe)
40 result.append(entry)
41 except EOFError:
42 pass
43 pipe.close()
45 return result
47 def p4Cmd(cmd):
48 list = p4CmdList(cmd)
49 result = {}
50 for entry in list:
51 result.update(entry)
52 return result;
54 def p4Where(depotPath):
55 if not depotPath.endswith("/"):
56 depotPath += "/"
57 output = p4Cmd("where %s..." % depotPath)
58 if output["code"] == "error":
59 return ""
60 clientPath = ""
61 if "path" in output:
62 clientPath = output.get("path")
63 elif "data" in output:
64 data = output.get("data")
65 lastSpace = data.rfind(" ")
66 clientPath = data[lastSpace + 1:]
68 if clientPath.endswith("..."):
69 clientPath = clientPath[:-3]
70 return clientPath
72 def die(msg):
73 sys.stderr.write(msg + "\n")
74 sys.exit(1)
76 def currentGitBranch():
77 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
79 def isValidGitDir(path):
80 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
81 return True;
82 return False
84 def parseRevision(ref):
85 return mypopen("git rev-parse %s" % ref).read()[:-1]
87 def system(cmd):
88 if os.system(cmd) != 0:
89 die("command failed: %s" % cmd)
91 def extractLogMessageFromGitCommit(commit):
92 logMessage = ""
93 foundTitle = False
94 for log in mypopen("git cat-file commit %s" % commit).readlines():
95 if not foundTitle:
96 if len(log) == 1:
97 foundTitle = True
98 continue
100 logMessage += log
101 return logMessage
103 def extractDepotPathAndChangeFromGitLog(log):
104 values = {}
105 for line in log.split("\n"):
106 line = line.strip()
107 if line.startswith("[git-p4:") and line.endswith("]"):
108 line = line[8:-1].strip()
109 for assignment in line.split(":"):
110 variable = assignment.strip()
111 value = ""
112 equalPos = assignment.find("=")
113 if equalPos != -1:
114 variable = assignment[:equalPos].strip()
115 value = assignment[equalPos + 1:].strip()
116 if value.startswith("\"") and value.endswith("\""):
117 value = value[1:-1]
118 values[variable] = value
120 return values.get("depot-path"), values.get("change")
122 def gitBranchExists(branch):
123 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
124 return proc.wait() == 0;
126 class Command:
127 def __init__(self):
128 self.usage = "usage: %prog [options]"
129 self.needsGit = True
131 class P4Debug(Command):
132 def __init__(self):
133 Command.__init__(self)
134 self.options = [
136 self.description = "A tool to debug the output of p4 -G."
137 self.needsGit = False
139 def run(self, args):
140 for output in p4CmdList(" ".join(args)):
141 print output
142 return True
144 class P4Submit(Command):
145 def __init__(self):
146 Command.__init__(self)
147 self.options = [
148 optparse.make_option("--continue", action="store_false", dest="firstTime"),
149 optparse.make_option("--origin", dest="origin"),
150 optparse.make_option("--reset", action="store_true", dest="reset"),
151 optparse.make_option("--log-substitutions", dest="substFile"),
152 optparse.make_option("--noninteractive", action="store_false"),
153 optparse.make_option("--dry-run", action="store_true"),
154 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
156 self.description = "Submit changes from git to the perforce depot."
157 self.usage += " [name of git branch to submit into perforce depot]"
158 self.firstTime = True
159 self.reset = False
160 self.interactive = True
161 self.dryRun = False
162 self.substFile = ""
163 self.firstTime = True
164 self.origin = ""
165 self.directSubmit = False
167 self.logSubstitutions = {}
168 self.logSubstitutions["<enter description here>"] = "%log%"
169 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
171 def check(self):
172 if len(p4CmdList("opened ...")) > 0:
173 die("You have files opened with perforce! Close them before starting the sync.")
175 def start(self):
176 if len(self.config) > 0 and not self.reset:
177 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)
179 commits = []
180 if self.directSubmit:
181 commits.append("0")
182 else:
183 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
184 commits.append(line[:-1])
185 commits.reverse()
187 self.config["commits"] = commits
189 def prepareLogMessage(self, template, message):
190 result = ""
192 for line in template.split("\n"):
193 if line.startswith("#"):
194 result += line + "\n"
195 continue
197 substituted = False
198 for key in self.logSubstitutions.keys():
199 if line.find(key) != -1:
200 value = self.logSubstitutions[key]
201 value = value.replace("%log%", message)
202 if value != "@remove@":
203 result += line.replace(key, value) + "\n"
204 substituted = True
205 break
207 if not substituted:
208 result += line + "\n"
210 return result
212 def apply(self, id):
213 if self.directSubmit:
214 print "Applying local change in working directory/index"
215 diff = self.diffStatus
216 else:
217 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
218 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
219 filesToAdd = set()
220 filesToDelete = set()
221 editedFiles = set()
222 for line in diff:
223 modifier = line[0]
224 path = line[1:].strip()
225 if modifier == "M":
226 system("p4 edit \"%s\"" % path)
227 editedFiles.add(path)
228 elif modifier == "A":
229 filesToAdd.add(path)
230 if path in filesToDelete:
231 filesToDelete.remove(path)
232 elif modifier == "D":
233 filesToDelete.add(path)
234 if path in filesToAdd:
235 filesToAdd.remove(path)
236 else:
237 die("unknown modifier %s for %s" % (modifier, path))
239 if self.directSubmit:
240 diffcmd = "cat \"%s\"" % self.diffFile
241 else:
242 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
243 patchcmd = diffcmd + " | git apply "
244 tryPatchCmd = patchcmd + "--check -"
245 applyPatchCmd = patchcmd + "--check --apply -"
247 if os.system(tryPatchCmd) != 0:
248 print "Unfortunately applying the change failed!"
249 print "What do you want to do?"
250 response = "x"
251 while response != "s" and response != "a" and response != "w":
252 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) ")
253 if response == "s":
254 print "Skipping! Good luck with the next patches..."
255 return
256 elif response == "a":
257 os.system(applyPatchCmd)
258 if len(filesToAdd) > 0:
259 print "You may also want to call p4 add on the following files:"
260 print " ".join(filesToAdd)
261 if len(filesToDelete):
262 print "The following files should be scheduled for deletion with p4 delete:"
263 print " ".join(filesToDelete)
264 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
265 elif response == "w":
266 system(diffcmd + " > patch.txt")
267 print "Patch saved to patch.txt in %s !" % self.clientPath
268 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
270 system(applyPatchCmd)
272 for f in filesToAdd:
273 system("p4 add %s" % f)
274 for f in filesToDelete:
275 system("p4 revert %s" % f)
276 system("p4 delete %s" % f)
278 logMessage = ""
279 if not self.directSubmit:
280 logMessage = extractLogMessageFromGitCommit(id)
281 logMessage = logMessage.replace("\n", "\n\t")
282 logMessage = logMessage[:-1]
284 template = mypopen("p4 change -o").read()
286 if self.interactive:
287 submitTemplate = self.prepareLogMessage(template, logMessage)
288 diff = mypopen("p4 diff -du ...").read()
290 for newFile in filesToAdd:
291 diff += "==== new file ====\n"
292 diff += "--- /dev/null\n"
293 diff += "+++ %s\n" % newFile
294 f = open(newFile, "r")
295 for line in f.readlines():
296 diff += "+" + line
297 f.close()
299 separatorLine = "######## everything below this line is just the diff #######"
300 if platform.system() == "Windows":
301 separatorLine += "\r"
302 separatorLine += "\n"
304 response = "e"
305 firstIteration = True
306 while response == "e":
307 if not firstIteration:
308 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
309 firstIteration = False
310 if response == "e":
311 [handle, fileName] = tempfile.mkstemp()
312 tmpFile = os.fdopen(handle, "w+")
313 tmpFile.write(submitTemplate + separatorLine + diff)
314 tmpFile.close()
315 defaultEditor = "vi"
316 if platform.system() == "Windows":
317 defaultEditor = "notepad"
318 editor = os.environ.get("EDITOR", defaultEditor);
319 system(editor + " " + fileName)
320 tmpFile = open(fileName, "rb")
321 message = tmpFile.read()
322 tmpFile.close()
323 os.remove(fileName)
324 submitTemplate = message[:message.index(separatorLine)]
326 if response == "y" or response == "yes":
327 if self.dryRun:
328 print submitTemplate
329 raw_input("Press return to continue...")
330 else:
331 pipe = os.popen("p4 submit -i", "wb")
332 pipe.write(submitTemplate)
333 pipe.close()
334 elif response == "s":
335 for f in editedFiles:
336 system("p4 revert \"%s\"" % f);
337 for f in filesToAdd:
338 system("p4 revert \"%s\"" % f);
339 system("rm %s" %f)
340 for f in filesToDelete:
341 system("p4 delete \"%s\"" % f);
342 return
343 else:
344 print "Not submitting!"
345 self.interactive = False
346 else:
347 fileName = "submit.txt"
348 file = open(fileName, "w+")
349 file.write(self.prepareLogMessage(template, logMessage))
350 file.close()
351 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
353 def run(self, args):
354 global gitdir
355 # make gitdir absolute so we can cd out into the perforce checkout
356 gitdir = os.path.abspath(gitdir)
357 os.environ["GIT_DIR"] = gitdir
359 if len(args) == 0:
360 self.master = currentGitBranch()
361 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
362 die("Detecting current git branch failed!")
363 elif len(args) == 1:
364 self.master = args[0]
365 else:
366 return False
368 depotPath = ""
369 if gitBranchExists("p4"):
370 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
371 if len(depotPath) == 0 and gitBranchExists("origin"):
372 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
374 if len(depotPath) == 0:
375 print "Internal error: cannot locate perforce depot path from existing branches"
376 sys.exit(128)
378 self.clientPath = p4Where(depotPath)
380 if len(self.clientPath) == 0:
381 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
382 sys.exit(128)
384 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
385 oldWorkingDirectory = os.getcwd()
387 if self.directSubmit:
388 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
389 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
390 self.diffFile = gitdir + "/p4-git-diff"
391 f = open(self.diffFile, "wb")
392 f.write(patch)
393 f.close();
395 os.chdir(self.clientPath)
396 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
397 if response == "y" or response == "yes":
398 system("p4 sync ...")
400 if len(self.origin) == 0:
401 if gitBranchExists("p4"):
402 self.origin = "p4"
403 else:
404 self.origin = "origin"
406 if self.reset:
407 self.firstTime = True
409 if len(self.substFile) > 0:
410 for line in open(self.substFile, "r").readlines():
411 tokens = line[:-1].split("=")
412 self.logSubstitutions[tokens[0]] = tokens[1]
414 self.check()
415 self.configFile = gitdir + "/p4-git-sync.cfg"
416 self.config = shelve.open(self.configFile, writeback=True)
418 if self.firstTime:
419 self.start()
421 commits = self.config.get("commits", [])
423 while len(commits) > 0:
424 self.firstTime = False
425 commit = commits[0]
426 commits = commits[1:]
427 self.config["commits"] = commits
428 self.apply(commit)
429 if not self.interactive:
430 break
432 self.config.close()
434 if self.directSubmit:
435 os.remove(self.diffFile)
437 if len(commits) == 0:
438 if self.firstTime:
439 print "No changes found to apply between %s and current HEAD" % self.origin
440 else:
441 print "All changes applied!"
442 response = ""
443 os.chdir(oldWorkingDirectory)
445 if self.directSubmit:
446 response = raw_input("Do you want to DISCARD your git WORKING DIRECTORY CHANGES and sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
447 if response == "y" or response == "yes":
448 system("git reset --hard")
450 if len(response) == 0:
451 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
452 if response == "y" or response == "yes":
453 rebase = P4Rebase()
454 rebase.run([])
455 os.remove(self.configFile)
457 return True
459 class P4Sync(Command):
460 def __init__(self):
461 Command.__init__(self)
462 self.options = [
463 optparse.make_option("--branch", dest="branch"),
464 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
465 optparse.make_option("--changesfile", dest="changesFile"),
466 optparse.make_option("--silent", dest="silent", action="store_true"),
467 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
468 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
469 optparse.make_option("--verbose", dest="verbose", action="store_true")
471 self.description = """Imports from Perforce into a git repository.\n
472 example:
473 //depot/my/project/ -- to import the current head
474 //depot/my/project/@all -- to import everything
475 //depot/my/project/@1,6 -- to import only from revision 1 to 6
477 (a ... is not needed in the path p4 specification, it's added implicitly)"""
479 self.usage += " //depot/path[@revRange]"
481 self.silent = False
482 self.createdBranches = Set()
483 self.committedChanges = Set()
484 self.branch = ""
485 self.detectBranches = False
486 self.detectLabels = False
487 self.changesFile = ""
488 self.syncWithOrigin = False
489 self.verbose = False
491 def p4File(self, depotPath):
492 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
494 def extractFilesFromCommit(self, commit):
495 files = []
496 fnum = 0
497 while commit.has_key("depotFile%s" % fnum):
498 path = commit["depotFile%s" % fnum]
499 if not path.startswith(self.depotPath):
500 # if not self.silent:
501 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
502 fnum = fnum + 1
503 continue
505 file = {}
506 file["path"] = path
507 file["rev"] = commit["rev%s" % fnum]
508 file["action"] = commit["action%s" % fnum]
509 file["type"] = commit["type%s" % fnum]
510 files.append(file)
511 fnum = fnum + 1
512 return files
514 def splitFilesIntoBranches(self, commit):
515 branches = {}
517 fnum = 0
518 while commit.has_key("depotFile%s" % fnum):
519 path = commit["depotFile%s" % fnum]
520 if not path.startswith(self.depotPath):
521 # if not self.silent:
522 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
523 fnum = fnum + 1
524 continue
526 file = {}
527 file["path"] = path
528 file["rev"] = commit["rev%s" % fnum]
529 file["action"] = commit["action%s" % fnum]
530 file["type"] = commit["type%s" % fnum]
531 fnum = fnum + 1
533 relPath = path[len(self.depotPath):]
535 for branch in self.knownBranches.keys():
536 if relPath.startswith(branch):
537 if branch not in branches:
538 branches[branch] = []
539 branches[branch].append(file)
541 return branches
543 def commit(self, details, files, branch, branchPrefix, parent = ""):
544 epoch = details["time"]
545 author = details["user"]
547 if self.verbose:
548 print "commit into %s" % branch
550 self.gitStream.write("commit %s\n" % branch)
551 # gitStream.write("mark :%s\n" % details["change"])
552 self.committedChanges.add(int(details["change"]))
553 committer = ""
554 if author not in self.users:
555 self.getUserMapFromPerforceServer()
556 if author in self.users:
557 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
558 else:
559 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
561 self.gitStream.write("committer %s\n" % committer)
563 self.gitStream.write("data <<EOT\n")
564 self.gitStream.write(details["desc"])
565 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
566 self.gitStream.write("EOT\n\n")
568 if len(parent) > 0:
569 if self.verbose:
570 print "parent %s" % parent
571 self.gitStream.write("from %s\n" % parent)
573 for file in files:
574 path = file["path"]
575 if not path.startswith(branchPrefix):
576 # if not silent:
577 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
578 continue
579 rev = file["rev"]
580 depotPath = path + "#" + rev
581 relPath = path[len(branchPrefix):]
582 action = file["action"]
584 if file["type"] == "apple":
585 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
586 continue
588 if action == "delete":
589 self.gitStream.write("D %s\n" % relPath)
590 else:
591 mode = 644
592 if file["type"].startswith("x"):
593 mode = 755
595 data = self.p4File(depotPath)
597 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
598 self.gitStream.write("data %s\n" % len(data))
599 self.gitStream.write(data)
600 self.gitStream.write("\n")
602 self.gitStream.write("\n")
604 change = int(details["change"])
606 if self.labels.has_key(change):
607 label = self.labels[change]
608 labelDetails = label[0]
609 labelRevisions = label[1]
610 if self.verbose:
611 print "Change %s is labelled %s" % (change, labelDetails)
613 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
615 if len(files) == len(labelRevisions):
617 cleanedFiles = {}
618 for info in files:
619 if info["action"] == "delete":
620 continue
621 cleanedFiles[info["depotFile"]] = info["rev"]
623 if cleanedFiles == labelRevisions:
624 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
625 self.gitStream.write("from %s\n" % branch)
627 owner = labelDetails["Owner"]
628 tagger = ""
629 if author in self.users:
630 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
631 else:
632 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
633 self.gitStream.write("tagger %s\n" % tagger)
634 self.gitStream.write("data <<EOT\n")
635 self.gitStream.write(labelDetails["Description"])
636 self.gitStream.write("EOT\n\n")
638 else:
639 if not self.silent:
640 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
642 else:
643 if not self.silent:
644 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
646 def getUserMapFromPerforceServer(self):
647 self.users = {}
649 for output in p4CmdList("users"):
650 if not output.has_key("User"):
651 continue
652 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
654 cache = open(gitdir + "/p4-usercache.txt", "wb")
655 for user in self.users.keys():
656 cache.write("%s\t%s\n" % (user, self.users[user]))
657 cache.close();
659 def loadUserMapFromCache(self):
660 self.users = {}
661 try:
662 cache = open(gitdir + "/p4-usercache.txt", "rb")
663 lines = cache.readlines()
664 cache.close()
665 for line in lines:
666 entry = line[:-1].split("\t")
667 self.users[entry[0]] = entry[1]
668 except IOError:
669 self.getUserMapFromPerforceServer()
671 def getLabels(self):
672 self.labels = {}
674 l = p4CmdList("labels %s..." % self.depotPath)
675 if len(l) > 0 and not self.silent:
676 print "Finding files belonging to labels in %s" % self.depotPath
678 for output in l:
679 label = output["label"]
680 revisions = {}
681 newestChange = 0
682 if self.verbose:
683 print "Querying files for label %s" % label
684 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
685 revisions[file["depotFile"]] = file["rev"]
686 change = int(file["change"])
687 if change > newestChange:
688 newestChange = change
690 self.labels[newestChange] = [output, revisions]
692 if self.verbose:
693 print "Label changes: %s" % self.labels.keys()
695 def getBranchMapping(self):
696 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
698 for info in p4CmdList("branches"):
699 details = p4Cmd("branch -o %s" % info["branch"])
700 viewIdx = 0
701 while details.has_key("View%s" % viewIdx):
702 paths = details["View%s" % viewIdx].split(" ")
703 viewIdx = viewIdx + 1
704 # require standard //depot/foo/... //depot/bar/... mapping
705 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
706 continue
707 source = paths[0]
708 destination = paths[1]
709 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
710 source = source[len(self.depotPath):-4]
711 destination = destination[len(self.depotPath):-4]
712 if destination not in self.knownBranches:
713 self.knownBranches[destination] = source
714 if source not in self.knownBranches:
715 self.knownBranches[source] = source
717 def listExistingP4GitBranches(self):
718 self.p4BranchesInGit = []
720 for line in mypopen("git rev-parse --symbolic --remotes").readlines():
721 if line.startswith("p4/") and line != "p4/HEAD\n":
722 branch = line[3:-1]
723 self.p4BranchesInGit.append(branch)
724 self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1])
726 def run(self, args):
727 self.depotPath = ""
728 self.changeRange = ""
729 self.initialParent = ""
730 self.previousDepotPath = ""
731 # map from branch depot path to parent branch
732 self.knownBranches = {}
733 self.initialParents = {}
735 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
736 ### needs to be ported to multi branch import
738 print "Syncing with origin first as requested by calling git fetch origin"
739 system("git fetch origin")
740 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
741 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
742 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
743 if originPreviousDepotPath == p4PreviousDepotPath:
744 originP4Change = int(originP4Change)
745 p4Change = int(p4Change)
746 if originP4Change > p4Change:
747 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
748 system("git update-ref refs/remotes/p4/master origin");
749 else:
750 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
752 if len(self.branch) == 0:
753 self.branch = "refs/remotes/p4/master"
754 if gitBranchExists("refs/heads/p4"):
755 system("git update-ref %s refs/heads/p4" % self.branch)
756 system("git branch -D p4");
757 if not gitBranchExists("refs/remotes/p4/HEAD"):
758 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
760 # this needs to be called after the conversion from heads/p4 to remotes/p4/master
761 self.listExistingP4GitBranches()
762 if len(self.p4BranchesInGit) > 1 and not self.silent:
763 print "Importing from/into multiple branches"
764 self.detectBranches = True
766 if len(args) == 0:
767 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
768 ### needs to be ported to multi branch import
769 if not self.silent:
770 print "Creating %s branch in git repository based on origin" % self.branch
771 branch = self.branch
772 if not branch.startswith("refs"):
773 branch = "refs/heads/" + branch
774 system("git update-ref %s origin" % branch)
776 if self.verbose:
777 print "branches: %s" % self.p4BranchesInGit
779 p4Change = 0
780 for branch in self.p4BranchesInGit:
781 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
783 if self.verbose:
784 print "path %s change %s" % (depotPath, change)
786 if len(depotPath) > 0 and len(change) > 0:
787 change = int(change) + 1
788 p4Change = max(p4Change, change)
790 if len(self.previousDepotPath) == 0:
791 self.previousDepotPath = depotPath
792 else:
793 i = 0
794 l = min(len(self.previousDepotPath), len(depotPath))
795 while i < l and self.previousDepotPath[i] == depotPath[i]:
796 i = i + 1
797 self.previousDepotPath = self.previousDepotPath[:i]
799 if p4Change > 0:
800 self.depotPath = self.previousDepotPath
801 self.changeRange = "@%s,#head" % p4Change
802 self.initialParent = parseRevision(self.branch)
803 if not self.silent and not self.detectBranches:
804 print "Performing incremental import into %s git branch" % self.branch
806 if not self.branch.startswith("refs/"):
807 self.branch = "refs/heads/" + self.branch
809 if len(self.depotPath) != 0:
810 self.depotPath = self.depotPath[:-1]
812 if len(args) == 0 and len(self.depotPath) != 0:
813 if not self.silent:
814 print "Depot path: %s" % self.depotPath
815 elif len(args) != 1:
816 return False
817 else:
818 if len(self.depotPath) != 0 and self.depotPath != args[0]:
819 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
820 sys.exit(1)
821 self.depotPath = args[0]
823 self.revision = ""
824 self.users = {}
826 if self.depotPath.find("@") != -1:
827 atIdx = self.depotPath.index("@")
828 self.changeRange = self.depotPath[atIdx:]
829 if self.changeRange == "@all":
830 self.changeRange = ""
831 elif self.changeRange.find(",") == -1:
832 self.revision = self.changeRange
833 self.changeRange = ""
834 self.depotPath = self.depotPath[0:atIdx]
835 elif self.depotPath.find("#") != -1:
836 hashIdx = self.depotPath.index("#")
837 self.revision = self.depotPath[hashIdx:]
838 self.depotPath = self.depotPath[0:hashIdx]
839 elif len(self.previousDepotPath) == 0:
840 self.revision = "#head"
842 if self.depotPath.endswith("..."):
843 self.depotPath = self.depotPath[:-3]
845 if not self.depotPath.endswith("/"):
846 self.depotPath += "/"
848 self.loadUserMapFromCache()
849 self.labels = {}
850 if self.detectLabels:
851 self.getLabels();
853 if self.detectBranches:
854 self.getBranchMapping();
855 if self.verbose:
856 print "p4-git branches: %s" % self.p4BranchesInGit
857 print "initial parents: %s" % self.initialParents
858 for b in self.p4BranchesInGit:
859 if b != "master":
860 b = b[len(self.projectName):]
861 self.createdBranches.add(b)
863 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
865 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
866 self.gitOutput = importProcess.stdout
867 self.gitStream = importProcess.stdin
868 self.gitError = importProcess.stderr
870 if len(self.revision) > 0:
871 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
873 details = { "user" : "git perforce import user", "time" : int(time.time()) }
874 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
875 details["change"] = self.revision
876 newestRevision = 0
878 fileCnt = 0
879 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
880 change = int(info["change"])
881 if change > newestRevision:
882 newestRevision = change
884 if info["action"] == "delete":
885 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
886 #fileCnt = fileCnt + 1
887 continue
889 for prop in [ "depotFile", "rev", "action", "type" ]:
890 details["%s%s" % (prop, fileCnt)] = info[prop]
892 fileCnt = fileCnt + 1
894 details["change"] = newestRevision
896 try:
897 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
898 except IOError:
899 print "IO error with git fast-import. Is your git version recent enough?"
900 print self.gitError.read()
902 else:
903 changes = []
905 if len(self.changesFile) > 0:
906 output = open(self.changesFile).readlines()
907 changeSet = Set()
908 for line in output:
909 changeSet.add(int(line))
911 for change in changeSet:
912 changes.append(change)
914 changes.sort()
915 else:
916 if self.verbose:
917 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
918 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
920 for line in output:
921 changeNum = line.split(" ")[1]
922 changes.append(changeNum)
924 changes.reverse()
926 if len(changes) == 0:
927 if not self.silent:
928 print "No changes to import!"
929 return True
931 self.updatedBranches = set()
933 cnt = 1
934 for change in changes:
935 description = p4Cmd("describe %s" % change)
937 if not self.silent:
938 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
939 sys.stdout.flush()
940 cnt = cnt + 1
942 try:
943 if self.detectBranches:
944 branches = self.splitFilesIntoBranches(description)
945 for branch in branches.keys():
946 branchPrefix = self.depotPath + branch + "/"
948 parent = ""
950 filesForCommit = branches[branch]
952 if self.verbose:
953 print "branch is %s" % branch
955 self.updatedBranches.add(branch)
957 if branch not in self.createdBranches:
958 self.createdBranches.add(branch)
959 parent = self.knownBranches[branch]
960 if parent == branch:
961 parent = ""
962 elif self.verbose:
963 print "parent determined through known branches: %s" % parent
965 # main branch? use master
966 if branch == "main":
967 branch = "master"
968 else:
969 branch = self.projectName + branch
971 if parent == "main":
972 parent = "master"
973 elif len(parent) > 0:
974 parent = self.projectName + parent
976 branch = "refs/remotes/p4/" + branch
977 if len(parent) > 0:
978 parent = "refs/remotes/p4/" + parent
980 if self.verbose:
981 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
983 if len(parent) == 0 and branch in self.initialParents:
984 parent = self.initialParents[branch]
985 del self.initialParents[branch]
987 self.commit(description, filesForCommit, branch, branchPrefix, parent)
988 else:
989 files = self.extractFilesFromCommit(description)
990 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
991 self.initialParent = ""
992 except IOError:
993 print self.gitError.read()
994 sys.exit(1)
996 if not self.silent:
997 print ""
998 if len(self.updatedBranches) > 0:
999 sys.stdout.write("Updated branches: ")
1000 for b in self.updatedBranches:
1001 sys.stdout.write("%s " % b)
1002 sys.stdout.write("\n")
1005 self.gitStream.close()
1006 if importProcess.wait() != 0:
1007 die("fast-import failed: %s" % self.gitError.read())
1008 self.gitOutput.close()
1009 self.gitError.close()
1011 return True
1013 class P4Rebase(Command):
1014 def __init__(self):
1015 Command.__init__(self)
1016 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
1017 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1018 self.syncWithOrigin = False
1020 def run(self, args):
1021 sync = P4Sync()
1022 sync.syncWithOrigin = self.syncWithOrigin
1023 sync.run([])
1024 print "Rebasing the current branch"
1025 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1026 system("git rebase p4")
1027 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1028 return True
1030 class P4Clone(P4Sync):
1031 def __init__(self):
1032 P4Sync.__init__(self)
1033 self.description = "Creates a new git repository and imports from Perforce into it"
1034 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1035 self.needsGit = False
1037 def run(self, args):
1038 global gitdir
1040 if len(args) < 1:
1041 return False
1042 depotPath = args[0]
1043 dir = ""
1044 if len(args) == 2:
1045 dir = args[1]
1046 elif len(args) > 2:
1047 return False
1049 if not depotPath.startswith("//"):
1050 return False
1052 if len(dir) == 0:
1053 dir = depotPath
1054 atPos = dir.rfind("@")
1055 if atPos != -1:
1056 dir = dir[0:atPos]
1057 hashPos = dir.rfind("#")
1058 if hashPos != -1:
1059 dir = dir[0:hashPos]
1061 if dir.endswith("..."):
1062 dir = dir[:-3]
1064 if dir.endswith("/"):
1065 dir = dir[:-1]
1067 slashPos = dir.rfind("/")
1068 if slashPos != -1:
1069 dir = dir[slashPos + 1:]
1071 print "Importing from %s into %s" % (depotPath, dir)
1072 os.makedirs(dir)
1073 os.chdir(dir)
1074 system("git init")
1075 gitdir = os.getcwd() + "/.git"
1076 if not P4Sync.run(self, [depotPath]):
1077 return False
1078 if self.branch != "master":
1079 if gitBranchExists("refs/remotes/p4/master"):
1080 system("git branch master refs/remotes/p4/master")
1081 system("git checkout -f")
1082 else:
1083 print "Could not detect main branch. No checkout/master branch created."
1084 return True
1086 class HelpFormatter(optparse.IndentedHelpFormatter):
1087 def __init__(self):
1088 optparse.IndentedHelpFormatter.__init__(self)
1090 def format_description(self, description):
1091 if description:
1092 return description + "\n"
1093 else:
1094 return ""
1096 def printUsage(commands):
1097 print "usage: %s <command> [options]" % sys.argv[0]
1098 print ""
1099 print "valid commands: %s" % ", ".join(commands)
1100 print ""
1101 print "Try %s <command> --help for command specific help." % sys.argv[0]
1102 print ""
1104 commands = {
1105 "debug" : P4Debug(),
1106 "submit" : P4Submit(),
1107 "sync" : P4Sync(),
1108 "rebase" : P4Rebase(),
1109 "clone" : P4Clone()
1112 if len(sys.argv[1:]) == 0:
1113 printUsage(commands.keys())
1114 sys.exit(2)
1116 cmd = ""
1117 cmdName = sys.argv[1]
1118 try:
1119 cmd = commands[cmdName]
1120 except KeyError:
1121 print "unknown command %s" % cmdName
1122 print ""
1123 printUsage(commands.keys())
1124 sys.exit(2)
1126 options = cmd.options
1127 cmd.gitdir = gitdir
1129 args = sys.argv[2:]
1131 if len(options) > 0:
1132 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1134 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1135 options,
1136 description = cmd.description,
1137 formatter = HelpFormatter())
1139 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1141 if cmd.needsGit:
1142 gitdir = cmd.gitdir
1143 if len(gitdir) == 0:
1144 gitdir = ".git"
1145 if not isValidGitDir(gitdir):
1146 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1147 if os.path.exists(gitdir):
1148 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1149 if len(cdup) > 0:
1150 os.chdir(cdup);
1152 if not isValidGitDir(gitdir):
1153 if isValidGitDir(gitdir + "/.git"):
1154 gitdir += "/.git"
1155 else:
1156 die("fatal: cannot locate git repository at %s" % gitdir)
1158 os.environ["GIT_DIR"] = gitdir
1160 if not cmd.run(args):
1161 parser.print_help()