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>
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
15 gitdir
= os
.environ
.get("GIT_DIR", "")
18 return os
.popen(command
, "rb");
21 cmd
= "p4 -G %s" % cmd
22 pipe
= os
.popen(cmd
, "rb")
27 entry
= marshal
.load(pipe
)
31 exitCode
= pipe
.close()
34 entry
["p4ExitCode"] = exitCode
46 def p4Where(depotPath
):
47 if not depotPath
.endswith("/"):
49 output
= p4Cmd("where %s..." % depotPath
)
50 if output
["code"] == "error":
54 clientPath
= output
.get("path")
55 elif "data" in output
:
56 data
= output
.get("data")
57 lastSpace
= data
.rfind(" ")
58 clientPath
= data
[lastSpace
+ 1:]
60 if clientPath
.endswith("..."):
61 clientPath
= clientPath
[:-3]
65 sys
.stderr
.write(msg
+ "\n")
68 def currentGitBranch():
69 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
71 def isValidGitDir(path
):
72 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
76 def parseRevision(ref
):
77 return mypopen("git rev-parse %s" % ref
).read()[:-1]
80 if os
.system(cmd
) != 0:
81 die("command failed: %s" % cmd
)
83 def extractLogMessageFromGitCommit(commit
):
86 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
95 def extractDepotPathAndChangeFromGitLog(log
):
97 for line
in log
.split("\n"):
99 if line
.startswith("[git-p4:") and line
.endswith("]"):
100 line
= line
[8:-1].strip()
101 for assignment
in line
.split(":"):
102 variable
= assignment
.strip()
104 equalPos
= assignment
.find("=")
106 variable
= assignment
[:equalPos
].strip()
107 value
= assignment
[equalPos
+ 1:].strip()
108 if value
.startswith("\"") and value
.endswith("\""):
110 values
[variable
] = value
112 return values
.get("depot-path"), values
.get("change")
114 def gitBranchExists(branch
):
115 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
116 return proc
.wait() == 0;
119 return mypopen("git config %s" % key
).read()[:-1]
123 self
.usage
= "usage: %prog [options]"
126 class P4Debug(Command
):
128 Command
.__init
__(self
)
131 self
.description
= "A tool to debug the output of p4 -G."
132 self
.needsGit
= False
135 for output
in p4CmdList(" ".join(args
)):
139 class P4RollBack(Command
):
141 Command
.__init
__(self
)
143 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
144 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
146 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
148 self
.rollbackLocalBranches
= False
153 maxChange
= int(args
[0])
155 if "p4ExitCode" in p4Cmd("changes -m 1"):
156 die("Problems executing p4");
158 if self
.rollbackLocalBranches
:
159 refPrefix
= "refs/heads/"
160 lines
= mypopen("git rev-parse --symbolic --branches").readlines()
162 refPrefix
= "refs/remotes/"
163 lines
= mypopen("git rev-parse --symbolic --remotes").readlines()
166 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
167 ref
= refPrefix
+ line
[:-1]
168 log
= extractLogMessageFromGitCommit(ref
)
169 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
172 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath
, maxChange
))) == 0:
173 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
174 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
177 while len(change
) > 0 and int(change
) > maxChange
:
180 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
181 system("git update-ref %s \"%s^\"" % (ref
, ref
))
182 log
= extractLogMessageFromGitCommit(ref
)
183 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
186 print "%s rewound to %s" % (ref
, change
)
190 class P4Submit(Command
):
192 Command
.__init
__(self
)
194 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
195 optparse
.make_option("--origin", dest
="origin"),
196 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
197 optparse
.make_option("--log-substitutions", dest
="substFile"),
198 optparse
.make_option("--noninteractive", action
="store_false"),
199 optparse
.make_option("--dry-run", action
="store_true"),
200 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
202 self
.description
= "Submit changes from git to the perforce depot."
203 self
.usage
+= " [name of git branch to submit into perforce depot]"
204 self
.firstTime
= True
206 self
.interactive
= True
209 self
.firstTime
= True
211 self
.directSubmit
= False
213 self
.logSubstitutions
= {}
214 self
.logSubstitutions
["<enter description here>"] = "%log%"
215 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
218 if len(p4CmdList("opened ...")) > 0:
219 die("You have files opened with perforce! Close them before starting the sync.")
222 if len(self
.config
) > 0 and not self
.reset
:
223 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
)
226 if self
.directSubmit
:
229 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
230 commits
.append(line
[:-1])
233 self
.config
["commits"] = commits
235 def prepareLogMessage(self
, template
, message
):
238 for line
in template
.split("\n"):
239 if line
.startswith("#"):
240 result
+= line
+ "\n"
244 for key
in self
.logSubstitutions
.keys():
245 if line
.find(key
) != -1:
246 value
= self
.logSubstitutions
[key
]
247 value
= value
.replace("%log%", message
)
248 if value
!= "@remove@":
249 result
+= line
.replace(key
, value
) + "\n"
254 result
+= line
+ "\n"
259 if self
.directSubmit
:
260 print "Applying local change in working directory/index"
261 diff
= self
.diffStatus
263 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
264 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
266 filesToDelete
= set()
270 path
= line
[1:].strip()
272 system("p4 edit \"%s\"" % path
)
273 editedFiles
.add(path
)
274 elif modifier
== "A":
276 if path
in filesToDelete
:
277 filesToDelete
.remove(path
)
278 elif modifier
== "D":
279 filesToDelete
.add(path
)
280 if path
in filesToAdd
:
281 filesToAdd
.remove(path
)
283 die("unknown modifier %s for %s" % (modifier
, path
))
285 if self
.directSubmit
:
286 diffcmd
= "cat \"%s\"" % self
.diffFile
288 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
289 patchcmd
= diffcmd
+ " | git apply "
290 tryPatchCmd
= patchcmd
+ "--check -"
291 applyPatchCmd
= patchcmd
+ "--check --apply -"
293 if os
.system(tryPatchCmd
) != 0:
294 print "Unfortunately applying the change failed!"
295 print "What do you want to do?"
297 while response
!= "s" and response
!= "a" and response
!= "w":
298 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) ")
300 print "Skipping! Good luck with the next patches..."
302 elif response
== "a":
303 os
.system(applyPatchCmd
)
304 if len(filesToAdd
) > 0:
305 print "You may also want to call p4 add on the following files:"
306 print " ".join(filesToAdd
)
307 if len(filesToDelete
):
308 print "The following files should be scheduled for deletion with p4 delete:"
309 print " ".join(filesToDelete
)
310 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
311 elif response
== "w":
312 system(diffcmd
+ " > patch.txt")
313 print "Patch saved to patch.txt in %s !" % self
.clientPath
314 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
316 system(applyPatchCmd
)
319 system("p4 add %s" % f
)
320 for f
in filesToDelete
:
321 system("p4 revert %s" % f
)
322 system("p4 delete %s" % f
)
325 if not self
.directSubmit
:
326 logMessage
= extractLogMessageFromGitCommit(id)
327 logMessage
= logMessage
.replace("\n", "\n\t")
328 logMessage
= logMessage
[:-1]
330 template
= mypopen("p4 change -o").read()
333 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
334 diff
= mypopen("p4 diff -du ...").read()
336 for newFile
in filesToAdd
:
337 diff
+= "==== new file ====\n"
338 diff
+= "--- /dev/null\n"
339 diff
+= "+++ %s\n" % newFile
340 f
= open(newFile
, "r")
341 for line
in f
.readlines():
345 separatorLine
= "######## everything below this line is just the diff #######"
346 if platform
.system() == "Windows":
347 separatorLine
+= "\r"
348 separatorLine
+= "\n"
351 firstIteration
= True
352 while response
== "e":
353 if not firstIteration
:
354 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
355 firstIteration
= False
357 [handle
, fileName
] = tempfile
.mkstemp()
358 tmpFile
= os
.fdopen(handle
, "w+")
359 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
362 if platform
.system() == "Windows":
363 defaultEditor
= "notepad"
364 editor
= os
.environ
.get("EDITOR", defaultEditor
);
365 system(editor
+ " " + fileName
)
366 tmpFile
= open(fileName
, "rb")
367 message
= tmpFile
.read()
370 submitTemplate
= message
[:message
.index(separatorLine
)]
372 if response
== "y" or response
== "yes":
375 raw_input("Press return to continue...")
377 if self
.directSubmit
:
378 print "Submitting to git first"
379 os
.chdir(self
.oldWorkingDirectory
)
380 pipe
= os
.popen("git commit -a -F -", "wb")
381 pipe
.write(submitTemplate
)
383 os
.chdir(self
.clientPath
)
385 pipe
= os
.popen("p4 submit -i", "wb")
386 pipe
.write(submitTemplate
)
388 elif response
== "s":
389 for f
in editedFiles
:
390 system("p4 revert \"%s\"" % f
);
392 system("p4 revert \"%s\"" % f
);
394 for f
in filesToDelete
:
395 system("p4 delete \"%s\"" % f
);
398 print "Not submitting!"
399 self
.interactive
= False
401 fileName
= "submit.txt"
402 file = open(fileName
, "w+")
403 file.write(self
.prepareLogMessage(template
, logMessage
))
405 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
409 # make gitdir absolute so we can cd out into the perforce checkout
410 gitdir
= os
.path
.abspath(gitdir
)
411 os
.environ
["GIT_DIR"] = gitdir
414 self
.master
= currentGitBranch()
415 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
416 die("Detecting current git branch failed!")
418 self
.master
= args
[0]
423 if gitBranchExists("p4"):
424 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
425 if len(depotPath
) == 0 and gitBranchExists("origin"):
426 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
428 if len(depotPath
) == 0:
429 print "Internal error: cannot locate perforce depot path from existing branches"
432 self
.clientPath
= p4Where(depotPath
)
434 if len(self
.clientPath
) == 0:
435 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
438 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
439 self
.oldWorkingDirectory
= os
.getcwd()
441 if self
.directSubmit
:
442 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
443 if len(self
.diffStatus
) == 0:
444 print "No changes in working directory to submit."
446 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
447 self
.diffFile
= gitdir
+ "/p4-git-diff"
448 f
= open(self
.diffFile
, "wb")
452 os
.chdir(self
.clientPath
)
453 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
454 if response
== "y" or response
== "yes":
455 system("p4 sync ...")
457 if len(self
.origin
) == 0:
458 if gitBranchExists("p4"):
461 self
.origin
= "origin"
464 self
.firstTime
= True
466 if len(self
.substFile
) > 0:
467 for line
in open(self
.substFile
, "r").readlines():
468 tokens
= line
[:-1].split("=")
469 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
472 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
473 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
478 commits
= self
.config
.get("commits", [])
480 while len(commits
) > 0:
481 self
.firstTime
= False
483 commits
= commits
[1:]
484 self
.config
["commits"] = commits
486 if not self
.interactive
:
491 if self
.directSubmit
:
492 os
.remove(self
.diffFile
)
494 if len(commits
) == 0:
496 print "No changes found to apply between %s and current HEAD" % self
.origin
498 print "All changes applied!"
499 os
.chdir(self
.oldWorkingDirectory
)
500 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
501 if response
== "y" or response
== "yes":
504 os
.remove(self
.configFile
)
508 class P4Sync(Command
):
510 Command
.__init
__(self
)
512 optparse
.make_option("--branch", dest
="branch"),
513 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
514 optparse
.make_option("--changesfile", dest
="changesFile"),
515 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
516 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
517 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
518 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
519 optparse
.make_option("--max-changes", dest
="maxChanges")
521 self
.description
= """Imports from Perforce into a git repository.\n
523 //depot/my/project/ -- to import the current head
524 //depot/my/project/@all -- to import everything
525 //depot/my/project/@1,6 -- to import only from revision 1 to 6
527 (a ... is not needed in the path p4 specification, it's added implicitly)"""
529 self
.usage
+= " //depot/path[@revRange]"
532 self
.createdBranches
= Set()
533 self
.committedChanges
= Set()
535 self
.detectBranches
= False
536 self
.detectLabels
= False
537 self
.changesFile
= ""
538 self
.syncWithOrigin
= True
540 self
.importIntoRemotes
= True
542 self
.isWindows
= (platform
.system() == "Windows")
544 if gitConfig("git-p4.syncFromOrigin") == "false":
545 self
.syncWithOrigin
= False
547 def p4File(self
, depotPath
):
548 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
550 def extractFilesFromCommit(self
, commit
):
553 while commit
.has_key("depotFile%s" % fnum
):
554 path
= commit
["depotFile%s" % fnum
]
555 if not path
.startswith(self
.depotPath
):
556 # if not self.silent:
557 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
563 file["rev"] = commit
["rev%s" % fnum
]
564 file["action"] = commit
["action%s" % fnum
]
565 file["type"] = commit
["type%s" % fnum
]
570 def splitFilesIntoBranches(self
, commit
):
574 while commit
.has_key("depotFile%s" % fnum
):
575 path
= commit
["depotFile%s" % fnum
]
576 if not path
.startswith(self
.depotPath
):
577 # if not self.silent:
578 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
584 file["rev"] = commit
["rev%s" % fnum
]
585 file["action"] = commit
["action%s" % fnum
]
586 file["type"] = commit
["type%s" % fnum
]
589 relPath
= path
[len(self
.depotPath
):]
591 for branch
in self
.knownBranches
.keys():
592 if relPath
.startswith(branch
+ "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
593 if branch
not in branches
:
594 branches
[branch
] = []
595 branches
[branch
].append(file)
599 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
600 epoch
= details
["time"]
601 author
= details
["user"]
604 print "commit into %s" % branch
606 self
.gitStream
.write("commit %s\n" % branch
)
607 # gitStream.write("mark :%s\n" % details["change"])
608 self
.committedChanges
.add(int(details
["change"]))
610 if author
not in self
.users
:
611 self
.getUserMapFromPerforceServer()
612 if author
in self
.users
:
613 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
615 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
617 self
.gitStream
.write("committer %s\n" % committer
)
619 self
.gitStream
.write("data <<EOT\n")
620 self
.gitStream
.write(details
["desc"])
621 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
622 self
.gitStream
.write("EOT\n\n")
626 print "parent %s" % parent
627 self
.gitStream
.write("from %s\n" % parent
)
631 if not path
.startswith(branchPrefix
):
633 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
636 depotPath
= path
+ "#" + rev
637 relPath
= path
[len(branchPrefix
):]
638 action
= file["action"]
640 if file["type"] == "apple":
641 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
644 if action
== "delete":
645 self
.gitStream
.write("D %s\n" % relPath
)
648 if file["type"].startswith("x"):
651 data
= self
.p4File(depotPath
)
653 if self
.isWindows
and file["type"].endswith("text"):
654 data
= data
.replace("\r\n", "\n")
656 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
657 self
.gitStream
.write("data %s\n" % len(data
))
658 self
.gitStream
.write(data
)
659 self
.gitStream
.write("\n")
661 self
.gitStream
.write("\n")
663 change
= int(details
["change"])
665 if self
.labels
.has_key(change
):
666 label
= self
.labels
[change
]
667 labelDetails
= label
[0]
668 labelRevisions
= label
[1]
670 print "Change %s is labelled %s" % (change
, labelDetails
)
672 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
674 if len(files
) == len(labelRevisions
):
678 if info
["action"] == "delete":
680 cleanedFiles
[info
["depotFile"]] = info
["rev"]
682 if cleanedFiles
== labelRevisions
:
683 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
684 self
.gitStream
.write("from %s\n" % branch
)
686 owner
= labelDetails
["Owner"]
688 if author
in self
.users
:
689 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
691 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
692 self
.gitStream
.write("tagger %s\n" % tagger
)
693 self
.gitStream
.write("data <<EOT\n")
694 self
.gitStream
.write(labelDetails
["Description"])
695 self
.gitStream
.write("EOT\n\n")
699 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
703 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
705 def getUserMapFromPerforceServer(self
):
706 if self
.userMapFromPerforceServer
:
710 for output
in p4CmdList("users"):
711 if not output
.has_key("User"):
713 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
715 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
716 for user
in self
.users
.keys():
717 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
719 self
.userMapFromPerforceServer
= True
721 def loadUserMapFromCache(self
):
723 self
.userMapFromPerforceServer
= False
725 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
726 lines
= cache
.readlines()
729 entry
= line
[:-1].split("\t")
730 self
.users
[entry
[0]] = entry
[1]
732 self
.getUserMapFromPerforceServer()
737 l
= p4CmdList("labels %s..." % self
.depotPath
)
738 if len(l
) > 0 and not self
.silent
:
739 print "Finding files belonging to labels in %s" % self
.depotPath
742 label
= output
["label"]
746 print "Querying files for label %s" % label
747 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
748 revisions
[file["depotFile"]] = file["rev"]
749 change
= int(file["change"])
750 if change
> newestChange
:
751 newestChange
= change
753 self
.labels
[newestChange
] = [output
, revisions
]
756 print "Label changes: %s" % self
.labels
.keys()
758 def getBranchMapping(self
):
759 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
761 for info
in p4CmdList("branches"):
762 details
= p4Cmd("branch -o %s" % info
["branch"])
764 while details
.has_key("View%s" % viewIdx
):
765 paths
= details
["View%s" % viewIdx
].split(" ")
766 viewIdx
= viewIdx
+ 1
767 # require standard //depot/foo/... //depot/bar/... mapping
768 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
771 destination
= paths
[1]
772 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
773 source
= source
[len(self
.depotPath
):-4]
774 destination
= destination
[len(self
.depotPath
):-4]
775 if destination
not in self
.knownBranches
:
776 self
.knownBranches
[destination
] = source
777 if source
not in self
.knownBranches
:
778 self
.knownBranches
[source
] = source
780 def listExistingP4GitBranches(self
):
781 self
.p4BranchesInGit
= []
783 cmdline
= "git rev-parse --symbolic "
784 if self
.importIntoRemotes
:
785 cmdline
+= " --remotes"
787 cmdline
+= " --branches"
789 for line
in mypopen(cmdline
).readlines():
790 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
792 if self
.importIntoRemotes
:
797 self
.p4BranchesInGit
.append(branch
)
798 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
[:-1])
800 def createOrUpdateBranchesFromOrigin(self
):
802 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
804 for line
in mypopen("git rev-parse --symbolic --remotes"):
805 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
808 headName
= line
[len("origin/"):-1]
809 remoteHead
= self
.refPrefix
+ headName
810 originHead
= "origin/" + headName
812 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
813 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
817 if not gitBranchExists(remoteHead
):
819 print "creating %s" % remoteHead
822 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
823 if len(p4Change
) > 0:
824 if originPreviousDepotPath
== p4PreviousDepotPath
:
825 originP4Change
= int(originP4Change
)
826 p4Change
= int(p4Change
)
827 if originP4Change
> p4Change
:
828 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
831 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
834 system("git update-ref %s %s" % (remoteHead
, originHead
))
838 self
.changeRange
= ""
839 self
.initialParent
= ""
840 self
.previousDepotPath
= ""
841 # map from branch depot path to parent branch
842 self
.knownBranches
= {}
843 self
.initialParents
= {}
844 self
.hasOrigin
= gitBranchExists("origin")
846 if self
.importIntoRemotes
:
847 self
.refPrefix
= "refs/remotes/p4/"
849 self
.refPrefix
= "refs/heads/"
851 if self
.syncWithOrigin
:
854 print "Syncing with origin first by calling git fetch origin"
855 system("git fetch origin")
857 createP4HeadRef
= False;
859 if len(self
.branch
) == 0:
860 self
.branch
= self
.refPrefix
+ "master"
861 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
862 system("git update-ref %s refs/heads/p4" % self
.branch
)
863 system("git branch -D p4");
864 # create it /after/ importing, when master exists
865 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
866 createP4HeadRef
= True
870 self
.createOrUpdateBranchesFromOrigin()
871 self
.listExistingP4GitBranches()
873 if len(self
.p4BranchesInGit
) > 1:
875 print "Importing from/into multiple branches"
876 self
.detectBranches
= True
879 print "branches: %s" % self
.p4BranchesInGit
882 for branch
in self
.p4BranchesInGit
:
883 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self
.refPrefix
+ branch
))
886 print "path %s change %s" % (depotPath
, change
)
888 if len(depotPath
) > 0 and len(change
) > 0:
889 change
= int(change
) + 1
890 p4Change
= max(p4Change
, change
)
892 if len(self
.previousDepotPath
) == 0:
893 self
.previousDepotPath
= depotPath
896 l
= min(len(self
.previousDepotPath
), len(depotPath
))
897 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
899 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
902 self
.depotPath
= self
.previousDepotPath
903 self
.changeRange
= "@%s,#head" % p4Change
904 self
.initialParent
= parseRevision(self
.branch
)
905 if not self
.silent
and not self
.detectBranches
:
906 print "Performing incremental import into %s git branch" % self
.branch
908 if not self
.branch
.startswith("refs/"):
909 self
.branch
= "refs/heads/" + self
.branch
911 if len(self
.depotPath
) != 0:
912 self
.depotPath
= self
.depotPath
[:-1]
914 if len(args
) == 0 and len(self
.depotPath
) != 0:
916 print "Depot path: %s" % self
.depotPath
920 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
921 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
923 self
.depotPath
= args
[0]
928 if self
.depotPath
.find("@") != -1:
929 atIdx
= self
.depotPath
.index("@")
930 self
.changeRange
= self
.depotPath
[atIdx
:]
931 if self
.changeRange
== "@all":
932 self
.changeRange
= ""
933 elif self
.changeRange
.find(",") == -1:
934 self
.revision
= self
.changeRange
935 self
.changeRange
= ""
936 self
.depotPath
= self
.depotPath
[0:atIdx
]
937 elif self
.depotPath
.find("#") != -1:
938 hashIdx
= self
.depotPath
.index("#")
939 self
.revision
= self
.depotPath
[hashIdx
:]
940 self
.depotPath
= self
.depotPath
[0:hashIdx
]
941 elif len(self
.previousDepotPath
) == 0:
942 self
.revision
= "#head"
944 if self
.depotPath
.endswith("..."):
945 self
.depotPath
= self
.depotPath
[:-3]
947 if not self
.depotPath
.endswith("/"):
948 self
.depotPath
+= "/"
950 self
.loadUserMapFromCache()
952 if self
.detectLabels
:
955 if self
.detectBranches
:
956 self
.getBranchMapping();
958 print "p4-git branches: %s" % self
.p4BranchesInGit
959 print "initial parents: %s" % self
.initialParents
960 for b
in self
.p4BranchesInGit
:
962 b
= b
[len(self
.projectName
):]
963 self
.createdBranches
.add(b
)
965 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
967 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
968 self
.gitOutput
= importProcess
.stdout
969 self
.gitStream
= importProcess
.stdin
970 self
.gitError
= importProcess
.stderr
972 if len(self
.revision
) > 0:
973 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
975 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
976 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
977 details
["change"] = self
.revision
981 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
982 change
= int(info
["change"])
983 if change
> newestRevision
:
984 newestRevision
= change
986 if info
["action"] == "delete":
987 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
988 #fileCnt = fileCnt + 1
991 for prop
in [ "depotFile", "rev", "action", "type" ]:
992 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
994 fileCnt
= fileCnt
+ 1
996 details
["change"] = newestRevision
999 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
1001 print "IO error with git fast-import. Is your git version recent enough?"
1002 print self
.gitError
.read()
1007 if len(self
.changesFile
) > 0:
1008 output
= open(self
.changesFile
).readlines()
1011 changeSet
.add(int(line
))
1013 for change
in changeSet
:
1014 changes
.append(change
)
1019 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
1020 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
1023 changeNum
= line
.split(" ")[1]
1024 changes
.append(changeNum
)
1028 if len(self
.maxChanges
) > 0:
1029 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1031 if len(changes
) == 0:
1033 print "No changes to import!"
1036 self
.updatedBranches
= set()
1039 for change
in changes
:
1040 description
= p4Cmd("describe %s" % change
)
1043 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1048 if self
.detectBranches
:
1049 branches
= self
.splitFilesIntoBranches(description
)
1050 for branch
in branches
.keys():
1051 branchPrefix
= self
.depotPath
+ branch
+ "/"
1055 filesForCommit
= branches
[branch
]
1058 print "branch is %s" % branch
1060 self
.updatedBranches
.add(branch
)
1062 if branch
not in self
.createdBranches
:
1063 self
.createdBranches
.add(branch
)
1064 parent
= self
.knownBranches
[branch
]
1065 if parent
== branch
:
1068 print "parent determined through known branches: %s" % parent
1070 # main branch? use master
1071 if branch
== "main":
1074 branch
= self
.projectName
+ branch
1076 if parent
== "main":
1078 elif len(parent
) > 0:
1079 parent
= self
.projectName
+ parent
1081 branch
= self
.refPrefix
+ branch
1083 parent
= self
.refPrefix
+ parent
1086 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1088 if len(parent
) == 0 and branch
in self
.initialParents
:
1089 parent
= self
.initialParents
[branch
]
1090 del self
.initialParents
[branch
]
1092 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1094 files
= self
.extractFilesFromCommit(description
)
1095 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1096 self
.initialParent
= ""
1098 print self
.gitError
.read()
1103 if len(self
.updatedBranches
) > 0:
1104 sys
.stdout
.write("Updated branches: ")
1105 for b
in self
.updatedBranches
:
1106 sys
.stdout
.write("%s " % b
)
1107 sys
.stdout
.write("\n")
1110 self
.gitStream
.close()
1111 if importProcess
.wait() != 0:
1112 die("fast-import failed: %s" % self
.gitError
.read())
1113 self
.gitOutput
.close()
1114 self
.gitError
.close()
1117 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1121 class P4Rebase(Command
):
1123 Command
.__init
__(self
)
1125 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1127 def run(self
, args
):
1130 print "Rebasing the current branch"
1131 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1132 system("git rebase p4")
1133 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1136 class P4Clone(P4Sync
):
1138 P4Sync
.__init
__(self
)
1139 self
.description
= "Creates a new git repository and imports from Perforce into it"
1140 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1141 self
.needsGit
= False
1143 def run(self
, args
):
1155 if not depotPath
.startswith("//"):
1160 atPos
= dir.rfind("@")
1163 hashPos
= dir.rfind("#")
1165 dir = dir[0:hashPos
]
1167 if dir.endswith("..."):
1170 if dir.endswith("/"):
1173 slashPos
= dir.rfind("/")
1175 dir = dir[slashPos
+ 1:]
1177 print "Importing from %s into %s" % (depotPath
, dir)
1181 gitdir
= os
.getcwd() + "/.git"
1182 if not P4Sync
.run(self
, [depotPath
]):
1184 if self
.branch
!= "master":
1185 if gitBranchExists("refs/remotes/p4/master"):
1186 system("git branch master refs/remotes/p4/master")
1187 system("git checkout -f")
1189 print "Could not detect main branch. No checkout/master branch created."
1192 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1194 optparse
.IndentedHelpFormatter
.__init
__(self
)
1196 def format_description(self
, description
):
1198 return description
+ "\n"
1202 def printUsage(commands
):
1203 print "usage: %s <command> [options]" % sys
.argv
[0]
1205 print "valid commands: %s" % ", ".join(commands
)
1207 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1211 "debug" : P4Debug(),
1212 "submit" : P4Submit(),
1214 "rebase" : P4Rebase(),
1215 "clone" : P4Clone(),
1216 "rollback" : P4RollBack()
1219 if len(sys
.argv
[1:]) == 0:
1220 printUsage(commands
.keys())
1224 cmdName
= sys
.argv
[1]
1226 cmd
= commands
[cmdName
]
1228 print "unknown command %s" % cmdName
1230 printUsage(commands
.keys())
1233 options
= cmd
.options
1238 if len(options
) > 0:
1239 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1241 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1243 description
= cmd
.description
,
1244 formatter
= HelpFormatter())
1246 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1250 if len(gitdir
) == 0:
1252 if not isValidGitDir(gitdir
):
1253 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1254 if os
.path
.exists(gitdir
):
1255 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1259 if not isValidGitDir(gitdir
):
1260 if isValidGitDir(gitdir
+ "/.git"):
1263 die("fatal: cannot locate git repository at %s" % gitdir
)
1265 os
.environ
["GIT_DIR"] = gitdir
1267 if not cmd
.run(args
):