Set the default branch in run, not in the constructor
[fast-export.git] / git-p4
blobe6a34f4f478db2451de28687a55c9387d16c7c9d
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, shelve
12 import tempfile, getopt, sha, os.path, time
13 from sets import Set;
15 gitdir = os.environ.get("GIT_DIR", "")
17 def p4CmdList(cmd):
18 cmd = "p4 -G %s" % cmd
19 pipe = os.popen(cmd, "rb")
21 result = []
22 try:
23 while True:
24 entry = marshal.load(pipe)
25 result.append(entry)
26 except EOFError:
27 pass
28 pipe.close()
30 return result
32 def p4Cmd(cmd):
33 list = p4CmdList(cmd)
34 result = {}
35 for entry in list:
36 result.update(entry)
37 return result;
39 def die(msg):
40 sys.stderr.write(msg + "\n")
41 sys.exit(1)
43 def currentGitBranch():
44 return os.popen("git-name-rev HEAD").read().split(" ")[1][:-1]
46 def isValidGitDir(path):
47 if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
48 return True;
49 return False
51 def system(cmd):
52 if os.system(cmd) != 0:
53 die("command failed: %s" % cmd)
55 def extractLogMessageFromGitCommit(commit):
56 logMessage = ""
57 foundTitle = False
58 for log in os.popen("git-cat-file commit %s" % commit).readlines():
59 if not foundTitle:
60 if len(log) == 1:
61 foundTitle = 1
62 continue
64 logMessage += log
65 return logMessage
67 def extractDepotPathAndChangeFromGitLog(log):
68 values = {}
69 for line in log.split("\n"):
70 line = line.strip()
71 if line.startswith("[git-p4:") and line.endswith("]"):
72 line = line[8:-1].strip()
73 for assignment in line.split(":"):
74 variable = assignment.strip()
75 value = ""
76 equalPos = assignment.find("=")
77 if equalPos != -1:
78 variable = assignment[:equalPos].strip()
79 value = assignment[equalPos + 1:].strip()
80 if value.startswith("\"") and value.endswith("\""):
81 value = value[1:-1]
82 values[variable] = value
84 return values.get("depot-path"), values.get("change")
86 def gitBranchExists(branch):
87 return os.system("git-rev-parse %s 2>/dev/null >/dev/null") == 0
89 class Command:
90 def __init__(self):
91 self.usage = "usage: %prog [options]"
93 class P4Debug(Command):
94 def __init__(self):
95 Command.__init__(self)
96 self.options = [
98 self.description = "A tool to debug the output of p4 -G."
100 def run(self, args):
101 for output in p4CmdList(" ".join(args)):
102 print output
103 return True
105 class P4CleanTags(Command):
106 def __init__(self):
107 Command.__init__(self)
108 self.options = [
109 # optparse.make_option("--branch", dest="branch", default="refs/heads/master")
111 self.description = "A tool to remove stale unused tags from incremental perforce imports."
112 def run(self, args):
113 branch = currentGitBranch()
114 print "Cleaning out stale p4 import tags..."
115 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
116 output = sout.read()
117 try:
118 tagIdx = output.index(" tags/p4/")
119 except:
120 print "Cannot find any p4/* tag. Nothing to do."
121 sys.exit(0)
123 try:
124 caretIdx = output.index("^")
125 except:
126 caretIdx = len(output) - 1
127 rev = int(output[tagIdx + 9 : caretIdx])
129 allTags = os.popen("git tag -l p4/").readlines()
130 for i in range(len(allTags)):
131 allTags[i] = int(allTags[i][3:-1])
133 allTags.sort()
135 allTags.remove(rev)
137 for rev in allTags:
138 print os.popen("git tag -d p4/%s" % rev).read()
140 print "%s tags removed." % len(allTags)
141 return True
143 class P4Sync(Command):
144 def __init__(self):
145 Command.__init__(self)
146 self.options = [
147 optparse.make_option("--continue", action="store_false", dest="firstTime"),
148 optparse.make_option("--origin", dest="origin"),
149 optparse.make_option("--reset", action="store_true", dest="reset"),
150 optparse.make_option("--master", dest="master"),
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("--apply-as-patch", action="store_true", dest="applyAsPatch")
156 self.description = "Submit changes from git to the perforce depot."
157 self.firstTime = True
158 self.reset = False
159 self.interactive = True
160 self.dryRun = False
161 self.substFile = ""
162 self.firstTime = True
163 self.origin = "origin"
164 self.master = ""
165 self.applyAsPatch = True
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" % self.configFile)
179 commits = []
180 for line in os.popen("git-rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
181 commits.append(line[:-1])
182 commits.reverse()
184 self.config["commits"] = commits
186 if not self.applyAsPatch:
187 print "Creating temporary p4-sync branch from %s ..." % self.origin
188 system("git checkout -f -b p4-sync %s" % self.origin)
190 def prepareLogMessage(self, template, message):
191 result = ""
193 for line in template.split("\n"):
194 if line.startswith("#"):
195 result += line + "\n"
196 continue
198 substituted = False
199 for key in self.logSubstitutions.keys():
200 if line.find(key) != -1:
201 value = self.logSubstitutions[key]
202 value = value.replace("%log%", message)
203 if value != "@remove@":
204 result += line.replace(key, value) + "\n"
205 substituted = True
206 break
208 if not substituted:
209 result += line + "\n"
211 return result
213 def apply(self, id):
214 print "Applying %s" % (os.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
215 diff = os.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
216 filesToAdd = set()
217 filesToDelete = set()
218 for line in diff:
219 modifier = line[0]
220 path = line[1:].strip()
221 if modifier == "M":
222 system("p4 edit %s" % path)
223 elif modifier == "A":
224 filesToAdd.add(path)
225 if path in filesToDelete:
226 filesToDelete.remove(path)
227 elif modifier == "D":
228 filesToDelete.add(path)
229 if path in filesToAdd:
230 filesToAdd.remove(path)
231 else:
232 die("unknown modifier %s for %s" % (modifier, path))
234 if self.applyAsPatch:
235 system("git-diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\" | patch -p1" % (id, id))
236 else:
237 system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
238 system("git cherry-pick --no-commit \"%s\"" % id)
240 for f in filesToAdd:
241 system("p4 add %s" % f)
242 for f in filesToDelete:
243 system("p4 revert %s" % f)
244 system("p4 delete %s" % f)
246 logMessage = extractLogMessageFromGitCommit(id)
247 logMessage = logMessage.replace("\n", "\n\t")
248 logMessage = logMessage[:-1]
250 template = os.popen("p4 change -o").read()
252 if self.interactive:
253 submitTemplate = self.prepareLogMessage(template, logMessage)
254 diff = os.popen("p4 diff -du ...").read()
256 for newFile in filesToAdd:
257 diff += "==== new file ====\n"
258 diff += "--- /dev/null\n"
259 diff += "+++ %s\n" % newFile
260 f = open(newFile, "r")
261 for line in f.readlines():
262 diff += "+" + line
263 f.close()
265 separatorLine = "######## everything below this line is just the diff #######\n"
267 response = "e"
268 firstIteration = True
269 while response == "e":
270 if not firstIteration:
271 response = raw_input("Do you want to submit this change (y/e/n)? ")
272 firstIteration = False
273 if response == "e":
274 [handle, fileName] = tempfile.mkstemp()
275 tmpFile = os.fdopen(handle, "w+")
276 tmpFile.write(submitTemplate + separatorLine + diff)
277 tmpFile.close()
278 editor = os.environ.get("EDITOR", "vi")
279 system(editor + " " + fileName)
280 tmpFile = open(fileName, "r")
281 message = tmpFile.read()
282 tmpFile.close()
283 os.remove(fileName)
284 submitTemplate = message[:message.index(separatorLine)]
286 if response == "y" or response == "yes":
287 if self.dryRun:
288 print submitTemplate
289 raw_input("Press return to continue...")
290 else:
291 pipe = os.popen("p4 submit -i", "w")
292 pipe.write(submitTemplate)
293 pipe.close()
294 else:
295 print "Not submitting!"
296 self.interactive = False
297 else:
298 fileName = "submit.txt"
299 file = open(fileName, "w+")
300 file.write(self.prepareLogMessage(template, logMessage))
301 file.close()
302 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
304 def run(self, args):
305 if self.reset:
306 self.firstTime = True
308 if len(self.substFile) > 0:
309 for line in open(self.substFile, "r").readlines():
310 tokens = line[:-1].split("=")
311 self.logSubstitutions[tokens[0]] = tokens[1]
313 if len(self.master) == 0:
314 self.master = currentGitBranch()
315 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
316 die("Detecting current git branch failed!")
318 self.check()
319 self.configFile = gitdir + "/p4-git-sync.cfg"
320 self.config = shelve.open(self.configFile, writeback=True)
322 if self.firstTime:
323 self.start()
325 commits = self.config.get("commits", [])
327 while len(commits) > 0:
328 self.firstTime = False
329 commit = commits[0]
330 commits = commits[1:]
331 self.config["commits"] = commits
332 self.apply(commit)
333 if not self.interactive:
334 break
336 self.config.close()
338 if len(commits) == 0:
339 if self.firstTime:
340 print "No changes found to apply between %s and current HEAD" % self.origin
341 else:
342 print "All changes applied!"
343 if not self.applyAsPatch:
344 print "Deleting temporary p4-sync branch and going back to %s" % self.master
345 system("git checkout %s" % self.master)
346 system("git branch -D p4-sync")
347 print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
348 system("p4 edit ... >/dev/null")
349 system("p4 revert ... >/dev/null")
350 os.remove(self.configFile)
352 return True
354 class GitSync(Command):
355 def __init__(self):
356 Command.__init__(self)
357 self.options = [
358 optparse.make_option("--branch", dest="branch"),
359 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
360 optparse.make_option("--changesfile", dest="changesFile"),
361 optparse.make_option("--silent", dest="silent", action="store_true"),
362 optparse.make_option("--known-branches", dest="knownBranches"),
363 optparse.make_option("--cache", dest="doCache", action="store_true"),
364 optparse.make_option("--command-cache", dest="commandCache", action="store_true")
366 self.description = """Imports from Perforce into a git repository.\n
367 example:
368 //depot/my/project/ -- to import the current head
369 //depot/my/project/@all -- to import everything
370 //depot/my/project/@1,6 -- to import only from revision 1 to 6
372 (a ... is not needed in the path p4 specification, it's added implicitly)"""
374 self.usage += " //depot/path[@revRange]"
376 self.dataCache = False
377 self.commandCache = False
378 self.silent = False
379 self.knownBranches = Set()
380 self.createdBranches = Set()
381 self.committedChanges = Set()
382 self.branch = ""
383 self.detectBranches = False
384 self.changesFile = ""
386 def p4File(self, depotPath):
387 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
389 def extractFilesFromCommit(self, commit):
390 files = []
391 fnum = 0
392 while commit.has_key("depotFile%s" % fnum):
393 path = commit["depotFile%s" % fnum]
394 if not path.startswith(self.globalPrefix):
395 # if not self.silent:
396 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
397 fnum = fnum + 1
398 continue
400 file = {}
401 file["path"] = path
402 file["rev"] = commit["rev%s" % fnum]
403 file["action"] = commit["action%s" % fnum]
404 file["type"] = commit["type%s" % fnum]
405 files.append(file)
406 fnum = fnum + 1
407 return files
409 def isSubPathOf(self, first, second):
410 if not first.startswith(second):
411 return False
412 if first == second:
413 return True
414 return first[len(second)] == "/"
416 def branchesForCommit(self, files):
417 branches = Set()
419 for file in files:
420 relativePath = file["path"][len(self.globalPrefix):]
421 # strip off the filename
422 relativePath = relativePath[0:relativePath.rfind("/")]
424 # if len(branches) == 0:
425 # branches.add(relativePath)
426 # knownBranches.add(relativePath)
427 # continue
429 ###### this needs more testing :)
430 knownBranch = False
431 for branch in branches:
432 if relativePath == branch:
433 knownBranch = True
434 break
435 # if relativePath.startswith(branch):
436 if self.isSubPathOf(relativePath, branch):
437 knownBranch = True
438 break
439 # if branch.startswith(relativePath):
440 if self.isSubPathOf(branch, relativePath):
441 branches.remove(branch)
442 break
444 if knownBranch:
445 continue
447 for branch in knownBranches:
448 #if relativePath.startswith(branch):
449 if self.isSubPathOf(relativePath, branch):
450 if len(branches) == 0:
451 relativePath = branch
452 else:
453 knownBranch = True
454 break
456 if knownBranch:
457 continue
459 branches.add(relativePath)
460 self.knownBranches.add(relativePath)
462 return branches
464 def findBranchParent(self, branchPrefix, files):
465 for file in files:
466 path = file["path"]
467 if not path.startswith(branchPrefix):
468 continue
469 action = file["action"]
470 if action != "integrate" and action != "branch":
471 continue
472 rev = file["rev"]
473 depotPath = path + "#" + rev
475 log = p4CmdList("filelog \"%s\"" % depotPath)
476 if len(log) != 1:
477 print "eek! I got confused by the filelog of %s" % depotPath
478 sys.exit(1);
480 log = log[0]
481 if log["action0"] != action:
482 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
483 sys.exit(1);
485 branchAction = log["how0,0"]
486 # if branchAction == "branch into" or branchAction == "ignored":
487 # continue # ignore for branching
489 if not branchAction.endswith(" from"):
490 continue # ignore for branching
491 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
492 # sys.exit(1);
494 source = log["file0,0"]
495 if source.startswith(branchPrefix):
496 continue
498 lastSourceRev = log["erev0,0"]
500 sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
501 if len(sourceLog) != 1:
502 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
503 sys.exit(1);
504 sourceLog = sourceLog[0]
506 relPath = source[len(self.globalPrefix):]
507 # strip off the filename
508 relPath = relPath[0:relPath.rfind("/")]
510 for branch in self.knownBranches:
511 if self.isSubPathOf(relPath, branch):
512 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
513 return branch
514 # else:
515 # print "%s is not a subpath of branch %s" % (relPath, branch)
517 return ""
519 def commit(self, details, files, branch, branchPrefix, parent = "", merged = ""):
520 epoch = details["time"]
521 author = details["user"]
523 self.gitStream.write("commit %s\n" % branch)
524 # gitStream.write("mark :%s\n" % details["change"])
525 self.committedChanges.add(int(details["change"]))
526 committer = ""
527 if author in self.users:
528 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
529 else:
530 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
532 self.gitStream.write("committer %s\n" % committer)
534 self.gitStream.write("data <<EOT\n")
535 self.gitStream.write(details["desc"])
536 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
537 self.gitStream.write("EOT\n\n")
539 if len(parent) > 0:
540 self.gitStream.write("from %s\n" % parent)
542 if len(merged) > 0:
543 self.gitStream.write("merge %s\n" % merged)
545 for file in files:
546 path = file["path"]
547 if not path.startswith(branchPrefix):
548 # if not silent:
549 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
550 continue
551 rev = file["rev"]
552 depotPath = path + "#" + rev
553 relPath = path[len(branchPrefix):]
554 action = file["action"]
556 if file["type"] == "apple":
557 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
558 continue
560 if action == "delete":
561 self.gitStream.write("D %s\n" % relPath)
562 else:
563 mode = 644
564 if file["type"].startswith("x"):
565 mode = 755
567 data = self.p4File(depotPath)
569 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
570 self.gitStream.write("data %s\n" % len(data))
571 self.gitStream.write(data)
572 self.gitStream.write("\n")
574 self.gitStream.write("\n")
576 self.lastChange = int(details["change"])
578 def extractFilesInCommitToBranch(self, files, branchPrefix):
579 newFiles = []
581 for file in files:
582 path = file["path"]
583 if path.startswith(branchPrefix):
584 newFiles.append(file)
586 return newFiles
588 def findBranchSourceHeuristic(self, files, branch, branchPrefix):
589 for file in files:
590 action = file["action"]
591 if action != "integrate" and action != "branch":
592 continue
593 path = file["path"]
594 rev = file["rev"]
595 depotPath = path + "#" + rev
597 log = p4CmdList("filelog \"%s\"" % depotPath)
598 if len(log) != 1:
599 print "eek! I got confused by the filelog of %s" % depotPath
600 sys.exit(1);
602 log = log[0]
603 if log["action0"] != action:
604 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
605 sys.exit(1);
607 branchAction = log["how0,0"]
609 if not branchAction.endswith(" from"):
610 continue # ignore for branching
611 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
612 # sys.exit(1);
614 source = log["file0,0"]
615 if source.startswith(branchPrefix):
616 continue
618 lastSourceRev = log["erev0,0"]
620 sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
621 if len(sourceLog) != 1:
622 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
623 sys.exit(1);
624 sourceLog = sourceLog[0]
626 relPath = source[len(self.globalPrefix):]
627 # strip off the filename
628 relPath = relPath[0:relPath.rfind("/")]
630 for candidate in self.knownBranches:
631 if self.isSubPathOf(relPath, candidate) and candidate != branch:
632 return candidate
634 return ""
636 def changeIsBranchMerge(self, sourceBranch, destinationBranch, change):
637 sourceFiles = {}
638 for file in p4CmdList("files %s...@%s" % (self.globalPrefix + sourceBranch + "/", change)):
639 if file["action"] == "delete":
640 continue
641 sourceFiles[file["depotFile"]] = file
643 destinationFiles = {}
644 for file in p4CmdList("files %s...@%s" % (self.globalPrefix + destinationBranch + "/", change)):
645 destinationFiles[file["depotFile"]] = file
647 for fileName in sourceFiles.keys():
648 integrations = []
649 deleted = False
650 integrationCount = 0
651 for integration in p4CmdList("integrated \"%s\"" % fileName):
652 toFile = integration["fromFile"] # yes, it's true, it's fromFile
653 if not toFile in destinationFiles:
654 continue
655 destFile = destinationFiles[toFile]
656 if destFile["action"] == "delete":
657 # print "file %s has been deleted in %s" % (fileName, toFile)
658 deleted = True
659 break
660 integrationCount += 1
661 if integration["how"] == "branch from":
662 continue
664 if int(integration["change"]) == change:
665 integrations.append(integration)
666 continue
667 if int(integration["change"]) > change:
668 continue
670 destRev = int(destFile["rev"])
672 startRev = integration["startFromRev"][1:]
673 if startRev == "none":
674 startRev = 0
675 else:
676 startRev = int(startRev)
678 endRev = integration["endFromRev"][1:]
679 if endRev == "none":
680 endRev = 0
681 else:
682 endRev = int(endRev)
684 initialBranch = (destRev == 1 and integration["how"] != "branch into")
685 inRange = (destRev >= startRev and destRev <= endRev)
686 newer = (destRev > startRev and destRev > endRev)
688 if initialBranch or inRange or newer:
689 integrations.append(integration)
691 if deleted:
692 continue
694 if len(integrations) == 0 and integrationCount > 1:
695 print "file %s was not integrated from %s into %s" % (fileName, sourceBranch, destinationBranch)
696 return False
698 return True
700 def getUserMap(self):
701 self.users = {}
703 for output in p4CmdList("users"):
704 if not output.has_key("User"):
705 continue
706 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
708 def run(self, args):
709 if len(self.branch) == 0:
710 self.branch = "p4"
712 self.branch = "refs/heads/" + self.branch
713 self.globalPrefix = self.previousDepotPath = os.popen("git-repo-config --get p4.depotpath").read()
714 if len(self.globalPrefix) != 0:
715 self.globalPrefix = self.globalPrefix[:-1]
717 if len(args) == 0 and len(self.globalPrefix) != 0:
718 if not self.silent:
719 print "[using previously specified depot path %s]" % self.globalPrefix
720 elif len(args) != 1:
721 return False
722 else:
723 if len(self.globalPrefix) != 0 and self.globalPrefix != args[0]:
724 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.globalPrefix, args[0])
725 sys.exit(1)
726 self.globalPrefix = args[0]
728 self.changeRange = ""
729 self.revision = ""
730 self.users = {}
731 self.initialParent = ""
732 self.lastChange = 0
733 self.initialTag = ""
735 if self.globalPrefix.find("@") != -1:
736 atIdx = self.globalPrefix.index("@")
737 self.changeRange = self.globalPrefix[atIdx:]
738 if self.changeRange == "@all":
739 self.changeRange = ""
740 elif self.changeRange.find(",") == -1:
741 self.revision = self.changeRange
742 self.changeRange = ""
743 self.globalPrefix = self.globalPrefix[0:atIdx]
744 elif self.globalPrefix.find("#") != -1:
745 hashIdx = self.globalPrefix.index("#")
746 self.revision = self.globalPrefix[hashIdx:]
747 self.globalPrefix = self.globalPrefix[0:hashIdx]
748 elif len(self.previousDepotPath) == 0:
749 self.revision = "#head"
751 if self.globalPrefix.endswith("..."):
752 self.globalPrefix = self.globalPrefix[:-3]
754 if not self.globalPrefix.endswith("/"):
755 self.globalPrefix += "/"
757 self.getUserMap()
759 if len(self.changeRange) == 0:
760 try:
761 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % self.branch)
762 output = sout.read()
763 if output.endswith("\n"):
764 output = output[:-1]
765 tagIdx = output.index(" tags/p4/")
766 caretIdx = output.find("^")
767 endPos = len(output)
768 if caretIdx != -1:
769 endPos = caretIdx
770 self.rev = int(output[tagIdx + 9 : endPos]) + 1
771 self.changeRange = "@%s,#head" % self.rev
772 self.initialParent = os.popen("git-rev-parse %s" % self.branch).read()[:-1]
773 self.initialTag = "p4/%s" % (int(self.rev) - 1)
774 except:
775 pass
777 self.tz = - time.timezone / 36
778 tzsign = ("%s" % self.tz)[0]
779 if tzsign != '+' and tzsign != '-':
780 self.tz = "+" + ("%s" % self.tz)
782 self.gitOutput, self.gitStream, self.gitError = popen2.popen3("git-fast-import")
784 if len(self.revision) > 0:
785 print "Doing initial import of %s from revision %s" % (self.globalPrefix, self.revision)
787 details = { "user" : "git perforce import user", "time" : int(time.time()) }
788 details["desc"] = "Initial import of %s from the state at revision %s" % (self.globalPrefix, self.revision)
789 details["change"] = self.revision
790 newestRevision = 0
792 fileCnt = 0
793 for info in p4CmdList("files %s...%s" % (self.globalPrefix, self.revision)):
794 change = int(info["change"])
795 if change > newestRevision:
796 newestRevision = change
798 if info["action"] == "delete":
799 fileCnt = fileCnt + 1
800 continue
802 for prop in [ "depotFile", "rev", "action", "type" ]:
803 details["%s%s" % (prop, fileCnt)] = info[prop]
805 fileCnt = fileCnt + 1
807 details["change"] = newestRevision
809 try:
810 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.globalPrefix)
811 except IOError:
812 print self.gitError.read()
814 else:
815 changes = []
817 if len(self.changesFile) > 0:
818 output = open(self.changesFile).readlines()
819 changeSet = Set()
820 for line in output:
821 changeSet.add(int(line))
823 for change in changeSet:
824 changes.append(change)
826 changes.sort()
827 else:
828 output = os.popen("p4 changes %s...%s" % (self.globalPrefix, self.changeRange)).readlines()
830 for line in output:
831 changeNum = line.split(" ")[1]
832 changes.append(changeNum)
834 changes.reverse()
836 if len(changes) == 0:
837 if not self.silent:
838 print "no changes to import!"
839 sys.exit(1)
841 cnt = 1
842 for change in changes:
843 description = p4Cmd("describe %s" % change)
845 if not self.silent:
846 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
847 sys.stdout.flush()
848 cnt = cnt + 1
850 try:
851 files = self.extractFilesFromCommit(description)
852 if self.detectBranches:
853 for branch in self.branchesForCommit(files):
854 self.knownBranches.add(branch)
855 branchPrefix = self.globalPrefix + branch + "/"
857 filesForCommit = self.extractFilesInCommitToBranch(files, branchPrefix)
859 merged = ""
860 parent = ""
861 ########### remove cnt!!!
862 if branch not in self.createdBranches and cnt > 2:
863 self.createdBranches.add(branch)
864 parent = self.findBranchParent(branchPrefix, files)
865 if parent == branch:
866 parent = ""
867 # elif len(parent) > 0:
868 # print "%s branched off of %s" % (branch, parent)
870 if len(parent) == 0:
871 merged = self.findBranchSourceHeuristic(filesForCommit, branch, branchPrefix)
872 if len(merged) > 0:
873 print "change %s could be a merge from %s into %s" % (description["change"], merged, branch)
874 if not self.changeIsBranchMerge(merged, branch, int(description["change"])):
875 merged = ""
877 branch = "refs/heads/" + branch
878 if len(parent) > 0:
879 parent = "refs/heads/" + parent
880 if len(merged) > 0:
881 merged = "refs/heads/" + merged
882 self.commit(description, files, branch, branchPrefix, parent, merged)
883 else:
884 self.commit(description, files, self.branch, self.globalPrefix, self.initialParent)
885 self.initialParent = ""
886 except IOError:
887 print self.gitError.read()
888 sys.exit(1)
890 if not self.silent:
891 print ""
893 self.gitStream.write("reset refs/tags/p4/%s\n" % self.lastChange)
894 self.gitStream.write("from %s\n\n" % self.branch);
897 self.gitStream.close()
898 self.gitOutput.close()
899 self.gitError.close()
901 os.popen("git-repo-config p4.depotpath %s" % self.globalPrefix).read()
902 if len(self.initialTag) > 0:
903 os.popen("git tag -d %s" % self.initialTag).read()
905 return True
907 class HelpFormatter(optparse.IndentedHelpFormatter):
908 def __init__(self):
909 optparse.IndentedHelpFormatter.__init__(self)
911 def format_description(self, description):
912 if description:
913 return description + "\n"
914 else:
915 return ""
917 def printUsage(commands):
918 print "usage: %s <command> [options]" % sys.argv[0]
919 print ""
920 print "valid commands: %s" % ", ".join(commands)
921 print ""
922 print "Try %s <command> --help for command specific help." % sys.argv[0]
923 print ""
925 commands = {
926 "debug" : P4Debug(),
927 "clean-tags" : P4CleanTags(),
928 "submit" : P4Sync(),
929 "sync" : GitSync()
932 if len(sys.argv[1:]) == 0:
933 printUsage(commands.keys())
934 sys.exit(2)
936 cmd = ""
937 cmdName = sys.argv[1]
938 try:
939 cmd = commands[cmdName]
940 except KeyError:
941 print "unknown command %s" % cmdName
942 print ""
943 printUsage(commands.keys())
944 sys.exit(2)
946 options = cmd.options
947 cmd.gitdir = gitdir
948 options.append(optparse.make_option("--git-dir", dest="gitdir"))
950 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
951 options,
952 description = cmd.description,
953 formatter = HelpFormatter())
955 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
957 gitdir = cmd.gitdir
958 if len(gitdir) == 0:
959 gitdir = ".git"
960 if not isValidGitDir(gitdir):
961 cdup = os.popen("git-rev-parse --show-cdup").read()[:-1]
962 if isValidGitDir(cdup + "/" + gitdir):
963 os.chdir(cdup)
965 if not isValidGitDir(gitdir):
966 if isValidGitDir(gitdir + "/.git"):
967 gitdir += "/.git"
968 else:
969 die("fatal: cannot locate git repository at %s" % gitdir)
971 os.environ["GIT_DIR"] = gitdir
973 if not cmd.run(args):
974 parser.print_help()