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>
10 # TODO: * Consider making --with-origin the default, assuming that the git
11 # protocol is always more efficient. (needs manual testing first :)
14 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
15 import tempfile
, getopt
, sha
, os
.path
, time
, platform
18 gitdir
= os
.environ
.get("GIT_DIR", "")
21 return os
.popen(command
, "rb");
24 cmd
= "p4 -G %s" % cmd
25 pipe
= os
.popen(cmd
, "rb")
30 entry
= marshal
.load(pipe
)
34 exitCode
= pipe
.close()
37 entry
["p4ExitCode"] = exitCode
49 def p4Where(depotPath
):
50 if not depotPath
.endswith("/"):
52 output
= p4Cmd("where %s..." % depotPath
)
53 if output
["code"] == "error":
57 clientPath
= output
.get("path")
58 elif "data" in output
:
59 data
= output
.get("data")
60 lastSpace
= data
.rfind(" ")
61 clientPath
= data
[lastSpace
+ 1:]
63 if clientPath
.endswith("..."):
64 clientPath
= clientPath
[:-3]
68 sys
.stderr
.write(msg
+ "\n")
71 def currentGitBranch():
72 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
74 def isValidGitDir(path
):
75 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
79 def parseRevision(ref
):
80 return mypopen("git rev-parse %s" % ref
).read()[:-1]
83 if os
.system(cmd
) != 0:
84 die("command failed: %s" % cmd
)
86 def extractLogMessageFromGitCommit(commit
):
89 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
98 def extractDepotPathAndChangeFromGitLog(log
):
100 for line
in log
.split("\n"):
102 if line
.startswith("[git-p4:") and line
.endswith("]"):
103 line
= line
[8:-1].strip()
104 for assignment
in line
.split(":"):
105 variable
= assignment
.strip()
107 equalPos
= assignment
.find("=")
109 variable
= assignment
[:equalPos
].strip()
110 value
= assignment
[equalPos
+ 1:].strip()
111 if value
.startswith("\"") and value
.endswith("\""):
113 values
[variable
] = value
115 return values
.get("depot-path"), values
.get("change")
117 def gitBranchExists(branch
):
118 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
119 return proc
.wait() == 0;
122 return mypopen("git config %s" % key
).read()[:-1]
126 self
.usage
= "usage: %prog [options]"
129 class P4Debug(Command
):
131 Command
.__init
__(self
)
134 self
.description
= "A tool to debug the output of p4 -G."
135 self
.needsGit
= False
138 for output
in p4CmdList(" ".join(args
)):
142 class P4RollBack(Command
):
144 Command
.__init
__(self
)
146 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
147 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
149 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
151 self
.rollbackLocalBranches
= False
156 maxChange
= int(args
[0])
158 if "p4ExitCode" in p4Cmd("changes -m 1"):
159 die("Problems executing p4");
161 if self
.rollbackLocalBranches
:
162 refPrefix
= "refs/heads/"
163 lines
= mypopen("git rev-parse --symbolic --branches").readlines()
165 refPrefix
= "refs/remotes/"
166 lines
= mypopen("git rev-parse --symbolic --remotes").readlines()
169 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
170 ref
= refPrefix
+ line
[:-1]
171 log
= extractLogMessageFromGitCommit(ref
)
172 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
175 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath
, maxChange
))) == 0:
176 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
177 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
180 while len(change
) > 0 and int(change
) > maxChange
:
183 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
184 system("git update-ref %s \"%s^\"" % (ref
, ref
))
185 log
= extractLogMessageFromGitCommit(ref
)
186 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
189 print "%s rewound to %s" % (ref
, change
)
193 class P4Submit(Command
):
195 Command
.__init
__(self
)
197 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
198 optparse
.make_option("--origin", dest
="origin"),
199 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
200 optparse
.make_option("--log-substitutions", dest
="substFile"),
201 optparse
.make_option("--noninteractive", action
="store_false"),
202 optparse
.make_option("--dry-run", action
="store_true"),
203 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
205 self
.description
= "Submit changes from git to the perforce depot."
206 self
.usage
+= " [name of git branch to submit into perforce depot]"
207 self
.firstTime
= True
209 self
.interactive
= True
212 self
.firstTime
= True
214 self
.directSubmit
= False
216 self
.logSubstitutions
= {}
217 self
.logSubstitutions
["<enter description here>"] = "%log%"
218 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
221 if len(p4CmdList("opened ...")) > 0:
222 die("You have files opened with perforce! Close them before starting the sync.")
225 if len(self
.config
) > 0 and not self
.reset
:
226 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
)
229 if self
.directSubmit
:
232 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
233 commits
.append(line
[:-1])
236 self
.config
["commits"] = commits
238 def prepareLogMessage(self
, template
, message
):
241 for line
in template
.split("\n"):
242 if line
.startswith("#"):
243 result
+= line
+ "\n"
247 for key
in self
.logSubstitutions
.keys():
248 if line
.find(key
) != -1:
249 value
= self
.logSubstitutions
[key
]
250 value
= value
.replace("%log%", message
)
251 if value
!= "@remove@":
252 result
+= line
.replace(key
, value
) + "\n"
257 result
+= line
+ "\n"
262 if self
.directSubmit
:
263 print "Applying local change in working directory/index"
264 diff
= self
.diffStatus
266 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
267 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
269 filesToDelete
= set()
273 path
= line
[1:].strip()
275 system("p4 edit \"%s\"" % path
)
276 editedFiles
.add(path
)
277 elif modifier
== "A":
279 if path
in filesToDelete
:
280 filesToDelete
.remove(path
)
281 elif modifier
== "D":
282 filesToDelete
.add(path
)
283 if path
in filesToAdd
:
284 filesToAdd
.remove(path
)
286 die("unknown modifier %s for %s" % (modifier
, path
))
288 if self
.directSubmit
:
289 diffcmd
= "cat \"%s\"" % self
.diffFile
291 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
292 patchcmd
= diffcmd
+ " | git apply "
293 tryPatchCmd
= patchcmd
+ "--check -"
294 applyPatchCmd
= patchcmd
+ "--check --apply -"
296 if os
.system(tryPatchCmd
) != 0:
297 print "Unfortunately applying the change failed!"
298 print "What do you want to do?"
300 while response
!= "s" and response
!= "a" and response
!= "w":
301 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) ")
303 print "Skipping! Good luck with the next patches..."
305 elif response
== "a":
306 os
.system(applyPatchCmd
)
307 if len(filesToAdd
) > 0:
308 print "You may also want to call p4 add on the following files:"
309 print " ".join(filesToAdd
)
310 if len(filesToDelete
):
311 print "The following files should be scheduled for deletion with p4 delete:"
312 print " ".join(filesToDelete
)
313 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
314 elif response
== "w":
315 system(diffcmd
+ " > patch.txt")
316 print "Patch saved to patch.txt in %s !" % self
.clientPath
317 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
319 system(applyPatchCmd
)
322 system("p4 add %s" % f
)
323 for f
in filesToDelete
:
324 system("p4 revert %s" % f
)
325 system("p4 delete %s" % f
)
328 if not self
.directSubmit
:
329 logMessage
= extractLogMessageFromGitCommit(id)
330 logMessage
= logMessage
.replace("\n", "\n\t")
331 logMessage
= logMessage
[:-1]
333 template
= mypopen("p4 change -o").read()
336 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
337 diff
= mypopen("p4 diff -du ...").read()
339 for newFile
in filesToAdd
:
340 diff
+= "==== new file ====\n"
341 diff
+= "--- /dev/null\n"
342 diff
+= "+++ %s\n" % newFile
343 f
= open(newFile
, "r")
344 for line
in f
.readlines():
348 separatorLine
= "######## everything below this line is just the diff #######"
349 if platform
.system() == "Windows":
350 separatorLine
+= "\r"
351 separatorLine
+= "\n"
354 firstIteration
= True
355 while response
== "e":
356 if not firstIteration
:
357 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
358 firstIteration
= False
360 [handle
, fileName
] = tempfile
.mkstemp()
361 tmpFile
= os
.fdopen(handle
, "w+")
362 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
365 if platform
.system() == "Windows":
366 defaultEditor
= "notepad"
367 editor
= os
.environ
.get("EDITOR", defaultEditor
);
368 system(editor
+ " " + fileName
)
369 tmpFile
= open(fileName
, "rb")
370 message
= tmpFile
.read()
373 submitTemplate
= message
[:message
.index(separatorLine
)]
375 if response
== "y" or response
== "yes":
378 raw_input("Press return to continue...")
380 if self
.directSubmit
:
381 print "Submitting to git first"
382 os
.chdir(self
.oldWorkingDirectory
)
383 pipe
= os
.popen("git commit -a -F -", "wb")
384 pipe
.write(submitTemplate
)
386 os
.chdir(self
.clientPath
)
388 pipe
= os
.popen("p4 submit -i", "wb")
389 pipe
.write(submitTemplate
)
391 elif response
== "s":
392 for f
in editedFiles
:
393 system("p4 revert \"%s\"" % f
);
395 system("p4 revert \"%s\"" % f
);
397 for f
in filesToDelete
:
398 system("p4 delete \"%s\"" % f
);
401 print "Not submitting!"
402 self
.interactive
= False
404 fileName
= "submit.txt"
405 file = open(fileName
, "w+")
406 file.write(self
.prepareLogMessage(template
, logMessage
))
408 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
412 # make gitdir absolute so we can cd out into the perforce checkout
413 gitdir
= os
.path
.abspath(gitdir
)
414 os
.environ
["GIT_DIR"] = gitdir
417 self
.master
= currentGitBranch()
418 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
419 die("Detecting current git branch failed!")
421 self
.master
= args
[0]
426 if gitBranchExists("p4"):
427 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
428 if len(depotPath
) == 0 and gitBranchExists("origin"):
429 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
431 if len(depotPath
) == 0:
432 print "Internal error: cannot locate perforce depot path from existing branches"
435 self
.clientPath
= p4Where(depotPath
)
437 if len(self
.clientPath
) == 0:
438 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
441 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
442 self
.oldWorkingDirectory
= os
.getcwd()
444 if self
.directSubmit
:
445 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
446 if len(self
.diffStatus
) == 0:
447 print "No changes in working directory to submit."
449 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
450 self
.diffFile
= gitdir
+ "/p4-git-diff"
451 f
= open(self
.diffFile
, "wb")
455 os
.chdir(self
.clientPath
)
456 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
457 if response
== "y" or response
== "yes":
458 system("p4 sync ...")
460 if len(self
.origin
) == 0:
461 if gitBranchExists("p4"):
464 self
.origin
= "origin"
467 self
.firstTime
= True
469 if len(self
.substFile
) > 0:
470 for line
in open(self
.substFile
, "r").readlines():
471 tokens
= line
[:-1].split("=")
472 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
475 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
476 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
481 commits
= self
.config
.get("commits", [])
483 while len(commits
) > 0:
484 self
.firstTime
= False
486 commits
= commits
[1:]
487 self
.config
["commits"] = commits
489 if not self
.interactive
:
494 if self
.directSubmit
:
495 os
.remove(self
.diffFile
)
497 if len(commits
) == 0:
499 print "No changes found to apply between %s and current HEAD" % self
.origin
501 print "All changes applied!"
502 os
.chdir(self
.oldWorkingDirectory
)
503 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
504 if response
== "y" or response
== "yes":
507 os
.remove(self
.configFile
)
511 class P4Sync(Command
):
513 Command
.__init
__(self
)
515 optparse
.make_option("--branch", dest
="branch"),
516 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
517 optparse
.make_option("--changesfile", dest
="changesFile"),
518 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
519 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
520 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
521 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
522 optparse
.make_option("--max-changes", dest
="maxChanges")
524 self
.description
= """Imports from Perforce into a git repository.\n
526 //depot/my/project/ -- to import the current head
527 //depot/my/project/@all -- to import everything
528 //depot/my/project/@1,6 -- to import only from revision 1 to 6
530 (a ... is not needed in the path p4 specification, it's added implicitly)"""
532 self
.usage
+= " //depot/path[@revRange]"
535 self
.createdBranches
= Set()
536 self
.committedChanges
= Set()
538 self
.detectBranches
= False
539 self
.detectLabels
= False
540 self
.changesFile
= ""
541 self
.syncWithOrigin
= True
543 self
.importIntoRemotes
= True
545 self
.isWindows
= (platform
.system() == "Windows")
547 if gitConfig("git-p4.syncFromOrigin") == "false":
548 self
.syncWithOrigin
= False
550 def p4File(self
, depotPath
):
551 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
553 def extractFilesFromCommit(self
, commit
):
556 while commit
.has_key("depotFile%s" % fnum
):
557 path
= commit
["depotFile%s" % fnum
]
558 if not path
.startswith(self
.depotPath
):
559 # if not self.silent:
560 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
566 file["rev"] = commit
["rev%s" % fnum
]
567 file["action"] = commit
["action%s" % fnum
]
568 file["type"] = commit
["type%s" % fnum
]
573 def splitFilesIntoBranches(self
, commit
):
577 while commit
.has_key("depotFile%s" % fnum
):
578 path
= commit
["depotFile%s" % fnum
]
579 if not path
.startswith(self
.depotPath
):
580 # if not self.silent:
581 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
587 file["rev"] = commit
["rev%s" % fnum
]
588 file["action"] = commit
["action%s" % fnum
]
589 file["type"] = commit
["type%s" % fnum
]
592 relPath
= path
[len(self
.depotPath
):]
594 for branch
in self
.knownBranches
.keys():
595 if relPath
.startswith(branch
+ "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
596 if branch
not in branches
:
597 branches
[branch
] = []
598 branches
[branch
].append(file)
602 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
603 epoch
= details
["time"]
604 author
= details
["user"]
607 print "commit into %s" % branch
609 self
.gitStream
.write("commit %s\n" % branch
)
610 # gitStream.write("mark :%s\n" % details["change"])
611 self
.committedChanges
.add(int(details
["change"]))
613 if author
not in self
.users
:
614 self
.getUserMapFromPerforceServer()
615 if author
in self
.users
:
616 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
618 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
620 self
.gitStream
.write("committer %s\n" % committer
)
622 self
.gitStream
.write("data <<EOT\n")
623 self
.gitStream
.write(details
["desc"])
624 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
625 self
.gitStream
.write("EOT\n\n")
629 print "parent %s" % parent
630 self
.gitStream
.write("from %s\n" % parent
)
634 if not path
.startswith(branchPrefix
):
636 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
639 depotPath
= path
+ "#" + rev
640 relPath
= path
[len(branchPrefix
):]
641 action
= file["action"]
643 if file["type"] == "apple":
644 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
647 if action
== "delete":
648 self
.gitStream
.write("D %s\n" % relPath
)
651 if file["type"].startswith("x"):
654 data
= self
.p4File(depotPath
)
656 if self
.isWindows
and file["type"].endswith("text"):
657 data
= data
.replace("\r\n", "\n")
659 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
660 self
.gitStream
.write("data %s\n" % len(data
))
661 self
.gitStream
.write(data
)
662 self
.gitStream
.write("\n")
664 self
.gitStream
.write("\n")
666 change
= int(details
["change"])
668 if self
.labels
.has_key(change
):
669 label
= self
.labels
[change
]
670 labelDetails
= label
[0]
671 labelRevisions
= label
[1]
673 print "Change %s is labelled %s" % (change
, labelDetails
)
675 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
677 if len(files
) == len(labelRevisions
):
681 if info
["action"] == "delete":
683 cleanedFiles
[info
["depotFile"]] = info
["rev"]
685 if cleanedFiles
== labelRevisions
:
686 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
687 self
.gitStream
.write("from %s\n" % branch
)
689 owner
= labelDetails
["Owner"]
691 if author
in self
.users
:
692 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
694 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
695 self
.gitStream
.write("tagger %s\n" % tagger
)
696 self
.gitStream
.write("data <<EOT\n")
697 self
.gitStream
.write(labelDetails
["Description"])
698 self
.gitStream
.write("EOT\n\n")
702 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
706 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
708 def getUserMapFromPerforceServer(self
):
709 if self
.userMapFromPerforceServer
:
713 for output
in p4CmdList("users"):
714 if not output
.has_key("User"):
716 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
718 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
719 for user
in self
.users
.keys():
720 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
722 self
.userMapFromPerforceServer
= True
724 def loadUserMapFromCache(self
):
726 self
.userMapFromPerforceServer
= False
728 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
729 lines
= cache
.readlines()
732 entry
= line
[:-1].split("\t")
733 self
.users
[entry
[0]] = entry
[1]
735 self
.getUserMapFromPerforceServer()
740 l
= p4CmdList("labels %s..." % self
.depotPath
)
741 if len(l
) > 0 and not self
.silent
:
742 print "Finding files belonging to labels in %s" % self
.depotPath
745 label
= output
["label"]
749 print "Querying files for label %s" % label
750 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
751 revisions
[file["depotFile"]] = file["rev"]
752 change
= int(file["change"])
753 if change
> newestChange
:
754 newestChange
= change
756 self
.labels
[newestChange
] = [output
, revisions
]
759 print "Label changes: %s" % self
.labels
.keys()
761 def getBranchMapping(self
):
762 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
764 for info
in p4CmdList("branches"):
765 details
= p4Cmd("branch -o %s" % info
["branch"])
767 while details
.has_key("View%s" % viewIdx
):
768 paths
= details
["View%s" % viewIdx
].split(" ")
769 viewIdx
= viewIdx
+ 1
770 # require standard //depot/foo/... //depot/bar/... mapping
771 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
774 destination
= paths
[1]
775 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
776 source
= source
[len(self
.depotPath
):-4]
777 destination
= destination
[len(self
.depotPath
):-4]
778 if destination
not in self
.knownBranches
:
779 self
.knownBranches
[destination
] = source
780 if source
not in self
.knownBranches
:
781 self
.knownBranches
[source
] = source
783 def listExistingP4GitBranches(self
):
784 self
.p4BranchesInGit
= []
786 cmdline
= "git rev-parse --symbolic "
787 if self
.importIntoRemotes
:
788 cmdline
+= " --remotes"
790 cmdline
+= " --branches"
792 for line
in mypopen(cmdline
).readlines():
793 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
795 if self
.importIntoRemotes
:
800 self
.p4BranchesInGit
.append(branch
)
801 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
[:-1])
803 def createOrUpdateBranchesFromOrigin(self
):
805 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
807 for line
in mypopen("git rev-parse --symbolic --remotes"):
808 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
811 headName
= line
[len("origin/"):-1]
812 remoteHead
= self
.refPrefix
+ headName
813 originHead
= "origin/" + headName
815 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
816 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
820 if not gitBranchExists(remoteHead
):
822 print "creating %s" % remoteHead
825 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
826 if len(p4Change
) > 0:
827 if originPreviousDepotPath
== p4PreviousDepotPath
:
828 originP4Change
= int(originP4Change
)
829 p4Change
= int(p4Change
)
830 if originP4Change
> p4Change
:
831 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
834 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
837 system("git update-ref %s %s" % (remoteHead
, originHead
))
841 self
.changeRange
= ""
842 self
.initialParent
= ""
843 self
.previousDepotPath
= ""
844 # map from branch depot path to parent branch
845 self
.knownBranches
= {}
846 self
.initialParents
= {}
848 if self
.importIntoRemotes
:
849 self
.refPrefix
= "refs/remotes/p4/"
851 self
.refPrefix
= "refs/heads/"
853 if self
.syncWithOrigin
:
854 if gitBranchExists("origin"):
856 print "Syncing with origin first by calling git fetch origin"
857 system("git fetch origin")
859 createP4HeadRef
= False;
861 if len(self
.branch
) == 0:
862 self
.branch
= self
.refPrefix
+ "master"
863 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
864 system("git update-ref %s refs/heads/p4" % self
.branch
)
865 system("git branch -D p4");
866 # create it /after/ importing, when master exists
867 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
868 createP4HeadRef
= True
871 self
.createOrUpdateBranchesFromOrigin()
872 self
.listExistingP4GitBranches()
874 if len(self
.p4BranchesInGit
) > 1:
876 print "Importing from/into multiple branches"
877 self
.detectBranches
= True
880 print "branches: %s" % self
.p4BranchesInGit
883 for branch
in self
.p4BranchesInGit
:
884 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self
.refPrefix
+ branch
))
887 print "path %s change %s" % (depotPath
, change
)
889 if len(depotPath
) > 0 and len(change
) > 0:
890 change
= int(change
) + 1
891 p4Change
= max(p4Change
, change
)
893 if len(self
.previousDepotPath
) == 0:
894 self
.previousDepotPath
= depotPath
897 l
= min(len(self
.previousDepotPath
), len(depotPath
))
898 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
900 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
903 self
.depotPath
= self
.previousDepotPath
904 self
.changeRange
= "@%s,#head" % p4Change
905 self
.initialParent
= parseRevision(self
.branch
)
906 if not self
.silent
and not self
.detectBranches
:
907 print "Performing incremental import into %s git branch" % self
.branch
909 if not self
.branch
.startswith("refs/"):
910 self
.branch
= "refs/heads/" + self
.branch
912 if len(self
.depotPath
) != 0:
913 self
.depotPath
= self
.depotPath
[:-1]
915 if len(args
) == 0 and len(self
.depotPath
) != 0:
917 print "Depot path: %s" % self
.depotPath
921 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
922 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
924 self
.depotPath
= args
[0]
929 if self
.depotPath
.find("@") != -1:
930 atIdx
= self
.depotPath
.index("@")
931 self
.changeRange
= self
.depotPath
[atIdx
:]
932 if self
.changeRange
== "@all":
933 self
.changeRange
= ""
934 elif self
.changeRange
.find(",") == -1:
935 self
.revision
= self
.changeRange
936 self
.changeRange
= ""
937 self
.depotPath
= self
.depotPath
[0:atIdx
]
938 elif self
.depotPath
.find("#") != -1:
939 hashIdx
= self
.depotPath
.index("#")
940 self
.revision
= self
.depotPath
[hashIdx
:]
941 self
.depotPath
= self
.depotPath
[0:hashIdx
]
942 elif len(self
.previousDepotPath
) == 0:
943 self
.revision
= "#head"
945 if self
.depotPath
.endswith("..."):
946 self
.depotPath
= self
.depotPath
[:-3]
948 if not self
.depotPath
.endswith("/"):
949 self
.depotPath
+= "/"
951 self
.loadUserMapFromCache()
953 if self
.detectLabels
:
956 if self
.detectBranches
:
957 self
.getBranchMapping();
959 print "p4-git branches: %s" % self
.p4BranchesInGit
960 print "initial parents: %s" % self
.initialParents
961 for b
in self
.p4BranchesInGit
:
963 b
= b
[len(self
.projectName
):]
964 self
.createdBranches
.add(b
)
966 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
968 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
969 self
.gitOutput
= importProcess
.stdout
970 self
.gitStream
= importProcess
.stdin
971 self
.gitError
= importProcess
.stderr
973 if len(self
.revision
) > 0:
974 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
976 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
977 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
978 details
["change"] = self
.revision
982 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
983 change
= int(info
["change"])
984 if change
> newestRevision
:
985 newestRevision
= change
987 if info
["action"] == "delete":
988 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
989 #fileCnt = fileCnt + 1
992 for prop
in [ "depotFile", "rev", "action", "type" ]:
993 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
995 fileCnt
= fileCnt
+ 1
997 details
["change"] = newestRevision
1000 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
1002 print "IO error with git fast-import. Is your git version recent enough?"
1003 print self
.gitError
.read()
1008 if len(self
.changesFile
) > 0:
1009 output
= open(self
.changesFile
).readlines()
1012 changeSet
.add(int(line
))
1014 for change
in changeSet
:
1015 changes
.append(change
)
1020 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
1021 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
1024 changeNum
= line
.split(" ")[1]
1025 changes
.append(changeNum
)
1029 if len(self
.maxChanges
) > 0:
1030 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1032 if len(changes
) == 0:
1034 print "No changes to import!"
1037 self
.updatedBranches
= set()
1040 for change
in changes
:
1041 description
= p4Cmd("describe %s" % change
)
1044 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1049 if self
.detectBranches
:
1050 branches
= self
.splitFilesIntoBranches(description
)
1051 for branch
in branches
.keys():
1052 branchPrefix
= self
.depotPath
+ branch
+ "/"
1056 filesForCommit
= branches
[branch
]
1059 print "branch is %s" % branch
1061 self
.updatedBranches
.add(branch
)
1063 if branch
not in self
.createdBranches
:
1064 self
.createdBranches
.add(branch
)
1065 parent
= self
.knownBranches
[branch
]
1066 if parent
== branch
:
1069 print "parent determined through known branches: %s" % parent
1071 # main branch? use master
1072 if branch
== "main":
1075 branch
= self
.projectName
+ branch
1077 if parent
== "main":
1079 elif len(parent
) > 0:
1080 parent
= self
.projectName
+ parent
1082 branch
= self
.refPrefix
+ branch
1084 parent
= self
.refPrefix
+ parent
1087 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1089 if len(parent
) == 0 and branch
in self
.initialParents
:
1090 parent
= self
.initialParents
[branch
]
1091 del self
.initialParents
[branch
]
1093 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1095 files
= self
.extractFilesFromCommit(description
)
1096 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1097 self
.initialParent
= ""
1099 print self
.gitError
.read()
1104 if len(self
.updatedBranches
) > 0:
1105 sys
.stdout
.write("Updated branches: ")
1106 for b
in self
.updatedBranches
:
1107 sys
.stdout
.write("%s " % b
)
1108 sys
.stdout
.write("\n")
1111 self
.gitStream
.close()
1112 if importProcess
.wait() != 0:
1113 die("fast-import failed: %s" % self
.gitError
.read())
1114 self
.gitOutput
.close()
1115 self
.gitError
.close()
1118 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1122 class P4Rebase(Command
):
1124 Command
.__init
__(self
)
1126 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1128 def run(self
, args
):
1131 print "Rebasing the current branch"
1132 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1133 system("git rebase p4")
1134 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1137 class P4Clone(P4Sync
):
1139 P4Sync
.__init
__(self
)
1140 self
.description
= "Creates a new git repository and imports from Perforce into it"
1141 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1142 self
.needsGit
= False
1144 def run(self
, args
):
1156 if not depotPath
.startswith("//"):
1161 atPos
= dir.rfind("@")
1164 hashPos
= dir.rfind("#")
1166 dir = dir[0:hashPos
]
1168 if dir.endswith("..."):
1171 if dir.endswith("/"):
1174 slashPos
= dir.rfind("/")
1176 dir = dir[slashPos
+ 1:]
1178 print "Importing from %s into %s" % (depotPath
, dir)
1182 gitdir
= os
.getcwd() + "/.git"
1183 if not P4Sync
.run(self
, [depotPath
]):
1185 if self
.branch
!= "master":
1186 if gitBranchExists("refs/remotes/p4/master"):
1187 system("git branch master refs/remotes/p4/master")
1188 system("git checkout -f")
1190 print "Could not detect main branch. No checkout/master branch created."
1193 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1195 optparse
.IndentedHelpFormatter
.__init
__(self
)
1197 def format_description(self
, description
):
1199 return description
+ "\n"
1203 def printUsage(commands
):
1204 print "usage: %s <command> [options]" % sys
.argv
[0]
1206 print "valid commands: %s" % ", ".join(commands
)
1208 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1212 "debug" : P4Debug(),
1213 "submit" : P4Submit(),
1215 "rebase" : P4Rebase(),
1216 "clone" : P4Clone(),
1217 "rollback" : P4RollBack()
1220 if len(sys
.argv
[1:]) == 0:
1221 printUsage(commands
.keys())
1225 cmdName
= sys
.argv
[1]
1227 cmd
= commands
[cmdName
]
1229 print "unknown command %s" % cmdName
1231 printUsage(commands
.keys())
1234 options
= cmd
.options
1239 if len(options
) > 0:
1240 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1242 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1244 description
= cmd
.description
,
1245 formatter
= HelpFormatter())
1247 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1251 if len(gitdir
) == 0:
1253 if not isValidGitDir(gitdir
):
1254 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1255 if os
.path
.exists(gitdir
):
1256 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1260 if not isValidGitDir(gitdir
):
1261 if isValidGitDir(gitdir
+ "/.git"):
1264 die("fatal: cannot locate git repository at %s" % gitdir
)
1266 os
.environ
["GIT_DIR"] = gitdir
1268 if not cmd
.run(args
):