Added some helper function(s) to parse the depot path and change number from the...
[fast-export.git] / contrib / fast-import / git-p4
blob6ead1c41732743cabdd3741bf5da66c1a44b134e
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 class Command:
87 def __init__(self):
88 self.usage = "usage: %prog [options]"
90 class P4Debug(Command):
91 def __init__(self):
92 Command.__init__(self)
93 self.options = [
95 self.description = "A tool to debug the output of p4 -G."
97 def run(self, args):
98 for output in p4CmdList(" ".join(args)):
99 print output
100 return True
102 class P4CleanTags(Command):
103 def __init__(self):
104 Command.__init__(self)
105 self.options = [
106 # optparse.make_option("--branch", dest="branch", default="refs/heads/master")
108 self.description = "A tool to remove stale unused tags from incremental perforce imports."
109 def run(self, args):
110 branch = currentGitBranch()
111 print "Cleaning out stale p4 import tags..."
112 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % branch)
113 output = sout.read()
114 try:
115 tagIdx = output.index(" tags/p4/")
116 except:
117 print "Cannot find any p4/* tag. Nothing to do."
118 sys.exit(0)
120 try:
121 caretIdx = output.index("^")
122 except:
123 caretIdx = len(output) - 1
124 rev = int(output[tagIdx + 9 : caretIdx])
126 allTags = os.popen("git tag -l p4/").readlines()
127 for i in range(len(allTags)):
128 allTags[i] = int(allTags[i][3:-1])
130 allTags.sort()
132 allTags.remove(rev)
134 for rev in allTags:
135 print os.popen("git tag -d p4/%s" % rev).read()
137 print "%s tags removed." % len(allTags)
138 return True
140 class P4Sync(Command):
141 def __init__(self):
142 Command.__init__(self)
143 self.options = [
144 optparse.make_option("--continue", action="store_false", dest="firstTime"),
145 optparse.make_option("--origin", dest="origin"),
146 optparse.make_option("--reset", action="store_true", dest="reset"),
147 optparse.make_option("--master", dest="master"),
148 optparse.make_option("--log-substitutions", dest="substFile"),
149 optparse.make_option("--noninteractive", action="store_false"),
150 optparse.make_option("--dry-run", action="store_true"),
151 optparse.make_option("--apply-as-patch", action="store_true", dest="applyAsPatch")
153 self.description = "Submit changes from git to the perforce depot."
154 self.firstTime = True
155 self.reset = False
156 self.interactive = True
157 self.dryRun = False
158 self.substFile = ""
159 self.firstTime = True
160 self.origin = "origin"
161 self.master = ""
162 self.applyAsPatch = True
164 self.logSubstitutions = {}
165 self.logSubstitutions["<enter description here>"] = "%log%"
166 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
168 def check(self):
169 if len(p4CmdList("opened ...")) > 0:
170 die("You have files opened with perforce! Close them before starting the sync.")
172 def start(self):
173 if len(self.config) > 0 and not self.reset:
174 die("Cannot start sync. Previous sync config found at %s" % self.configFile)
176 commits = []
177 for line in os.popen("git-rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
178 commits.append(line[:-1])
179 commits.reverse()
181 self.config["commits"] = commits
183 if not self.applyAsPatch:
184 print "Creating temporary p4-sync branch from %s ..." % self.origin
185 system("git checkout -f -b p4-sync %s" % self.origin)
187 def prepareLogMessage(self, template, message):
188 result = ""
190 for line in template.split("\n"):
191 if line.startswith("#"):
192 result += line + "\n"
193 continue
195 substituted = False
196 for key in self.logSubstitutions.keys():
197 if line.find(key) != -1:
198 value = self.logSubstitutions[key]
199 value = value.replace("%log%", message)
200 if value != "@remove@":
201 result += line.replace(key, value) + "\n"
202 substituted = True
203 break
205 if not substituted:
206 result += line + "\n"
208 return result
210 def apply(self, id):
211 print "Applying %s" % (os.popen("git-log --max-count=1 --pretty=oneline %s" % id).read())
212 diff = os.popen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
213 filesToAdd = set()
214 filesToDelete = set()
215 for line in diff:
216 modifier = line[0]
217 path = line[1:].strip()
218 if modifier == "M":
219 system("p4 edit %s" % path)
220 elif modifier == "A":
221 filesToAdd.add(path)
222 if path in filesToDelete:
223 filesToDelete.remove(path)
224 elif modifier == "D":
225 filesToDelete.add(path)
226 if path in filesToAdd:
227 filesToAdd.remove(path)
228 else:
229 die("unknown modifier %s for %s" % (modifier, path))
231 if self.applyAsPatch:
232 system("git-diff-tree -p --diff-filter=ACMRTUXB \"%s^\" \"%s\" | patch -p1" % (id, id))
233 else:
234 system("git-diff-files --name-only -z | git-update-index --remove -z --stdin")
235 system("git cherry-pick --no-commit \"%s\"" % id)
237 for f in filesToAdd:
238 system("p4 add %s" % f)
239 for f in filesToDelete:
240 system("p4 revert %s" % f)
241 system("p4 delete %s" % f)
243 logMessage = extractLogMessageFromGitCommit(id)
244 logMessage = logMessage.replace("\n", "\n\t")
245 logMessage = logMessage[:-1]
247 template = os.popen("p4 change -o").read()
249 if self.interactive:
250 submitTemplate = self.prepareLogMessage(template, logMessage)
251 diff = os.popen("p4 diff -du ...").read()
253 for newFile in filesToAdd:
254 diff += "==== new file ====\n"
255 diff += "--- /dev/null\n"
256 diff += "+++ %s\n" % newFile
257 f = open(newFile, "r")
258 for line in f.readlines():
259 diff += "+" + line
260 f.close()
262 separatorLine = "######## everything below this line is just the diff #######\n"
264 response = "e"
265 firstIteration = True
266 while response == "e":
267 if not firstIteration:
268 response = raw_input("Do you want to submit this change (y/e/n)? ")
269 firstIteration = False
270 if response == "e":
271 [handle, fileName] = tempfile.mkstemp()
272 tmpFile = os.fdopen(handle, "w+")
273 tmpFile.write(submitTemplate + separatorLine + diff)
274 tmpFile.close()
275 editor = os.environ.get("EDITOR", "vi")
276 system(editor + " " + fileName)
277 tmpFile = open(fileName, "r")
278 message = tmpFile.read()
279 tmpFile.close()
280 os.remove(fileName)
281 submitTemplate = message[:message.index(separatorLine)]
283 if response == "y" or response == "yes":
284 if self.dryRun:
285 print submitTemplate
286 raw_input("Press return to continue...")
287 else:
288 pipe = os.popen("p4 submit -i", "w")
289 pipe.write(submitTemplate)
290 pipe.close()
291 else:
292 print "Not submitting!"
293 self.interactive = False
294 else:
295 fileName = "submit.txt"
296 file = open(fileName, "w+")
297 file.write(self.prepareLogMessage(template, logMessage))
298 file.close()
299 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
301 def run(self, args):
302 if self.reset:
303 self.firstTime = True
305 if len(self.substFile) > 0:
306 for line in open(self.substFile, "r").readlines():
307 tokens = line[:-1].split("=")
308 self.logSubstitutions[tokens[0]] = tokens[1]
310 if len(self.master) == 0:
311 self.master = currentGitBranch()
312 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
313 die("Detecting current git branch failed!")
315 self.check()
316 self.configFile = gitdir + "/p4-git-sync.cfg"
317 self.config = shelve.open(self.configFile, writeback=True)
319 if self.firstTime:
320 self.start()
322 commits = self.config.get("commits", [])
324 while len(commits) > 0:
325 self.firstTime = False
326 commit = commits[0]
327 commits = commits[1:]
328 self.config["commits"] = commits
329 self.apply(commit)
330 if not self.interactive:
331 break
333 self.config.close()
335 if len(commits) == 0:
336 if self.firstTime:
337 print "No changes found to apply between %s and current HEAD" % self.origin
338 else:
339 print "All changes applied!"
340 if not self.applyAsPatch:
341 print "Deleting temporary p4-sync branch and going back to %s" % self.master
342 system("git checkout %s" % self.master)
343 system("git branch -D p4-sync")
344 print "Cleaning out your perforce checkout by doing p4 edit ... ; p4 revert ..."
345 system("p4 edit ... >/dev/null")
346 system("p4 revert ... >/dev/null")
347 os.remove(self.configFile)
349 return True
351 class GitSync(Command):
352 def __init__(self):
353 Command.__init__(self)
354 self.options = [
355 optparse.make_option("--branch", dest="branch"),
356 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
357 optparse.make_option("--changesfile", dest="changesFile"),
358 optparse.make_option("--silent", dest="silent", action="store_true"),
359 optparse.make_option("--known-branches", dest="knownBranches"),
360 optparse.make_option("--cache", dest="doCache", action="store_true"),
361 optparse.make_option("--command-cache", dest="commandCache", action="store_true")
363 self.description = """Imports from Perforce into a git repository.\n
364 example:
365 //depot/my/project/ -- to import the current head
366 //depot/my/project/@all -- to import everything
367 //depot/my/project/@1,6 -- to import only from revision 1 to 6
369 (a ... is not needed in the path p4 specification, it's added implicitly)"""
371 self.usage += " //depot/path[@revRange]"
373 self.dataCache = False
374 self.commandCache = False
375 self.silent = False
376 self.knownBranches = Set()
377 self.createdBranches = Set()
378 self.committedChanges = Set()
379 self.branch = "p4"
380 self.detectBranches = False
381 self.changesFile = ""
383 def p4File(self, depotPath):
384 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
386 def extractFilesFromCommit(self, commit):
387 files = []
388 fnum = 0
389 while commit.has_key("depotFile%s" % fnum):
390 path = commit["depotFile%s" % fnum]
391 if not path.startswith(self.globalPrefix):
392 # if not self.silent:
393 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.globalPrefix, change)
394 fnum = fnum + 1
395 continue
397 file = {}
398 file["path"] = path
399 file["rev"] = commit["rev%s" % fnum]
400 file["action"] = commit["action%s" % fnum]
401 file["type"] = commit["type%s" % fnum]
402 files.append(file)
403 fnum = fnum + 1
404 return files
406 def isSubPathOf(self, first, second):
407 if not first.startswith(second):
408 return False
409 if first == second:
410 return True
411 return first[len(second)] == "/"
413 def branchesForCommit(self, files):
414 branches = Set()
416 for file in files:
417 relativePath = file["path"][len(self.globalPrefix):]
418 # strip off the filename
419 relativePath = relativePath[0:relativePath.rfind("/")]
421 # if len(branches) == 0:
422 # branches.add(relativePath)
423 # knownBranches.add(relativePath)
424 # continue
426 ###### this needs more testing :)
427 knownBranch = False
428 for branch in branches:
429 if relativePath == branch:
430 knownBranch = True
431 break
432 # if relativePath.startswith(branch):
433 if self.isSubPathOf(relativePath, branch):
434 knownBranch = True
435 break
436 # if branch.startswith(relativePath):
437 if self.isSubPathOf(branch, relativePath):
438 branches.remove(branch)
439 break
441 if knownBranch:
442 continue
444 for branch in knownBranches:
445 #if relativePath.startswith(branch):
446 if self.isSubPathOf(relativePath, branch):
447 if len(branches) == 0:
448 relativePath = branch
449 else:
450 knownBranch = True
451 break
453 if knownBranch:
454 continue
456 branches.add(relativePath)
457 self.knownBranches.add(relativePath)
459 return branches
461 def findBranchParent(self, branchPrefix, files):
462 for file in files:
463 path = file["path"]
464 if not path.startswith(branchPrefix):
465 continue
466 action = file["action"]
467 if action != "integrate" and action != "branch":
468 continue
469 rev = file["rev"]
470 depotPath = path + "#" + rev
472 log = p4CmdList("filelog \"%s\"" % depotPath)
473 if len(log) != 1:
474 print "eek! I got confused by the filelog of %s" % depotPath
475 sys.exit(1);
477 log = log[0]
478 if log["action0"] != action:
479 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
480 sys.exit(1);
482 branchAction = log["how0,0"]
483 # if branchAction == "branch into" or branchAction == "ignored":
484 # continue # ignore for branching
486 if not branchAction.endswith(" from"):
487 continue # ignore for branching
488 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
489 # sys.exit(1);
491 source = log["file0,0"]
492 if source.startswith(branchPrefix):
493 continue
495 lastSourceRev = log["erev0,0"]
497 sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
498 if len(sourceLog) != 1:
499 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
500 sys.exit(1);
501 sourceLog = sourceLog[0]
503 relPath = source[len(self.globalPrefix):]
504 # strip off the filename
505 relPath = relPath[0:relPath.rfind("/")]
507 for branch in self.knownBranches:
508 if self.isSubPathOf(relPath, branch):
509 # print "determined parent branch branch %s due to change in file %s" % (branch, source)
510 return branch
511 # else:
512 # print "%s is not a subpath of branch %s" % (relPath, branch)
514 return ""
516 def commit(self, details, files, branch, branchPrefix, parent = "", merged = ""):
517 epoch = details["time"]
518 author = details["user"]
520 self.gitStream.write("commit %s\n" % branch)
521 # gitStream.write("mark :%s\n" % details["change"])
522 self.committedChanges.add(int(details["change"]))
523 committer = ""
524 if author in self.users:
525 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
526 else:
527 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
529 self.gitStream.write("committer %s\n" % committer)
531 self.gitStream.write("data <<EOT\n")
532 self.gitStream.write(details["desc"])
533 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
534 self.gitStream.write("EOT\n\n")
536 if len(parent) > 0:
537 self.gitStream.write("from %s\n" % parent)
539 if len(merged) > 0:
540 self.gitStream.write("merge %s\n" % merged)
542 for file in files:
543 path = file["path"]
544 if not path.startswith(branchPrefix):
545 # if not silent:
546 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
547 continue
548 rev = file["rev"]
549 depotPath = path + "#" + rev
550 relPath = path[len(branchPrefix):]
551 action = file["action"]
553 if file["type"] == "apple":
554 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
555 continue
557 if action == "delete":
558 self.gitStream.write("D %s\n" % relPath)
559 else:
560 mode = 644
561 if file["type"].startswith("x"):
562 mode = 755
564 data = self.p4File(depotPath)
566 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
567 self.gitStream.write("data %s\n" % len(data))
568 self.gitStream.write(data)
569 self.gitStream.write("\n")
571 self.gitStream.write("\n")
573 self.lastChange = int(details["change"])
575 def extractFilesInCommitToBranch(self, files, branchPrefix):
576 newFiles = []
578 for file in files:
579 path = file["path"]
580 if path.startswith(branchPrefix):
581 newFiles.append(file)
583 return newFiles
585 def findBranchSourceHeuristic(self, files, branch, branchPrefix):
586 for file in files:
587 action = file["action"]
588 if action != "integrate" and action != "branch":
589 continue
590 path = file["path"]
591 rev = file["rev"]
592 depotPath = path + "#" + rev
594 log = p4CmdList("filelog \"%s\"" % depotPath)
595 if len(log) != 1:
596 print "eek! I got confused by the filelog of %s" % depotPath
597 sys.exit(1);
599 log = log[0]
600 if log["action0"] != action:
601 print "eek! wrong action in filelog for %s : found %s, expected %s" % (depotPath, log["action0"], action)
602 sys.exit(1);
604 branchAction = log["how0,0"]
606 if not branchAction.endswith(" from"):
607 continue # ignore for branching
608 # print "eek! file %s was not branched from but instead: %s" % (depotPath, branchAction)
609 # sys.exit(1);
611 source = log["file0,0"]
612 if source.startswith(branchPrefix):
613 continue
615 lastSourceRev = log["erev0,0"]
617 sourceLog = p4CmdList("filelog -m 1 \"%s%s\"" % (source, lastSourceRev))
618 if len(sourceLog) != 1:
619 print "eek! I got confused by the source filelog of %s%s" % (source, lastSourceRev)
620 sys.exit(1);
621 sourceLog = sourceLog[0]
623 relPath = source[len(self.globalPrefix):]
624 # strip off the filename
625 relPath = relPath[0:relPath.rfind("/")]
627 for candidate in self.knownBranches:
628 if self.isSubPathOf(relPath, candidate) and candidate != branch:
629 return candidate
631 return ""
633 def changeIsBranchMerge(self, sourceBranch, destinationBranch, change):
634 sourceFiles = {}
635 for file in p4CmdList("files %s...@%s" % (self.globalPrefix + sourceBranch + "/", change)):
636 if file["action"] == "delete":
637 continue
638 sourceFiles[file["depotFile"]] = file
640 destinationFiles = {}
641 for file in p4CmdList("files %s...@%s" % (self.globalPrefix + destinationBranch + "/", change)):
642 destinationFiles[file["depotFile"]] = file
644 for fileName in sourceFiles.keys():
645 integrations = []
646 deleted = False
647 integrationCount = 0
648 for integration in p4CmdList("integrated \"%s\"" % fileName):
649 toFile = integration["fromFile"] # yes, it's true, it's fromFile
650 if not toFile in destinationFiles:
651 continue
652 destFile = destinationFiles[toFile]
653 if destFile["action"] == "delete":
654 # print "file %s has been deleted in %s" % (fileName, toFile)
655 deleted = True
656 break
657 integrationCount += 1
658 if integration["how"] == "branch from":
659 continue
661 if int(integration["change"]) == change:
662 integrations.append(integration)
663 continue
664 if int(integration["change"]) > change:
665 continue
667 destRev = int(destFile["rev"])
669 startRev = integration["startFromRev"][1:]
670 if startRev == "none":
671 startRev = 0
672 else:
673 startRev = int(startRev)
675 endRev = integration["endFromRev"][1:]
676 if endRev == "none":
677 endRev = 0
678 else:
679 endRev = int(endRev)
681 initialBranch = (destRev == 1 and integration["how"] != "branch into")
682 inRange = (destRev >= startRev and destRev <= endRev)
683 newer = (destRev > startRev and destRev > endRev)
685 if initialBranch or inRange or newer:
686 integrations.append(integration)
688 if deleted:
689 continue
691 if len(integrations) == 0 and integrationCount > 1:
692 print "file %s was not integrated from %s into %s" % (fileName, sourceBranch, destinationBranch)
693 return False
695 return True
697 def getUserMap(self):
698 self.users = {}
700 for output in p4CmdList("users"):
701 if not output.has_key("User"):
702 continue
703 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
705 def run(self, args):
706 self.branch = "refs/heads/" + self.branch
707 self.globalPrefix = self.previousDepotPath = os.popen("git-repo-config --get p4.depotpath").read()
708 if len(self.globalPrefix) != 0:
709 self.globalPrefix = self.globalPrefix[:-1]
711 if len(args) == 0 and len(self.globalPrefix) != 0:
712 if not self.silent:
713 print "[using previously specified depot path %s]" % self.globalPrefix
714 elif len(args) != 1:
715 return False
716 else:
717 if len(self.globalPrefix) != 0 and self.globalPrefix != args[0]:
718 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.globalPrefix, args[0])
719 sys.exit(1)
720 self.globalPrefix = args[0]
722 self.changeRange = ""
723 self.revision = ""
724 self.users = {}
725 self.initialParent = ""
726 self.lastChange = 0
727 self.initialTag = ""
729 if self.globalPrefix.find("@") != -1:
730 atIdx = self.globalPrefix.index("@")
731 self.changeRange = self.globalPrefix[atIdx:]
732 if self.changeRange == "@all":
733 self.changeRange = ""
734 elif self.changeRange.find(",") == -1:
735 self.revision = self.changeRange
736 self.changeRange = ""
737 self.globalPrefix = self.globalPrefix[0:atIdx]
738 elif self.globalPrefix.find("#") != -1:
739 hashIdx = self.globalPrefix.index("#")
740 self.revision = self.globalPrefix[hashIdx:]
741 self.globalPrefix = self.globalPrefix[0:hashIdx]
742 elif len(self.previousDepotPath) == 0:
743 self.revision = "#head"
745 if self.globalPrefix.endswith("..."):
746 self.globalPrefix = self.globalPrefix[:-3]
748 if not self.globalPrefix.endswith("/"):
749 self.globalPrefix += "/"
751 self.getUserMap()
753 if len(self.changeRange) == 0:
754 try:
755 sout, sin, serr = popen2.popen3("git-name-rev --tags `git-rev-parse %s`" % self.branch)
756 output = sout.read()
757 if output.endswith("\n"):
758 output = output[:-1]
759 tagIdx = output.index(" tags/p4/")
760 caretIdx = output.find("^")
761 endPos = len(output)
762 if caretIdx != -1:
763 endPos = caretIdx
764 self.rev = int(output[tagIdx + 9 : endPos]) + 1
765 self.changeRange = "@%s,#head" % self.rev
766 self.initialParent = os.popen("git-rev-parse %s" % self.branch).read()[:-1]
767 self.initialTag = "p4/%s" % (int(self.rev) - 1)
768 except:
769 pass
771 self.tz = - time.timezone / 36
772 tzsign = ("%s" % self.tz)[0]
773 if tzsign != '+' and tzsign != '-':
774 self.tz = "+" + ("%s" % self.tz)
776 self.gitOutput, self.gitStream, self.gitError = popen2.popen3("git-fast-import")
778 if len(self.revision) > 0:
779 print "Doing initial import of %s from revision %s" % (self.globalPrefix, self.revision)
781 details = { "user" : "git perforce import user", "time" : int(time.time()) }
782 details["desc"] = "Initial import of %s from the state at revision %s" % (self.globalPrefix, self.revision)
783 details["change"] = self.revision
784 newestRevision = 0
786 fileCnt = 0
787 for info in p4CmdList("files %s...%s" % (self.globalPrefix, self.revision)):
788 change = int(info["change"])
789 if change > newestRevision:
790 newestRevision = change
792 if info["action"] == "delete":
793 fileCnt = fileCnt + 1
794 continue
796 for prop in [ "depotFile", "rev", "action", "type" ]:
797 details["%s%s" % (prop, fileCnt)] = info[prop]
799 fileCnt = fileCnt + 1
801 details["change"] = newestRevision
803 try:
804 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.globalPrefix)
805 except IOError:
806 print self.gitError.read()
808 else:
809 changes = []
811 if len(self.changesFile) > 0:
812 output = open(self.changesFile).readlines()
813 changeSet = Set()
814 for line in output:
815 changeSet.add(int(line))
817 for change in changeSet:
818 changes.append(change)
820 changes.sort()
821 else:
822 output = os.popen("p4 changes %s...%s" % (self.globalPrefix, self.changeRange)).readlines()
824 for line in output:
825 changeNum = line.split(" ")[1]
826 changes.append(changeNum)
828 changes.reverse()
830 if len(changes) == 0:
831 if not self.silent:
832 print "no changes to import!"
833 sys.exit(1)
835 cnt = 1
836 for change in changes:
837 description = p4Cmd("describe %s" % change)
839 if not self.silent:
840 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
841 sys.stdout.flush()
842 cnt = cnt + 1
844 try:
845 files = self.extractFilesFromCommit(description)
846 if self.detectBranches:
847 for branch in self.branchesForCommit(files):
848 self.knownBranches.add(branch)
849 branchPrefix = self.globalPrefix + branch + "/"
851 filesForCommit = self.extractFilesInCommitToBranch(files, branchPrefix)
853 merged = ""
854 parent = ""
855 ########### remove cnt!!!
856 if branch not in self.createdBranches and cnt > 2:
857 self.createdBranches.add(branch)
858 parent = self.findBranchParent(branchPrefix, files)
859 if parent == branch:
860 parent = ""
861 # elif len(parent) > 0:
862 # print "%s branched off of %s" % (branch, parent)
864 if len(parent) == 0:
865 merged = self.findBranchSourceHeuristic(filesForCommit, branch, branchPrefix)
866 if len(merged) > 0:
867 print "change %s could be a merge from %s into %s" % (description["change"], merged, branch)
868 if not self.changeIsBranchMerge(merged, branch, int(description["change"])):
869 merged = ""
871 branch = "refs/heads/" + branch
872 if len(parent) > 0:
873 parent = "refs/heads/" + parent
874 if len(merged) > 0:
875 merged = "refs/heads/" + merged
876 self.commit(description, files, branch, branchPrefix, parent, merged)
877 else:
878 self.commit(description, files, self.branch, self.globalPrefix, self.initialParent)
879 self.initialParent = ""
880 except IOError:
881 print self.gitError.read()
882 sys.exit(1)
884 if not self.silent:
885 print ""
887 self.gitStream.write("reset refs/tags/p4/%s\n" % self.lastChange)
888 self.gitStream.write("from %s\n\n" % self.branch);
891 self.gitStream.close()
892 self.gitOutput.close()
893 self.gitError.close()
895 os.popen("git-repo-config p4.depotpath %s" % self.globalPrefix).read()
896 if len(self.initialTag) > 0:
897 os.popen("git tag -d %s" % self.initialTag).read()
899 return True
901 class HelpFormatter(optparse.IndentedHelpFormatter):
902 def __init__(self):
903 optparse.IndentedHelpFormatter.__init__(self)
905 def format_description(self, description):
906 if description:
907 return description + "\n"
908 else:
909 return ""
911 def printUsage(commands):
912 print "usage: %s <command> [options]" % sys.argv[0]
913 print ""
914 print "valid commands: %s" % ", ".join(commands)
915 print ""
916 print "Try %s <command> --help for command specific help." % sys.argv[0]
917 print ""
919 commands = {
920 "debug" : P4Debug(),
921 "clean-tags" : P4CleanTags(),
922 "submit" : P4Sync(),
923 "sync" : GitSync()
926 if len(sys.argv[1:]) == 0:
927 printUsage(commands.keys())
928 sys.exit(2)
930 cmd = ""
931 cmdName = sys.argv[1]
932 try:
933 cmd = commands[cmdName]
934 except KeyError:
935 print "unknown command %s" % cmdName
936 print ""
937 printUsage(commands.keys())
938 sys.exit(2)
940 options = cmd.options
941 cmd.gitdir = gitdir
942 options.append(optparse.make_option("--git-dir", dest="gitdir"))
944 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
945 options,
946 description = cmd.description,
947 formatter = HelpFormatter())
949 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
951 gitdir = cmd.gitdir
952 if len(gitdir) == 0:
953 gitdir = ".git"
954 if not isValidGitDir(gitdir):
955 cdup = os.popen("git-rev-parse --show-cdup").read()[:-1]
956 if isValidGitDir(cdup + "/" + gitdir):
957 os.chdir(cdup)
959 if not isValidGitDir(gitdir):
960 if isValidGitDir(gitdir + "/.git"):
961 gitdir += "/.git"
962 else:
963 die("fatal: cannot locate git repository at %s" % gitdir)
965 os.environ["GIT_DIR"] = gitdir
967 if not cmd.run(args):
968 parser.print_help()