Added support for git-p4 submit --direct (experimental)
[fast-export.git] / git-p4
blobbcea4cf3deac1c5eeb21c5468b574a043611cb27
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 parseRevision(ref):
71 return mypopen("git rev-parse %s" % ref).read()[:-1]
73 def system(cmd):
74 if os.system(cmd) != 0:
75 die("command failed: %s" % cmd)
77 def extractLogMessageFromGitCommit(commit):
78 logMessage = ""
79 foundTitle = False
80 for log in mypopen("git cat-file commit %s" % commit).readlines():
81 if not foundTitle:
82 if len(log) == 1:
83 foundTitle = True
84 continue
86 logMessage += log
87 return logMessage
89 def extractDepotPathAndChangeFromGitLog(log):
90 values = {}
91 for line in log.split("\n"):
92 line = line.strip()
93 if line.startswith("[git-p4:") and line.endswith("]"):
94 line = line[8:-1].strip()
95 for assignment in line.split(":"):
96 variable = assignment.strip()
97 value = ""
98 equalPos = assignment.find("=")
99 if equalPos != -1:
100 variable = assignment[:equalPos].strip()
101 value = assignment[equalPos + 1:].strip()
102 if value.startswith("\"") and value.endswith("\""):
103 value = value[1:-1]
104 values[variable] = value
106 return values.get("depot-path"), values.get("change")
108 def gitBranchExists(branch):
109 proc = subprocess.Popen(["git", "rev-parse", branch], stderr=subprocess.PIPE, stdout=subprocess.PIPE);
110 return proc.wait() == 0;
112 class Command:
113 def __init__(self):
114 self.usage = "usage: %prog [options]"
115 self.needsGit = True
117 class P4Debug(Command):
118 def __init__(self):
119 Command.__init__(self)
120 self.options = [
122 self.description = "A tool to debug the output of p4 -G."
123 self.needsGit = False
125 def run(self, args):
126 for output in p4CmdList(" ".join(args)):
127 print output
128 return True
130 class P4Submit(Command):
131 def __init__(self):
132 Command.__init__(self)
133 self.options = [
134 optparse.make_option("--continue", action="store_false", dest="firstTime"),
135 optparse.make_option("--origin", dest="origin"),
136 optparse.make_option("--reset", action="store_true", dest="reset"),
137 optparse.make_option("--log-substitutions", dest="substFile"),
138 optparse.make_option("--noninteractive", action="store_false"),
139 optparse.make_option("--dry-run", action="store_true"),
140 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
142 self.description = "Submit changes from git to the perforce depot."
143 self.usage += " [name of git branch to submit into perforce depot]"
144 self.firstTime = True
145 self.reset = False
146 self.interactive = True
147 self.dryRun = False
148 self.substFile = ""
149 self.firstTime = True
150 self.origin = ""
151 self.directSubmit = False
153 self.logSubstitutions = {}
154 self.logSubstitutions["<enter description here>"] = "%log%"
155 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
157 def check(self):
158 if len(p4CmdList("opened ...")) > 0:
159 die("You have files opened with perforce! Close them before starting the sync.")
161 def start(self):
162 if len(self.config) > 0 and not self.reset:
163 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)
165 commits = []
166 if self.directSubmit:
167 commits.append("0")
168 else:
169 for line in mypopen("git rev-list --no-merges %s..%s" % (self.origin, self.master)).readlines():
170 commits.append(line[:-1])
171 commits.reverse()
173 self.config["commits"] = commits
175 def prepareLogMessage(self, template, message):
176 result = ""
178 for line in template.split("\n"):
179 if line.startswith("#"):
180 result += line + "\n"
181 continue
183 substituted = False
184 for key in self.logSubstitutions.keys():
185 if line.find(key) != -1:
186 value = self.logSubstitutions[key]
187 value = value.replace("%log%", message)
188 if value != "@remove@":
189 result += line.replace(key, value) + "\n"
190 substituted = True
191 break
193 if not substituted:
194 result += line + "\n"
196 return result
198 def apply(self, id):
199 if self.directSubmit:
200 print "Applying local change in working directory/index"
201 diff = self.diffStatus
202 else:
203 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
204 diff = mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
205 filesToAdd = set()
206 filesToDelete = set()
207 editedFiles = set()
208 for line in diff:
209 modifier = line[0]
210 path = line[1:].strip()
211 if modifier == "M":
212 system("p4 edit \"%s\"" % path)
213 editedFiles.add(path)
214 elif modifier == "A":
215 filesToAdd.add(path)
216 if path in filesToDelete:
217 filesToDelete.remove(path)
218 elif modifier == "D":
219 filesToDelete.add(path)
220 if path in filesToAdd:
221 filesToAdd.remove(path)
222 else:
223 die("unknown modifier %s for %s" % (modifier, path))
225 if self.directSubmit:
226 diffcmd = "cat \"%s\"" % self.diffFile
227 else:
228 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
229 patchcmd = diffcmd + " | git apply "
230 tryPatchCmd = patchcmd + "--check -"
231 applyPatchCmd = patchcmd + "--check --apply -"
233 if os.system(tryPatchCmd) != 0:
234 print "Unfortunately applying the change failed!"
235 print "What do you want to do?"
236 response = "x"
237 while response != "s" and response != "a" and response != "w":
238 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) ")
239 if response == "s":
240 print "Skipping! Good luck with the next patches..."
241 return
242 elif response == "a":
243 os.system(applyPatchCmd)
244 if len(filesToAdd) > 0:
245 print "You may also want to call p4 add on the following files:"
246 print " ".join(filesToAdd)
247 if len(filesToDelete):
248 print "The following files should be scheduled for deletion with p4 delete:"
249 print " ".join(filesToDelete)
250 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
251 elif response == "w":
252 system(diffcmd + " > patch.txt")
253 print "Patch saved to patch.txt in %s !" % self.clientPath
254 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
256 system(applyPatchCmd)
258 for f in filesToAdd:
259 system("p4 add %s" % f)
260 for f in filesToDelete:
261 system("p4 revert %s" % f)
262 system("p4 delete %s" % f)
264 logMessage = ""
265 if not self.directSubmit:
266 logMessage = extractLogMessageFromGitCommit(id)
267 logMessage = logMessage.replace("\n", "\n\t")
268 logMessage = logMessage[:-1]
270 template = mypopen("p4 change -o").read()
272 if self.interactive:
273 submitTemplate = self.prepareLogMessage(template, logMessage)
274 diff = mypopen("p4 diff -du ...").read()
276 for newFile in filesToAdd:
277 diff += "==== new file ====\n"
278 diff += "--- /dev/null\n"
279 diff += "+++ %s\n" % newFile
280 f = open(newFile, "r")
281 for line in f.readlines():
282 diff += "+" + line
283 f.close()
285 separatorLine = "######## everything below this line is just the diff #######"
286 if platform.system() == "Windows":
287 separatorLine += "\r"
288 separatorLine += "\n"
290 response = "e"
291 firstIteration = True
292 while response == "e":
293 if not firstIteration:
294 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
295 firstIteration = False
296 if response == "e":
297 [handle, fileName] = tempfile.mkstemp()
298 tmpFile = os.fdopen(handle, "w+")
299 tmpFile.write(submitTemplate + separatorLine + diff)
300 tmpFile.close()
301 defaultEditor = "vi"
302 if platform.system() == "Windows":
303 defaultEditor = "notepad"
304 editor = os.environ.get("EDITOR", defaultEditor);
305 system(editor + " " + fileName)
306 tmpFile = open(fileName, "rb")
307 message = tmpFile.read()
308 tmpFile.close()
309 os.remove(fileName)
310 submitTemplate = message[:message.index(separatorLine)]
312 if response == "y" or response == "yes":
313 if self.dryRun:
314 print submitTemplate
315 raw_input("Press return to continue...")
316 else:
317 pipe = os.popen("p4 submit -i", "wb")
318 pipe.write(submitTemplate)
319 pipe.close()
320 elif response == "s":
321 for f in editedFiles:
322 system("p4 revert \"%s\"" % f);
323 for f in filesToAdd:
324 system("p4 revert \"%s\"" % f);
325 system("rm %s" %f)
326 for f in filesToDelete:
327 system("p4 delete \"%s\"" % f);
328 return
329 else:
330 print "Not submitting!"
331 self.interactive = False
332 else:
333 fileName = "submit.txt"
334 file = open(fileName, "w+")
335 file.write(self.prepareLogMessage(template, logMessage))
336 file.close()
337 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName, fileName)
339 def run(self, args):
340 global gitdir
341 # make gitdir absolute so we can cd out into the perforce checkout
342 gitdir = os.path.abspath(gitdir)
343 os.environ["GIT_DIR"] = gitdir
345 if len(args) == 0:
346 self.master = currentGitBranch()
347 if len(self.master) == 0 or not os.path.exists("%s/refs/heads/%s" % (gitdir, self.master)):
348 die("Detecting current git branch failed!")
349 elif len(args) == 1:
350 self.master = args[0]
351 else:
352 return False
354 depotPath = ""
355 if gitBranchExists("p4"):
356 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
357 if len(depotPath) == 0 and gitBranchExists("origin"):
358 [depotPath, dummy] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
360 if len(depotPath) == 0:
361 print "Internal error: cannot locate perforce depot path from existing branches"
362 sys.exit(128)
364 self.clientPath = p4Where(depotPath)
366 if len(self.clientPath) == 0:
367 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
368 sys.exit(128)
370 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
371 oldWorkingDirectory = os.getcwd()
373 if self.directSubmit:
374 self.diffStatus = mypopen("git diff -r --name-status HEAD").readlines()
375 patch = mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
376 self.diffFile = gitdir + "/p4-git-diff"
377 f = open(self.diffFile, "wb")
378 f.write(patch)
379 f.close();
381 os.chdir(self.clientPath)
382 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
383 if response == "y" or response == "yes":
384 system("p4 sync ...")
386 if len(self.origin) == 0:
387 if gitBranchExists("p4"):
388 self.origin = "p4"
389 else:
390 self.origin = "origin"
392 if self.reset:
393 self.firstTime = True
395 if len(self.substFile) > 0:
396 for line in open(self.substFile, "r").readlines():
397 tokens = line[:-1].split("=")
398 self.logSubstitutions[tokens[0]] = tokens[1]
400 self.check()
401 self.configFile = gitdir + "/p4-git-sync.cfg"
402 self.config = shelve.open(self.configFile, writeback=True)
404 if self.firstTime:
405 self.start()
407 commits = self.config.get("commits", [])
409 while len(commits) > 0:
410 self.firstTime = False
411 commit = commits[0]
412 commits = commits[1:]
413 self.config["commits"] = commits
414 self.apply(commit)
415 if not self.interactive:
416 break
418 self.config.close()
420 if self.directSubmit:
421 os.remove(self.diffFile)
423 if len(commits) == 0:
424 if self.firstTime:
425 print "No changes found to apply between %s and current HEAD" % self.origin
426 else:
427 print "All changes applied!"
428 response = ""
429 os.chdir(oldWorkingDirectory)
431 if self.directSubmit:
432 response = raw_input("Do you want to DISCARD your git WORKING DIRECTORY CHANGES and sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
433 if response == "y" or response == "yes":
434 system("git reset --hard")
436 if len(response) == 0:
437 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
438 if response == "y" or response == "yes":
439 rebase = P4Rebase()
440 rebase.run([])
441 os.remove(self.configFile)
443 return True
445 class P4Sync(Command):
446 def __init__(self):
447 Command.__init__(self)
448 self.options = [
449 optparse.make_option("--branch", dest="branch"),
450 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
451 optparse.make_option("--changesfile", dest="changesFile"),
452 optparse.make_option("--silent", dest="silent", action="store_true"),
453 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
454 optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true"),
455 optparse.make_option("--verbose", dest="verbose", 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.silent = False
468 self.createdBranches = Set()
469 self.committedChanges = Set()
470 self.branch = ""
471 self.detectBranches = False
472 self.detectLabels = False
473 self.changesFile = ""
474 self.syncWithOrigin = False
475 self.verbose = False
477 def p4File(self, depotPath):
478 return os.popen("p4 print -q \"%s\"" % depotPath, "rb").read()
480 def extractFilesFromCommit(self, commit):
481 files = []
482 fnum = 0
483 while commit.has_key("depotFile%s" % fnum):
484 path = commit["depotFile%s" % fnum]
485 if not path.startswith(self.depotPath):
486 # if not self.silent:
487 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
488 fnum = fnum + 1
489 continue
491 file = {}
492 file["path"] = path
493 file["rev"] = commit["rev%s" % fnum]
494 file["action"] = commit["action%s" % fnum]
495 file["type"] = commit["type%s" % fnum]
496 files.append(file)
497 fnum = fnum + 1
498 return files
500 def splitFilesIntoBranches(self, commit):
501 branches = {}
503 fnum = 0
504 while commit.has_key("depotFile%s" % fnum):
505 path = commit["depotFile%s" % fnum]
506 if not path.startswith(self.depotPath):
507 # if not self.silent:
508 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
509 fnum = fnum + 1
510 continue
512 file = {}
513 file["path"] = path
514 file["rev"] = commit["rev%s" % fnum]
515 file["action"] = commit["action%s" % fnum]
516 file["type"] = commit["type%s" % fnum]
517 fnum = fnum + 1
519 relPath = path[len(self.depotPath):]
521 for branch in self.knownBranches.keys():
522 if relPath.startswith(branch):
523 if branch not in branches:
524 branches[branch] = []
525 branches[branch].append(file)
527 return branches
529 def commit(self, details, files, branch, branchPrefix, parent = ""):
530 epoch = details["time"]
531 author = details["user"]
533 if self.verbose:
534 print "commit into %s" % branch
536 self.gitStream.write("commit %s\n" % branch)
537 # gitStream.write("mark :%s\n" % details["change"])
538 self.committedChanges.add(int(details["change"]))
539 committer = ""
540 if author not in self.users:
541 self.getUserMapFromPerforceServer()
542 if author in self.users:
543 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
544 else:
545 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
547 self.gitStream.write("committer %s\n" % committer)
549 self.gitStream.write("data <<EOT\n")
550 self.gitStream.write(details["desc"])
551 self.gitStream.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix, details["change"]))
552 self.gitStream.write("EOT\n\n")
554 if len(parent) > 0:
555 if self.verbose:
556 print "parent %s" % parent
557 self.gitStream.write("from %s\n" % parent)
559 for file in files:
560 path = file["path"]
561 if not path.startswith(branchPrefix):
562 # if not silent:
563 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
564 continue
565 rev = file["rev"]
566 depotPath = path + "#" + rev
567 relPath = path[len(branchPrefix):]
568 action = file["action"]
570 if file["type"] == "apple":
571 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
572 continue
574 if action == "delete":
575 self.gitStream.write("D %s\n" % relPath)
576 else:
577 mode = 644
578 if file["type"].startswith("x"):
579 mode = 755
581 data = self.p4File(depotPath)
583 self.gitStream.write("M %s inline %s\n" % (mode, relPath))
584 self.gitStream.write("data %s\n" % len(data))
585 self.gitStream.write(data)
586 self.gitStream.write("\n")
588 self.gitStream.write("\n")
590 change = int(details["change"])
592 if self.labels.has_key(change):
593 label = self.labels[change]
594 labelDetails = label[0]
595 labelRevisions = label[1]
596 if self.verbose:
597 print "Change %s is labelled %s" % (change, labelDetails)
599 files = p4CmdList("files %s...@%s" % (branchPrefix, change))
601 if len(files) == len(labelRevisions):
603 cleanedFiles = {}
604 for info in files:
605 if info["action"] == "delete":
606 continue
607 cleanedFiles[info["depotFile"]] = info["rev"]
609 if cleanedFiles == labelRevisions:
610 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
611 self.gitStream.write("from %s\n" % branch)
613 owner = labelDetails["Owner"]
614 tagger = ""
615 if author in self.users:
616 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
617 else:
618 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
619 self.gitStream.write("tagger %s\n" % tagger)
620 self.gitStream.write("data <<EOT\n")
621 self.gitStream.write(labelDetails["Description"])
622 self.gitStream.write("EOT\n\n")
624 else:
625 if not self.silent:
626 print "Tag %s does not match with change %s: files do not match." % (labelDetails["label"], change)
628 else:
629 if not self.silent:
630 print "Tag %s does not match with change %s: file count is different." % (labelDetails["label"], change)
632 def getUserMapFromPerforceServer(self):
633 self.users = {}
635 for output in p4CmdList("users"):
636 if not output.has_key("User"):
637 continue
638 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
640 cache = open(gitdir + "/p4-usercache.txt", "wb")
641 for user in self.users.keys():
642 cache.write("%s\t%s\n" % (user, self.users[user]))
643 cache.close();
645 def loadUserMapFromCache(self):
646 self.users = {}
647 try:
648 cache = open(gitdir + "/p4-usercache.txt", "rb")
649 lines = cache.readlines()
650 cache.close()
651 for line in lines:
652 entry = line[:-1].split("\t")
653 self.users[entry[0]] = entry[1]
654 except IOError:
655 self.getUserMapFromPerforceServer()
657 def getLabels(self):
658 self.labels = {}
660 l = p4CmdList("labels %s..." % self.depotPath)
661 if len(l) > 0 and not self.silent:
662 print "Finding files belonging to labels in %s" % self.depotPath
664 for output in l:
665 label = output["label"]
666 revisions = {}
667 newestChange = 0
668 if self.verbose:
669 print "Querying files for label %s" % label
670 for file in p4CmdList("files %s...@%s" % (self.depotPath, label)):
671 revisions[file["depotFile"]] = file["rev"]
672 change = int(file["change"])
673 if change > newestChange:
674 newestChange = change
676 self.labels[newestChange] = [output, revisions]
678 if self.verbose:
679 print "Label changes: %s" % self.labels.keys()
681 def getBranchMapping(self):
682 self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
684 for info in p4CmdList("branches"):
685 details = p4Cmd("branch -o %s" % info["branch"])
686 viewIdx = 0
687 while details.has_key("View%s" % viewIdx):
688 paths = details["View%s" % viewIdx].split(" ")
689 viewIdx = viewIdx + 1
690 # require standard //depot/foo/... //depot/bar/... mapping
691 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
692 continue
693 source = paths[0]
694 destination = paths[1]
695 if source.startswith(self.depotPath) and destination.startswith(self.depotPath):
696 source = source[len(self.depotPath):-4]
697 destination = destination[len(self.depotPath):-4]
698 if destination not in self.knownBranches:
699 self.knownBranches[destination] = source
700 if source not in self.knownBranches:
701 self.knownBranches[source] = source
703 def listExistingP4GitBranches(self):
704 self.p4BranchesInGit = []
706 for line in mypopen("git rev-parse --symbolic --remotes").readlines():
707 if line.startswith("p4/") and line != "p4/HEAD\n":
708 branch = line[3:-1]
709 self.p4BranchesInGit.append(branch)
710 self.initialParents["refs/remotes/p4/" + branch] = parseRevision(line[:-1])
712 def run(self, args):
713 self.depotPath = ""
714 self.changeRange = ""
715 self.initialParent = ""
716 self.previousDepotPath = ""
717 # map from branch depot path to parent branch
718 self.knownBranches = {}
719 self.initialParents = {}
721 self.listExistingP4GitBranches()
723 if self.syncWithOrigin and gitBranchExists("origin") and gitBranchExists("refs/remotes/p4/master") and not self.detectBranches:
724 ### needs to be ported to multi branch import
726 print "Syncing with origin first as requested by calling git fetch origin"
727 system("git fetch origin")
728 [originPreviousDepotPath, originP4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
729 [p4PreviousDepotPath, p4Change] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
730 if len(originPreviousDepotPath) > 0 and len(originP4Change) > 0 and len(p4Change) > 0:
731 if originPreviousDepotPath == p4PreviousDepotPath:
732 originP4Change = int(originP4Change)
733 p4Change = int(p4Change)
734 if originP4Change > p4Change:
735 print "origin (%s) is newer than p4 (%s). Updating p4 branch from origin." % (originP4Change, p4Change)
736 system("git update-ref refs/remotes/p4/master origin");
737 else:
738 print "Cannot sync with origin. It was imported from %s while remotes/p4 was imported from %s" % (originPreviousDepotPath, p4PreviousDepotPath)
740 if len(self.branch) == 0:
741 self.branch = "refs/remotes/p4/master"
742 if gitBranchExists("refs/heads/p4"):
743 system("git update-ref %s refs/heads/p4" % self.branch)
744 system("git branch -D p4");
745 if not gitBranchExists("refs/remotes/p4/HEAD"):
746 system("git symbolic-ref refs/remotes/p4/HEAD %s" % self.branch)
748 if len(args) == 0:
749 if not gitBranchExists(self.branch) and gitBranchExists("origin") and not self.detectBranches:
750 ### needs to be ported to multi branch import
751 if not self.silent:
752 print "Creating %s branch in git repository based on origin" % self.branch
753 branch = self.branch
754 if not branch.startswith("refs"):
755 branch = "refs/heads/" + branch
756 system("git update-ref %s origin" % branch)
758 if self.verbose:
759 print "branches: %s" % self.p4BranchesInGit
761 p4Change = 0
762 for branch in self.p4BranchesInGit:
763 depotPath, change = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("refs/remotes/p4/" + branch))
765 if self.verbose:
766 print "path %s change %s" % (depotPath, change)
768 if len(depotPath) > 0 and len(change) > 0:
769 change = int(change) + 1
770 p4Change = max(p4Change, change)
772 if len(self.previousDepotPath) == 0:
773 self.previousDepotPath = depotPath
774 else:
775 i = 0
776 l = min(len(self.previousDepotPath), len(depotPath))
777 while i < l and self.previousDepotPath[i] == depotPath[i]:
778 i = i + 1
779 self.previousDepotPath = self.previousDepotPath[:i]
781 if p4Change > 0:
782 self.depotPath = self.previousDepotPath
783 self.changeRange = "@%s,#head" % p4Change
784 self.initialParent = parseRevision(self.branch)
785 if not self.silent:
786 print "Performing incremental import into %s git branch" % self.branch
788 if not self.branch.startswith("refs/"):
789 self.branch = "refs/heads/" + self.branch
791 if len(self.depotPath) != 0:
792 self.depotPath = self.depotPath[:-1]
794 if len(args) == 0 and len(self.depotPath) != 0:
795 if not self.silent:
796 print "Depot path: %s" % self.depotPath
797 elif len(args) != 1:
798 return False
799 else:
800 if len(self.depotPath) != 0 and self.depotPath != args[0]:
801 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self.depotPath, args[0])
802 sys.exit(1)
803 self.depotPath = args[0]
805 self.revision = ""
806 self.users = {}
808 if self.depotPath.find("@") != -1:
809 atIdx = self.depotPath.index("@")
810 self.changeRange = self.depotPath[atIdx:]
811 if self.changeRange == "@all":
812 self.changeRange = ""
813 elif self.changeRange.find(",") == -1:
814 self.revision = self.changeRange
815 self.changeRange = ""
816 self.depotPath = self.depotPath[0:atIdx]
817 elif self.depotPath.find("#") != -1:
818 hashIdx = self.depotPath.index("#")
819 self.revision = self.depotPath[hashIdx:]
820 self.depotPath = self.depotPath[0:hashIdx]
821 elif len(self.previousDepotPath) == 0:
822 self.revision = "#head"
824 if self.depotPath.endswith("..."):
825 self.depotPath = self.depotPath[:-3]
827 if not self.depotPath.endswith("/"):
828 self.depotPath += "/"
830 self.loadUserMapFromCache()
831 self.labels = {}
832 if self.detectLabels:
833 self.getLabels();
835 if self.detectBranches:
836 self.getBranchMapping();
837 if self.verbose:
838 print "p4-git branches: %s" % self.p4BranchesInGit
839 print "initial parents: %s" % self.initialParents
840 for b in self.p4BranchesInGit:
841 if b != "master":
842 b = b[len(self.projectName):]
843 self.createdBranches.add(b)
845 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
847 importProcess = subprocess.Popen(["git", "fast-import"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE);
848 self.gitOutput = importProcess.stdout
849 self.gitStream = importProcess.stdin
850 self.gitError = importProcess.stderr
852 if len(self.revision) > 0:
853 print "Doing initial import of %s from revision %s" % (self.depotPath, self.revision)
855 details = { "user" : "git perforce import user", "time" : int(time.time()) }
856 details["desc"] = "Initial import of %s from the state at revision %s" % (self.depotPath, self.revision)
857 details["change"] = self.revision
858 newestRevision = 0
860 fileCnt = 0
861 for info in p4CmdList("files %s...%s" % (self.depotPath, self.revision)):
862 change = int(info["change"])
863 if change > newestRevision:
864 newestRevision = change
866 if info["action"] == "delete":
867 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
868 #fileCnt = fileCnt + 1
869 continue
871 for prop in [ "depotFile", "rev", "action", "type" ]:
872 details["%s%s" % (prop, fileCnt)] = info[prop]
874 fileCnt = fileCnt + 1
876 details["change"] = newestRevision
878 try:
879 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPath)
880 except IOError:
881 print "IO error with git fast-import. Is your git version recent enough?"
882 print self.gitError.read()
884 else:
885 changes = []
887 if len(self.changesFile) > 0:
888 output = open(self.changesFile).readlines()
889 changeSet = Set()
890 for line in output:
891 changeSet.add(int(line))
893 for change in changeSet:
894 changes.append(change)
896 changes.sort()
897 else:
898 if self.verbose:
899 print "Getting p4 changes for %s...%s" % (self.depotPath, self.changeRange)
900 output = mypopen("p4 changes %s...%s" % (self.depotPath, self.changeRange)).readlines()
902 for line in output:
903 changeNum = line.split(" ")[1]
904 changes.append(changeNum)
906 changes.reverse()
908 if len(changes) == 0:
909 if not self.silent:
910 print "no changes to import!"
911 return True
913 cnt = 1
914 for change in changes:
915 description = p4Cmd("describe %s" % change)
917 if not self.silent:
918 sys.stdout.write("\rimporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
919 sys.stdout.flush()
920 cnt = cnt + 1
922 try:
923 if self.detectBranches:
924 branches = self.splitFilesIntoBranches(description)
925 for branch in branches.keys():
926 branchPrefix = self.depotPath + branch + "/"
928 parent = ""
930 filesForCommit = branches[branch]
932 if self.verbose:
933 print "branch is %s" % branch
935 if branch not in self.createdBranches:
936 self.createdBranches.add(branch)
937 parent = self.knownBranches[branch]
938 if parent == branch:
939 parent = ""
940 elif self.verbose:
941 print "parent determined through known branches: %s" % parent
943 # main branch? use master
944 if branch == "main":
945 branch = "master"
946 else:
947 branch = self.projectName + branch
949 if parent == "main":
950 parent = "master"
951 elif len(parent) > 0:
952 parent = self.projectName + parent
954 branch = "refs/remotes/p4/" + branch
955 if len(parent) > 0:
956 parent = "refs/remotes/p4/" + parent
958 if self.verbose:
959 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
961 if len(parent) == 0 and branch in self.initialParents:
962 parent = self.initialParents[branch]
963 del self.initialParents[branch]
965 self.commit(description, filesForCommit, branch, branchPrefix, parent)
966 else:
967 files = self.extractFilesFromCommit(description)
968 self.commit(description, files, self.branch, self.depotPath, self.initialParent)
969 self.initialParent = ""
970 except IOError:
971 print self.gitError.read()
972 sys.exit(1)
974 if not self.silent:
975 print ""
978 self.gitStream.close()
979 if importProcess.wait() != 0:
980 die("fast-import failed: %s" % self.gitError.read())
981 self.gitOutput.close()
982 self.gitError.close()
984 return True
986 class P4Rebase(Command):
987 def __init__(self):
988 Command.__init__(self)
989 self.options = [ optparse.make_option("--with-origin", dest="syncWithOrigin", action="store_true") ]
990 self.description = "Fetches the latest revision from perforce and rebases the current work (branch) against it"
991 self.syncWithOrigin = False
993 def run(self, args):
994 sync = P4Sync()
995 sync.syncWithOrigin = self.syncWithOrigin
996 sync.run([])
997 print "Rebasing the current branch"
998 oldHead = mypopen("git rev-parse HEAD").read()[:-1]
999 system("git rebase p4")
1000 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
1001 return True
1003 class P4Clone(P4Sync):
1004 def __init__(self):
1005 P4Sync.__init__(self)
1006 self.description = "Creates a new git repository and imports from Perforce into it"
1007 self.usage = "usage: %prog [options] //depot/path[@revRange] [directory]"
1008 self.needsGit = False
1010 def run(self, args):
1011 global gitdir
1013 if len(args) < 1:
1014 return False
1015 depotPath = args[0]
1016 dir = ""
1017 if len(args) == 2:
1018 dir = args[1]
1019 elif len(args) > 2:
1020 return False
1022 if not depotPath.startswith("//"):
1023 return False
1025 if len(dir) == 0:
1026 dir = depotPath
1027 atPos = dir.rfind("@")
1028 if atPos != -1:
1029 dir = dir[0:atPos]
1030 hashPos = dir.rfind("#")
1031 if hashPos != -1:
1032 dir = dir[0:hashPos]
1034 if dir.endswith("..."):
1035 dir = dir[:-3]
1037 if dir.endswith("/"):
1038 dir = dir[:-1]
1040 slashPos = dir.rfind("/")
1041 if slashPos != -1:
1042 dir = dir[slashPos + 1:]
1044 print "Importing from %s into %s" % (depotPath, dir)
1045 os.makedirs(dir)
1046 os.chdir(dir)
1047 system("git init")
1048 gitdir = os.getcwd() + "/.git"
1049 if not P4Sync.run(self, [depotPath]):
1050 return False
1051 if self.branch != "master":
1052 if gitBranchExists("refs/remotes/p4/master"):
1053 system("git branch master refs/remotes/p4/master")
1054 system("git checkout -f")
1055 else:
1056 print "Could not detect main branch. No checkout/master branch created."
1057 return True
1059 class HelpFormatter(optparse.IndentedHelpFormatter):
1060 def __init__(self):
1061 optparse.IndentedHelpFormatter.__init__(self)
1063 def format_description(self, description):
1064 if description:
1065 return description + "\n"
1066 else:
1067 return ""
1069 def printUsage(commands):
1070 print "usage: %s <command> [options]" % sys.argv[0]
1071 print ""
1072 print "valid commands: %s" % ", ".join(commands)
1073 print ""
1074 print "Try %s <command> --help for command specific help." % sys.argv[0]
1075 print ""
1077 commands = {
1078 "debug" : P4Debug(),
1079 "submit" : P4Submit(),
1080 "sync" : P4Sync(),
1081 "rebase" : P4Rebase(),
1082 "clone" : P4Clone()
1085 if len(sys.argv[1:]) == 0:
1086 printUsage(commands.keys())
1087 sys.exit(2)
1089 cmd = ""
1090 cmdName = sys.argv[1]
1091 try:
1092 cmd = commands[cmdName]
1093 except KeyError:
1094 print "unknown command %s" % cmdName
1095 print ""
1096 printUsage(commands.keys())
1097 sys.exit(2)
1099 options = cmd.options
1100 cmd.gitdir = gitdir
1102 args = sys.argv[2:]
1104 if len(options) > 0:
1105 options.append(optparse.make_option("--git-dir", dest="gitdir"))
1107 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1108 options,
1109 description = cmd.description,
1110 formatter = HelpFormatter())
1112 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1114 if cmd.needsGit:
1115 gitdir = cmd.gitdir
1116 if len(gitdir) == 0:
1117 gitdir = ".git"
1118 if not isValidGitDir(gitdir):
1119 gitdir = mypopen("git rev-parse --git-dir").read()[:-1]
1120 if os.path.exists(gitdir):
1121 cdup = mypopen("git rev-parse --show-cdup").read()[:-1];
1122 if len(cdup) > 0:
1123 os.chdir(cdup);
1125 if not isValidGitDir(gitdir):
1126 if isValidGitDir(gitdir + "/.git"):
1127 gitdir += "/.git"
1128 else:
1129 die("fatal: cannot locate git repository at %s" % gitdir)
1131 os.environ["GIT_DIR"] = gitdir
1133 if not cmd.run(args):
1134 parser.print_help()