Fix calling git-p4 rebase from within a subdirectory (git rebase wants to be in toplevel)
[fast-export/rorcz.git] / git-p4
blobca6c62380990268a77a54bc7655c055445469b94
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>
11 import optparse, sys, os, marshal, popen2, subprocess, shelve
12 import tempfile, getopt, sha, os.path, time, platform
13 from sets import Set;
15 gitdir = os.environ.get("GIT_DIR", "")
17 def mypopen(command):
18 return os.popen(command, "rb");
20 def p4CmdList(cmd):
21 cmd = "p4 -G %s" % cmd
22 pipe = os.popen(cmd, "rb")
24 result = []
25 try:
26 while True:
27 entry = marshal.load(pipe)
28 result.append(entry)
29 except EOFError:
30 pass
31 pipe.close()
33 return result
35 def p4Cmd(cmd):
36 list = p4CmdList(cmd)
37 result = {}
38 for entry in list:
39 result.update(entry)
40 return result;
42 def p4Where(depotPath):
43 if not depotPath.endswith("/"):
44 depotPath += "/"
45 output = p4Cmd("where %s..." % depotPath)
46 clientPath = ""
47 if "path" in output:
48 clientPath = output.get("path")
49 elif "data" in output:
50 data = output.get("data")
51 lastSpace = data.rfind(" ")
52 clientPath = data[lastSpace + 1:]
54 if clientPath.endswith("..."):
55 clientPath = clientPath[:-3]
56 return clientPath
58 def die(msg):
59 sys.stderr.write(msg + "\n")
60 sys.exit(1)
62 def currentGitBranch():
63 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
65 def isValidGitDir(path):
66 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
67 return True;
68 return False
70 def system(cmd):
71 if os.system(cmd) != 0:
72 die("command failed: %s" % cmd)
74 def extractLogMessageFromGitCommit(commit):
75 logMessage = ""
76 foundTitle = False
77 for log in mypopen("git cat-file commit %s" % commit).readlines():
78 if not foundTitle:
79 if len(log) == 1:
80 foundTitle = True
81 continue
83 logMessage += log
84 return logMessage
86 def extractDepotPathAndChangeFromGitLog(log):
87 values = {}
88 for line in log.split("\n"):
89 line = line.strip()
90 if line.startswith("[git-p4:") and line.endswith("]"):
91 line = line[8:-1].strip()
92 for assignment in line.split(":"):
93 variable = assignment.strip()
94 value = ""
95 equalPos = assignment.find("=")
96 if equalPos != -1:
97 variable = assignment[:equalPos].strip()
98 value = assignment[equalPos + 1:].strip()
99 if value.startswith("\"") and value.endswith("\""):
100 value = value[1:-1]
101 values[variable] = value
103 return values.get("depot-path"), values.get("change")
105 def gitBranchExists(branch):
106 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
107 return proc.wait() == 0;
109 class Command:
110 def __init__(self):
111 self.usage = "usage: %prog [options]"
112 self.needsGit = True
114 class P4Debug(Command):
115 def __init__(self):
116 Command.__init__(self)
117 self.options = [
119 self.description = "A tool to debug the output of p4 -G."
120 self.needsGit = False
122 def run(self, args):
123 for output in p4CmdList(" ".join(args)):
124 print output
125 return True
127 class P4CleanTags(Command):
128 def __init__(self):
129 Command.__init__(self)
130 self.options = [
131 # optparse.make_option("--branch", dest="branch", default="refs/heads/master")
133 self.description = "A tool to remove stale unused tags from incremental perforce imports."
134 def run(self, args):
135 branch = currentGitBranch()
136 print "Cleaning out stale p4 import tags..."
137 sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % branch)
138 output = sout.read()
139 try:
140 tagIdx = output.index(" tags/p4/")
141 except:
142 print "Cannot find any p4/* tag. Nothing to do."
143 sys.exit(0)
145 try:
146 caretIdx = output.index("^")
147 except:
148 caretIdx = len(output) - 1
149 rev = int(output[tagIdx + 9 : caretIdx])
151 allTags = mypopen("git tag -l p4/").readlines()
152 for i in range(len(allTags)):
153 allTags[i] = int(allTags[i][3:-1])
155 allTags.sort()
157 allTags.remove(rev)
159 for rev in allTags:
160 print mypopen("git tag -d p4/%s" % rev).read()
162 print "%s tags removed." % len(allTags)
163 return True
165 class P4Submit(Command):
166 def __init__(self):
167 Command.__init__(self)
168 self.options = [
169 optparse.make_option("--continue", action="store_false", dest="firstTime"),
170 optparse.make_option("--origin", dest="origin"),
171 optparse.make_option("--reset", action="store_true", dest="reset"),
172 optparse.make_option("--log-substitutions", dest="substFile"),
173 optparse.make_option("--noninteractive", action="store_false"),
174 optparse.make_option("--dry-run", action="store_true"),
176 self.description = "Submit changes from git to the perforce depot."
177 self.usage += " [name of git branch to submit into perforce depot]"
178 self.firstTime = True
179 self.reset = False
180 self.interactive = True
181 self.dryRun = False
182 self.substFile = ""
183 self.firstTime = True
184 self.origin = ""
186 self.logSubstitutions = {}
187 self.logSubstitutions["<enter description here>"] = "%log%"
188 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
190 def check(self):
191 if len(p4CmdList("opened ...")) > 0:
192 die("You have files opened with perforce! Close them before starting the sync.")
194 def start(self):
195 if len(self.config) > 0 and not self.reset:
196 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)
198 commits = []
199 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
200 commits.append(line[:-1])
201 commits.reverse()
203 self.config["commits"] = commits
205 def prepareLogMessage(self, template, message):
206 result = ""
208 for line in template.split("\n"):
209 if line.startswith("#"):
210 result += line + "\n"
211 continue
213 substituted = False
214 for key in self.logSubstitutions.keys():
215 if line.find(key) != -1:
216 value = self.logSubstitutions[key]
217 value = value.replace("%log%", message)
218 if value != "@remove@":
219 result += line.replace(key, value) + "\n"
220 substituted = True
221 break
223 if not substituted:
224 result += line + "\n"
226 return result
228 def apply(self, id):
229 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
230 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
231 filesToAdd = set()
232 filesToDelete = set()
233 editedFiles = set()
234 for line in diff:
235 modifier = line[0]
236 path = line[1:].strip()
237 if modifier == "M":
238 system("p4 edit \"%s\"" % path)
239 editedFiles.add(path)
240 elif modifier == "A":
241 filesToAdd.add(path)
242 if path in filesToDelete:
243 filesToDelete.remove(path)
244 elif modifier == "D":
245 filesToDelete.add(path)
246 if path in filesToAdd:
247 filesToAdd.remove(path)
248 else:
249 die("unknown modifier %s for %s" % (modifier, path))
251 diffcmd = "git diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\"" % (id, id)
252 patchcmd = diffcmd + " | patch -p1"
254 if os.system(patchcmd + " --dry-run --silent") != 0:
255 print "Unfortunately applying the change failed!"
256 print "What do you want to do?"
257 response = "x"
258 while response != "s" and response != "a" and response != "w":
259 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) ")
260 if response == "s":
261 print "Skipping! Good luck with the next patches..."
262 return
263 elif response == "a":
264 os.system(patchcmd)
265 if len(filesToAdd) > 0:
266 print "You may also want to call p4 add on the following files:"
267 print " ".join(filesToAdd)
268 if len(filesToDelete):
269 print "The following files should be scheduled for deletion with p4 delete:"
270 print " ".join(filesToDelete)
271 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
272 elif response == "w":
273 system(diffcmd + " > patch.txt")
274 print "Patch saved to patch.txt in %s !" % self.clientPath
275 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
277 system(patchcmd)
279 for f in filesToAdd:
280 system("p4 add %s" % f)
281 for f in filesToDelete:
282 system("p4 revert %s" % f)
283 system("p4 delete %s" % f)
285 logMessage = extractLogMessageFromGitCommit(id)
286 logMessage = logMessage.replace("\n", "\n\t")
287 logMessage = logMessage[:-1]
289 template = mypopen("p4 change -o").read()
291 if self.interactive:
292 submitTemplate = self.prepareLogMessage(template, logMessage)
293 diff = mypopen("p4 diff -du ...").read()
295 for newFile in filesToAdd:
296 diff += "==== new file ====\n"
297 diff += "--- /dev/null\n"
298 diff += "+++ %s\n" % newFile
299 f = open(newFile, "r")
300 for line in f.readlines():
301 diff += "+" + line
302 f.close()
304 separatorLine = "######## everything below this line is just the diff #######"
305 if platform.system() == "Windows":
306 separatorLine += "\r"
307 separatorLine += "\n"
309 response = "e"
310 firstIteration = True
311 while response == "e":
312 if not firstIteration:
313 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
314 firstIteration = False
315 if response == "e":
316 [handle, fileName] = tempfile.mkstemp()
317 tmpFile = os.fdopen(handle, "w+")
318 tmpFile.write(submitTemplate + separatorLine + diff)
319 tmpFile.close()
320 defaultEditor = "vi"
321 if platform.system() == "Windows":
322 defaultEditor = "notepad"
323 editor = os.environ.get("EDITOR", defaultEditor);
324 system(editor + " " + fileName)
325 tmpFile = open(fileName, "rb")
326 message = tmpFile.read()
327 tmpFile.close()
328 os.remove(fileName)
329 submitTemplate = message[:message.index(separatorLine)]
331 if response == "y" or response == "yes":
332 if self.dryRun:
333 print submitTemplate
334 raw_input("Press return to continue...")
335 else:
336 pipe = os.popen("p4 submit -i", "wb")
337 pipe.write(submitTemplate)
338 pipe.close()
339 elif response == "s":
340 for f in editedFiles:
341 system("p4 revert \"%s\"" % f);
342 for f in filesToAdd:
343 system("p4 revert \"%s\"" % f);
344 system("rm %s" %f)
345 for f in filesToDelete:
346 system("p4 delete \"%s\"" % f);
347 return
348 else:
349 print "Not submitting!"
350 self.interactive = False
351 else:
352 fileName = "submit.txt"
353 file = open(fileName, "w+")
354 file.write(self.prepareLogMessage(template, logMessage))
355 file.close()
356 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
358 def run(self, args):
359 global gitdir
360 # make gitdir absolute so we can cd out into the perforce checkout
361 gitdir = os.path.abspath(gitdir)
362 os.environ["GIT_DIR"] = gitdir
364 if len(args) == 0:
365 self.master = currentGitBranch()
366 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
367 die("Detecting current git branch failed!")
368 elif len(args) == 1:
369 self.master = args[0]
370 else:
371 return False
373 depotPath = ""
374 if gitBranchExists("p4"):
375 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
376 if len(depotPath) == 0 and gitBranchExists("origin"):
377 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
379 if len(depotPath) == 0:
380 print "Internal error: cannot locate perforce depot path from existing branches"
381 sys.exit(128)
383 self.clientPath = p4Where(depotPath)
385 if len(self.clientPath) == 0:
386 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
387 sys.exit(128)
389 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
390 oldWorkingDirectory = os.getcwd()
391 os.chdir(self.clientPath)
392 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
393 if response == "y" or response == "yes":
394 system("p4 sync ...")
396 if len(self.origin) == 0:
397 if gitBranchExists("p4"):
398 self.origin = "p4"
399 else:
400 self.origin = "origin"
402 if self.reset:
403 self.firstTime = True
405 if len(self.substFile) > 0:
406 for line in open(self.substFile, "r").readlines():
407 tokens = line[:-1].split("=")
408 self.logSubstitutions[tokens[0]] = tokens[1]
410 self.check()
411 self.configFile = gitdir + "/p4-git-sync.cfg"
412 self.config = shelve.open(self.configFile, writeback=True)
414 if self.firstTime:
415 self.start()
417 commits = self.config.get("commits", [])
419 while len(commits) > 0:
420 self.firstTime = False
421 commit = commits[0]
422 commits = commits[1:]
423 self.config["commits"] = commits
424 self.apply(commit)
425 if not self.interactive:
426 break
428 self.config.close()
430 if len(commits) == 0:
431 if self.firstTime:
432 print "No changes found to apply between %s and current HEAD" % self.origin
433 else:
434 print "All changes applied!"
435 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
436 if response == "y" or response == "yes":
437 os.chdir(oldWorkingDirectory)
438 rebase = P4Rebase()
439 rebase.run([])
440 os.remove(self.configFile)
442 return True
444 class P4Sync(Command):
445 def __init__(self):
446 Command.__init__(self)
447 self.options = [
448 optparse.make_option("--branch", dest="branch"),
449 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
450 optparse.make_option("--changesfile", dest="changesFile"),
451 optparse.make_option("--silent", dest="silent", action="store_true"),
452 optparse.make_option("--known-branches", dest="knownBranches"),
453 optparse.make_option("--data-cache", dest="dataCache", action="store_true"),
454 optparse.make_option("--command-cache", dest="commandCache", action="store_true"),
455 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true")
457 self.description = """Imports from Perforce into a git repository.\n
458 example:
459 //depot/my/project/ -- to import the current head
460 //depot/my/project/@all -- to import everything
461 //depot/my/project/@1,6 -- to import only from revision 1 to 6
463 (a ... is not needed in the path p4 specification, it's added implicitly)"""
465 self.usage += " //depot/path[@revRange]"
467 self.dataCache = False
468 self.commandCache = False
469 self.silent = False
470 self.knownBranches = Set()
471 self.createdBranches = Set()
472 self.committedChanges = Set()
473 self.branch = ""
474 self.detectBranches = False
475 self.detectLabels = False
476 self.changesFile = ""
478 def p4File(self, depotPath):
479 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
481 def extractFilesFromCommit(self, commit):
482 files = []
483 fnum = 0
484 while commit.has_key("depotFile%s" % fnum):
485 path = commit["depotFile%s" % fnum]
486 if not path.startswith(self.depotPath):
487 # if not self.silent:
488 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
489 fnum = fnum + 1
490 continue
492 file = {}
493 file["path"] = path
494 file["rev"] = commit["rev%s" % fnum]
495 file["action"] = commit["action%s" % fnum]
496 file["type"] = commit["type%s" % fnum]
497 files.append(file)
498 fnum = fnum + 1
499 return files
501 def isSubPathOf(self, first, second):
502 if not first.startswith(second):
503 return False
504 if first == second:
505 return True
506 return first[len(second)] == "/"
508 def branchesForCommit(self, files):
509 branches = Set()
511 for file in files:
512 relativePath = file["path"][len(self.depotPath):]
513 # strip off the filename
514 relativePath = relativePath[0:relativePath.rfind("/")]
516 # if len(branches) == 0:
517 # branches.add(relativePath)
518 # knownBranches.add(relativePath)
519 # continue
521 ###### this needs more testing :)
522 knownBranch = False
523 for branch in branches:
524 if relativePath == branch:
525 knownBranch = True
526 break
527 # if relativePath.startswith(branch):
528 if self.isSubPathOf(relativePath, branch):
529 knownBranch = True
530 break
531 # if branch.startswith(relativePath):
532 if self.isSubPathOf(branch, relativePath):
533 branches.remove(branch)
534 break
536 if knownBranch:
537 continue
539 for branch in self.knownBranches:
540 #if relativePath.startswith(branch):
541 if self.isSubPathOf(relativePath, branch):
542 if len(branches) == 0:
543 relativePath = branch
544 else:
545 knownBranch = True
546 break
548 if knownBranch:
549 continue
551 branches.add(relativePath)
552 self.knownBranches.add(relativePath)
554 return branches
556 def findBranchParent(self, branchPrefix, files):
557 for file in files:
558 path = file["path"]
559 if not path.startswith(branchPrefix):
560 continue
561 action = file["action"]
562 if action != "integrate" and action != "branch":
563 continue
564 rev = file["rev"]
565 depotPath = path + "#" + rev
567 log = p4CmdList("filelog \"%s\"" % depotPath)
568 if len(log) != 1:
569 print "eek! I got confused by the filelog of %s" % depotPath
570 sys.exit(1);
572 log = log[0]
573 if log["action0"] != action:
574 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
575 sys.exit(1);
577 branchAction = log["how0,0"]
578 # if branchAction == "branch into" or branchAction == "ignored":
579 # continue # ignore for branching
581 if not branchAction.endswith(" from"):
582 continue # ignore for branching
583 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
584 # sys.exit(1);
586 source = log["file0,0"]
587 if source.startswith(branchPrefix):
588 continue
590 lastSourceRev = log["erev0,0"]
592 sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
593 if len(sourceLog) != 1:
594 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
595 sys.exit(1);
596 sourceLog = sourceLog[0]
598 relPath = source[len(self.depotPath):]
599 # strip off the filename
600 relPath = relPath[0:relPath.rfind("/")]
602 for branch in self.knownBranches:
603 if self.isSubPathOf(relPath, branch):
604 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
605 return branch
606 # else:
607 # print "%s is not a subpath of branch %s" % (relPath, branch)
609 return ""
611 def commit(self, details, files, branch, branchPrefix, parent = "", merged = ""):
612 epoch = details["time"]
613 author = details["user"]
615 self.gitStream.write("commit %s\n" % branch)
616 # gitStream.write("mark :%s\n" % details["change"])
617 self.committedChanges.add(int(details["change"]))
618 committer = ""
619 if author in self.users:
620 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
621 else:
622 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
624 self.gitStream.write("committer %s\n" % committer)
626 self.gitStream.write("data <<EOT\n")
627 self.gitStream.write(details["desc"])
628 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
629 self.gitStream.write("EOT\n\n")
631 if len(parent) > 0:
632 self.gitStream.write("from %s\n" % parent)
634 if len(merged) > 0:
635 self.gitStream.write("merge %s\n" % merged)
637 for file in files:
638 path = file["path"]
639 if not path.startswith(branchPrefix):
640 # if not silent:
641 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
642 continue
643 rev = file["rev"]
644 depotPath = path + "#" + rev
645 relPath = path[len(branchPrefix):]
646 action = file["action"]
648 if file["type"] == "apple":
649 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
650 continue
652 if action == "delete":
653 self.gitStream.write("D %s\n" % relPath)
654 else:
655 mode = 644
656 if file["type"].startswith("x"):
657 mode = 755
659 data = self.p4File(depotPath)
661 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
662 self.gitStream.write("data %s\n" % len(data))
663 self.gitStream.write(data)
664 self.gitStream.write("\n")
666 self.gitStream.write("\n")
668 change = int(details["change"])
670 self.lastChange = change
672 if change in self.labels:
673 label = self.labels[change]
674 labelDetails = label[0]
675 labelRevisions = label[1]
677 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
679 if len(files) == len(labelRevisions):
681 cleanedFiles = {}
682 for info in files:
683 if info["action"] == "delete":
684 continue
685 cleanedFiles[info["depotFile"]] = info["rev"]
687 if cleanedFiles == labelRevisions:
688 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
689 self.gitStream.write("from %s\n" % branch)
691 owner = labelDetails["Owner"]
692 tagger = ""
693 if author in self.users:
694 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
695 else:
696 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
697 self.gitStream.write("tagger %s\n" % tagger)
698 self.gitStream.write("data <<EOT\n")
699 self.gitStream.write(labelDetails["Description"])
700 self.gitStream.write("EOT\n\n")
702 else:
703 if not self.silent:
704 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
706 else:
707 if not self.silent:
708 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
710 def extractFilesInCommitToBranch(self, files, branchPrefix):
711 newFiles = []
713 for file in files:
714 path = file["path"]
715 if path.startswith(branchPrefix):
716 newFiles.append(file)
718 return newFiles
720 def findBranchSourceHeuristic(self, files, branch, branchPrefix):
721 for file in files:
722 action = file["action"]
723 if action != "integrate" and action != "branch":
724 continue
725 path = file["path"]
726 rev = file["rev"]
727 depotPath = path + "#" + rev
729 log = p4CmdList("filelog \"%s\"" % depotPath)
730 if len(log) != 1:
731 print "eek! I got confused by the filelog of %s" % depotPath
732 sys.exit(1);
734 log = log[0]
735 if log["action0"] != action:
736 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
737 sys.exit(1);
739 branchAction = log["how0,0"]
741 if not branchAction.endswith(" from"):
742 continue # ignore for branching
743 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
744 # sys.exit(1);
746 source = log["file0,0"]
747 if source.startswith(branchPrefix):
748 continue
750 lastSourceRev = log["erev0,0"]
752 sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
753 if len(sourceLog) != 1:
754 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
755 sys.exit(1);
756 sourceLog = sourceLog[0]
758 relPath = source[len(self.depotPath):]
759 # strip off the filename
760 relPath = relPath[0:relPath.rfind("/")]
762 for candidate in self.knownBranches:
763 if self.isSubPathOf(relPath, candidate) and candidate != branch:
764 return candidate
766 return ""
768 def changeIsBranchMerge(self, sourceBranch, destinationBranch, change):
769 sourceFiles = {}
770 for file in p4CmdList("files %s...@%s" % (self.depotPath + sourceBranch + "/", change)):
771 if file["action"] == "delete":
772 continue
773 sourceFiles[file["depotFile"]] = file
775 destinationFiles = {}
776 for file in p4CmdList("files %s...@%s" % (self.depotPath + destinationBranch + "/", change)):
777 destinationFiles[file["depotFile"]] = file
779 for fileName in sourceFiles.keys():
780 integrations = []
781 deleted = False
782 integrationCount = 0
783 for integration in p4CmdList("integrated \"%s\"" % fileName):
784 toFile = integration["fromFile"] # yes, it's true, it's fromFile
785 if not toFile in destinationFiles:
786 continue
787 destFile = destinationFiles[toFile]
788 if destFile["action"] == "delete":
789 # print "file %s has been deleted in %s" % (fileName, toFile)
790 deleted = True
791 break
792 integrationCount += 1
793 if integration["how"] == "branch from":
794 continue
796 if int(integration["change"]) == change:
797 integrations.append(integration)
798 continue
799 if int(integration["change"]) > change:
800 continue
802 destRev = int(destFile["rev"])
804 startRev = integration["startFromRev"][1:]
805 if startRev == "none":
806 startRev = 0
807 else:
808 startRev = int(startRev)
810 endRev = integration["endFromRev"][1:]
811 if endRev == "none":
812 endRev = 0
813 else:
814 endRev = int(endRev)
816 initialBranch = (destRev == 1 and integration["how"] != "branch into")
817 inRange = (destRev >= startRev and destRev <= endRev)
818 newer = (destRev > startRev and destRev > endRev)
820 if initialBranch or inRange or newer:
821 integrations.append(integration)
823 if deleted:
824 continue
826 if len(integrations) == 0 and integrationCount > 1:
827 print "file %s was not integrated from %s into %s" % (fileName, sourceBranch, destinationBranch)
828 return False
830 return True
832 def getUserMap(self):
833 self.users = {}
835 for output in p4CmdList("users"):
836 if not output.has_key("User"):
837 continue
838 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
840 def getLabels(self):
841 self.labels = {}
843 l = p4CmdList("labels %s..." % self.depotPath)
844 if len(l) > 0 and not self.silent:
845 print "Finding files belonging to labels in %s" % self.depotPath
847 for output in l:
848 label = output["label"]
849 revisions = {}
850 newestChange = 0
851 for file in p4CmdList("files //...@%s" % label):
852 revisions[file["depotFile"]] = file["rev"]
853 change = int(file["change"])
854 if change > newestChange:
855 newestChange = change
857 self.labels[newestChange] = [output, revisions]
859 def run(self, args):
860 self.depotPath = ""
861 self.changeRange = ""
862 self.initialParent = ""
863 self.previousDepotPath = ""
865 if len(self.branch) == 0:
866 self.branch = "p4"
868 if len(args) == 0:
869 if not gitBranchExists(self.branch) and gitBranchExists("origin"):
870 if not self.silent:
871 print "Creating %s branch in git repository based on origin" % self.branch
872 system("git branch %s origin" % self.branch)
874 [self.previousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self.branch))
875 if len(self.previousDepotPath) > 0 and len(p4Change) > 0:
876 p4Change = int(p4Change) + 1
877 self.depotPath = self.previousDepotPath
878 self.changeRange = "@%s,#head" % p4Change
879 self.initialParent = self.branch
880 if not self.silent:
881 print "Performing incremental import into %s git branch" % self.branch
883 self.branch = "refs/heads/" + self.branch
885 if len(self.depotPath) != 0:
886 self.depotPath = self.depotPath[:-1]
888 if len(args) == 0 and len(self.depotPath) != 0:
889 if not self.silent:
890 print "Depot path: %s" % self.depotPath
891 elif len(args) != 1:
892 return False
893 else:
894 if len(self.depotPath) != 0 and self.depotPath != args[0]:
895 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
896 sys.exit(1)
897 self.depotPath = args[0]
899 self.revision = ""
900 self.users = {}
901 self.lastChange = 0
903 if self.depotPath.find("@") != -1:
904 atIdx = self.depotPath.index("@")
905 self.changeRange = self.depotPath[atIdx:]
906 if self.changeRange == "@all":
907 self.changeRange = ""
908 elif self.changeRange.find(",") == -1:
909 self.revision = self.changeRange
910 self.changeRange = ""
911 self.depotPath = self.depotPath[0:atIdx]
912 elif self.depotPath.find("#") != -1:
913 hashIdx = self.depotPath.index("#")
914 self.revision = self.depotPath[hashIdx:]
915 self.depotPath = self.depotPath[0:hashIdx]
916 elif len(self.previousDepotPath) == 0:
917 self.revision = "#head"
919 if self.depotPath.endswith("..."):
920 self.depotPath = self.depotPath[:-3]
922 if not self.depotPath.endswith("/"):
923 self.depotPath += "/"
925 self.getUserMap()
926 self.labels = {}
927 if self.detectLabels:
928 self.getLabels();
930 if len(self.changeRange) == 0:
931 try:
932 sout, sin, serr = popen2.popen3("git name-rev --tags `git rev-parse %s`" % self.branch)
933 output = sout.read()
934 if output.endswith("\n"):
935 output = output[:-1]
936 tagIdx = output.index(" tags/p4/")
937 caretIdx = output.find("^")
938 endPos = len(output)
939 if caretIdx != -1:
940 endPos = caretIdx
941 self.rev = int(output[tagIdx + 9 : endPos]) + 1
942 self.changeRange = "@%s,#head" % self.rev
943 self.initialParent = mypopen("git rev-parse %s" % self.branch).read()[:-1]
944 except:
945 pass
947 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
949 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
950 self.gitOutput = importProcess.stdout
951 self.gitStream = importProcess.stdin
952 self.gitError = importProcess.stderr
954 if len(self.revision) > 0:
955 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
957 details = { "user" : "git perforce import user", "time" : int(time.time()) }
958 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
959 details["change"] = self.revision
960 newestRevision = 0
962 fileCnt = 0
963 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
964 change = int(info["change"])
965 if change > newestRevision:
966 newestRevision = change
968 if info["action"] == "delete":
969 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
970 #fileCnt = fileCnt + 1
971 continue
973 for prop in [ "depotFile", "rev", "action", "type" ]:
974 details["%s%s" % (prop, fileCnt)] = info[prop]
976 fileCnt = fileCnt + 1
978 details["change"] = newestRevision
980 try:
981 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
982 except IOError:
983 print "IO error with git fast-import. Is your git version recent enough?"
984 print self.gitError.read()
986 else:
987 changes = []
989 if len(self.changesFile) > 0:
990 output = open(self.changesFile).readlines()
991 changeSet = Set()
992 for line in output:
993 changeSet.add(int(line))
995 for change in changeSet:
996 changes.append(change)
998 changes.sort()
999 else:
1000 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
1002 for line in output:
1003 changeNum = line.split(" ")[1]
1004 changes.append(changeNum)
1006 changes.reverse()
1008 if len(changes) == 0:
1009 if not self.silent:
1010 print "no changes to import!"
1011 return True
1013 cnt = 1
1014 for change in changes:
1015 description = p4Cmd("describe %s" % change)
1017 if not self.silent:
1018 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1019 sys.stdout.flush()
1020 cnt = cnt + 1
1022 try:
1023 files = self.extractFilesFromCommit(description)
1024 if self.detectBranches:
1025 for branch in self.branchesForCommit(files):
1026 self.knownBranches.add(branch)
1027 branchPrefix = self.depotPath + branch + "/"
1029 filesForCommit = self.extractFilesInCommitToBranch(files, branchPrefix)
1031 merged = ""
1032 parent = ""
1033 ########### remove cnt!!!
1034 if branch not in self.createdBranches and cnt > 2:
1035 self.createdBranches.add(branch)
1036 parent = self.findBranchParent(branchPrefix, files)
1037 if parent == branch:
1038 parent = ""
1039 # elif len(parent) > 0:
1040 # print "%s branched off of %s" % (branch, parent)
1042 if len(parent) == 0:
1043 merged = self.findBranchSourceHeuristic(filesForCommit, branch, branchPrefix)
1044 if len(merged) > 0:
1045 print "change %s could be a merge from %s into %s" % (description["change"], merged, branch)
1046 if not self.changeIsBranchMerge(merged, branch, int(description["change"])):
1047 merged = ""
1049 branch = "refs/heads/" + branch
1050 if len(parent) > 0:
1051 parent = "refs/heads/" + parent
1052 if len(merged) > 0:
1053 merged = "refs/heads/" + merged
1054 self.commit(description, files, branch, branchPrefix, parent, merged)
1055 else:
1056 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
1057 self.initialParent = ""
1058 except IOError:
1059 print self.gitError.read()
1060 sys.exit(1)
1062 if not self.silent:
1063 print ""
1066 self.gitStream.close()
1067 self.gitOutput.close()
1068 self.gitError.close()
1069 importProcess.wait()
1071 return True
1073 class P4Rebase(Command):
1074 def __init__(self):
1075 Command.__init__(self)
1076 self.options = [ ]
1077 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1079 def run(self, args):
1080 sync = P4Sync()
1081 sync.run([])
1082 print "Rebasing the current branch"
1083 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
1084 system("git rebase p4")
1085 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1086 return True
1088 class P4Clone(P4Sync):
1089 def __init__(self):
1090 P4Sync.__init__(self)
1091 self.description = "Creates a new git repository and imports from Perforce into it"
1092 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1093 self.needsGit = False
1095 def run(self, args):
1096 if len(args) < 1:
1097 return False
1098 depotPath = args[0]
1099 dir = ""
1100 if len(args) == 2:
1101 dir = args[1]
1102 elif len(args) > 2:
1103 return False
1105 if not depotPath.startswith("//"):
1106 return False
1108 if len(dir) == 0:
1109 dir = depotPath
1110 atPos = dir.rfind("@")
1111 if atPos != -1:
1112 dir = dir[0:atPos]
1113 hashPos = dir.rfind("#")
1114 if hashPos != -1:
1115 dir = dir[0:hashPos]
1117 if dir.endswith("..."):
1118 dir = dir[:-3]
1120 if dir.endswith("/"):
1121 dir = dir[:-1]
1123 slashPos = dir.rfind("/")
1124 if slashPos != -1:
1125 dir = dir[slashPos + 1:]
1127 print "Importing from %s into %s" % (depotPath, dir)
1128 os.makedirs(dir)
1129 os.chdir(dir)
1130 system("git init")
1131 if not P4Sync.run(self, [depotPath]):
1132 return False
1133 if self.branch != "master":
1134 system("git branch master p4")
1135 system("git checkout -f")
1136 return True
1138 class HelpFormatter(optparse.IndentedHelpFormatter):
1139 def __init__(self):
1140 optparse.IndentedHelpFormatter.__init__(self)
1142 def format_description(self, description):
1143 if description:
1144 return description + "\n"
1145 else:
1146 return ""
1148 def printUsage(commands):
1149 print "usage: %s <command> [options]" % sys.argv[0]
1150 print ""
1151 print "valid commands: %s" % ", ".join(commands)
1152 print ""
1153 print "Try %s <command> --help for command specific help." % sys.argv[0]
1154 print ""
1156 commands = {
1157 "debug" : P4Debug(),
1158 "clean-tags" : P4CleanTags(),
1159 "submit" : P4Submit(),
1160 "sync" : P4Sync(),
1161 "rebase" : P4Rebase(),
1162 "clone" : P4Clone()
1165 if len(sys.argv[1:]) == 0:
1166 printUsage(commands.keys())
1167 sys.exit(2)
1169 cmd = ""
1170 cmdName = sys.argv[1]
1171 try:
1172 cmd = commands[cmdName]
1173 except KeyError:
1174 print "unknown command %s" % cmdName
1175 print ""
1176 printUsage(commands.keys())
1177 sys.exit(2)
1179 options = cmd.options
1180 cmd.gitdir = gitdir
1182 args = sys.argv[2:]
1184 if len(options) > 0:
1185 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1187 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1188 options,
1189 description = cmd.description,
1190 formatter = HelpFormatter())
1192 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1194 if cmd.needsGit:
1195 gitdir = cmd.gitdir
1196 if len(gitdir) == 0:
1197 gitdir = ".git"
1198 if not isValidGitDir(gitdir):
1199 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1200 if os.path.exists(gitdir):
1201 os.chdir(mypopen("git rev-parse --show-cdup").read()[:-1]);
1203 if not isValidGitDir(gitdir):
1204 if isValidGitDir(gitdir + "/.git"):
1205 gitdir += "/.git"
1206 else:
1207 die("fatal: cannot locate git repository at %s" % gitdir)
1209 os.environ["GIT_DIR"] = gitdir
1211 if not cmd.run(args):
1212 parser.print_help()