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("--dry-run", action
="store_true"),
199 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
200 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", 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
212 self
.trustMeLikeAFool
= False
214 self
.logSubstitutions
= {}
215 self
.logSubstitutions
["<enter description here>"] = "%log%"
216 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
219 if len(p4CmdList("opened ...")) > 0:
220 die("You have files opened with perforce! Close them before starting the sync.")
223 if len(self
.config
) > 0 and not self
.reset
:
224 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
)
227 if self
.directSubmit
:
230 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
231 commits
.append(line
[:-1])
234 self
.config
["commits"] = commits
236 def prepareLogMessage(self
, template
, message
):
239 for line
in template
.split("\n"):
240 if line
.startswith("#"):
241 result
+= line
+ "\n"
245 for key
in self
.logSubstitutions
.keys():
246 if line
.find(key
) != -1:
247 value
= self
.logSubstitutions
[key
]
248 value
= value
.replace("%log%", message
)
249 if value
!= "@remove@":
250 result
+= line
.replace(key
, value
) + "\n"
255 result
+= line
+ "\n"
260 if self
.directSubmit
:
261 print "Applying local change in working directory/index"
262 diff
= self
.diffStatus
264 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
265 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
267 filesToDelete
= set()
271 path
= line
[1:].strip()
273 system("p4 edit \"%s\"" % path
)
274 editedFiles
.add(path
)
275 elif modifier
== "A":
277 if path
in filesToDelete
:
278 filesToDelete
.remove(path
)
279 elif modifier
== "D":
280 filesToDelete
.add(path
)
281 if path
in filesToAdd
:
282 filesToAdd
.remove(path
)
284 die("unknown modifier %s for %s" % (modifier
, path
))
286 if self
.directSubmit
:
287 diffcmd
= "cat \"%s\"" % self
.diffFile
289 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
290 patchcmd
= diffcmd
+ " | git apply "
291 tryPatchCmd
= patchcmd
+ "--check -"
292 applyPatchCmd
= patchcmd
+ "--check --apply -"
294 if os
.system(tryPatchCmd
) != 0:
295 print "Unfortunately applying the change failed!"
296 print "What do you want to do?"
298 while response
!= "s" and response
!= "a" and response
!= "w":
299 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) ")
301 print "Skipping! Good luck with the next patches..."
303 elif response
== "a":
304 os
.system(applyPatchCmd
)
305 if len(filesToAdd
) > 0:
306 print "You may also want to call p4 add on the following files:"
307 print " ".join(filesToAdd
)
308 if len(filesToDelete
):
309 print "The following files should be scheduled for deletion with p4 delete:"
310 print " ".join(filesToDelete
)
311 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
312 elif response
== "w":
313 system(diffcmd
+ " > patch.txt")
314 print "Patch saved to patch.txt in %s !" % self
.clientPath
315 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
317 system(applyPatchCmd
)
320 system("p4 add %s" % f
)
321 for f
in filesToDelete
:
322 system("p4 revert %s" % f
)
323 system("p4 delete %s" % f
)
326 if not self
.directSubmit
:
327 logMessage
= extractLogMessageFromGitCommit(id)
328 logMessage
= logMessage
.replace("\n", "\n\t")
329 logMessage
= logMessage
[:-1]
331 template
= mypopen("p4 change -o").read()
334 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
335 diff
= mypopen("p4 diff -du ...").read()
337 for newFile
in filesToAdd
:
338 diff
+= "==== new file ====\n"
339 diff
+= "--- /dev/null\n"
340 diff
+= "+++ %s\n" % newFile
341 f
= open(newFile
, "r")
342 for line
in f
.readlines():
346 separatorLine
= "######## everything below this line is just the diff #######"
347 if platform
.system() == "Windows":
348 separatorLine
+= "\r"
349 separatorLine
+= "\n"
352 if self
.trustMeLikeAFool
:
355 firstIteration
= True
356 while response
== "e":
357 if not firstIteration
:
358 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
359 firstIteration
= False
361 [handle
, fileName
] = tempfile
.mkstemp()
362 tmpFile
= os
.fdopen(handle
, "w+")
363 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
366 if platform
.system() == "Windows":
367 defaultEditor
= "notepad"
368 editor
= os
.environ
.get("EDITOR", defaultEditor
);
369 system(editor
+ " " + fileName
)
370 tmpFile
= open(fileName
, "rb")
371 message
= tmpFile
.read()
374 submitTemplate
= message
[:message
.index(separatorLine
)]
376 if response
== "y" or response
== "yes":
379 raw_input("Press return to continue...")
381 if self
.directSubmit
:
382 print "Submitting to git first"
383 os
.chdir(self
.oldWorkingDirectory
)
384 pipe
= os
.popen("git commit -a -F -", "wb")
385 pipe
.write(submitTemplate
)
387 os
.chdir(self
.clientPath
)
389 pipe
= os
.popen("p4 submit -i", "wb")
390 pipe
.write(submitTemplate
)
392 elif response
== "s":
393 for f
in editedFiles
:
394 system("p4 revert \"%s\"" % f
);
396 system("p4 revert \"%s\"" % f
);
398 for f
in filesToDelete
:
399 system("p4 delete \"%s\"" % f
);
402 print "Not submitting!"
403 self
.interactive
= False
405 fileName
= "submit.txt"
406 file = open(fileName
, "w+")
407 file.write(self
.prepareLogMessage(template
, logMessage
))
409 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
413 # make gitdir absolute so we can cd out into the perforce checkout
414 gitdir
= os
.path
.abspath(gitdir
)
415 os
.environ
["GIT_DIR"] = gitdir
418 self
.master
= currentGitBranch()
419 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
420 die("Detecting current git branch failed!")
422 self
.master
= args
[0]
427 if gitBranchExists("p4"):
428 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
429 if len(depotPath
) == 0 and gitBranchExists("origin"):
430 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
432 if len(depotPath
) == 0:
433 print "Internal error: cannot locate perforce depot path from existing branches"
436 self
.clientPath
= p4Where(depotPath
)
438 if len(self
.clientPath
) == 0:
439 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
442 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
443 self
.oldWorkingDirectory
= os
.getcwd()
445 if self
.directSubmit
:
446 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
447 if len(self
.diffStatus
) == 0:
448 print "No changes in working directory to submit."
450 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
451 self
.diffFile
= gitdir
+ "/p4-git-diff"
452 f
= open(self
.diffFile
, "wb")
456 os
.chdir(self
.clientPath
)
457 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
458 if response
== "y" or response
== "yes":
459 system("p4 sync ...")
461 if len(self
.origin
) == 0:
462 if gitBranchExists("p4"):
465 self
.origin
= "origin"
468 self
.firstTime
= True
470 if len(self
.substFile
) > 0:
471 for line
in open(self
.substFile
, "r").readlines():
472 tokens
= line
[:-1].split("=")
473 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
476 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
477 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
482 commits
= self
.config
.get("commits", [])
484 while len(commits
) > 0:
485 self
.firstTime
= False
487 commits
= commits
[1:]
488 self
.config
["commits"] = commits
490 if not self
.interactive
:
495 if self
.directSubmit
:
496 os
.remove(self
.diffFile
)
498 if len(commits
) == 0:
500 print "No changes found to apply between %s and current HEAD" % self
.origin
502 print "All changes applied!"
503 os
.chdir(self
.oldWorkingDirectory
)
504 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
505 if response
== "y" or response
== "yes":
508 os
.remove(self
.configFile
)
512 class P4Sync(Command
):
514 Command
.__init
__(self
)
516 optparse
.make_option("--branch", dest
="branch"),
517 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
518 optparse
.make_option("--changesfile", dest
="changesFile"),
519 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
520 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
521 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
522 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
523 optparse
.make_option("--max-changes", dest
="maxChanges")
525 self
.description
= """Imports from Perforce into a git repository.\n
527 //depot/my/project/ -- to import the current head
528 //depot/my/project/@all -- to import everything
529 //depot/my/project/@1,6 -- to import only from revision 1 to 6
531 (a ... is not needed in the path p4 specification, it's added implicitly)"""
533 self
.usage
+= " //depot/path[@revRange]"
536 self
.createdBranches
= Set()
537 self
.committedChanges
= Set()
539 self
.detectBranches
= False
540 self
.detectLabels
= False
541 self
.changesFile
= ""
542 self
.syncWithOrigin
= True
544 self
.importIntoRemotes
= True
546 self
.isWindows
= (platform
.system() == "Windows")
548 if gitConfig("git-p4.syncFromOrigin") == "false":
549 self
.syncWithOrigin
= False
551 def p4File(self
, depotPath
):
552 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
554 def extractFilesFromCommit(self
, commit
):
557 while commit
.has_key("depotFile%s" % fnum
):
558 path
= commit
["depotFile%s" % fnum
]
559 if not path
.startswith(self
.depotPath
):
560 # if not self.silent:
561 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
567 file["rev"] = commit
["rev%s" % fnum
]
568 file["action"] = commit
["action%s" % fnum
]
569 file["type"] = commit
["type%s" % fnum
]
574 def splitFilesIntoBranches(self
, commit
):
578 while commit
.has_key("depotFile%s" % fnum
):
579 path
= commit
["depotFile%s" % fnum
]
580 if not path
.startswith(self
.depotPath
):
581 # if not self.silent:
582 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
588 file["rev"] = commit
["rev%s" % fnum
]
589 file["action"] = commit
["action%s" % fnum
]
590 file["type"] = commit
["type%s" % fnum
]
593 relPath
= path
[len(self
.depotPath
):]
595 for branch
in self
.knownBranches
.keys():
596 if relPath
.startswith(branch
+ "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
597 if branch
not in branches
:
598 branches
[branch
] = []
599 branches
[branch
].append(file)
603 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
604 epoch
= details
["time"]
605 author
= details
["user"]
608 print "commit into %s" % branch
610 self
.gitStream
.write("commit %s\n" % branch
)
611 # gitStream.write("mark :%s\n" % details["change"])
612 self
.committedChanges
.add(int(details
["change"]))
614 if author
not in self
.users
:
615 self
.getUserMapFromPerforceServer()
616 if author
in self
.users
:
617 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
619 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
621 self
.gitStream
.write("committer %s\n" % committer
)
623 self
.gitStream
.write("data <<EOT\n")
624 self
.gitStream
.write(details
["desc"])
625 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
626 self
.gitStream
.write("EOT\n\n")
630 print "parent %s" % parent
631 self
.gitStream
.write("from %s\n" % parent
)
635 if not path
.startswith(branchPrefix
):
637 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
640 depotPath
= path
+ "#" + rev
641 relPath
= path
[len(branchPrefix
):]
642 action
= file["action"]
644 if file["type"] == "apple":
645 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
648 if action
== "delete":
649 self
.gitStream
.write("D %s\n" % relPath
)
652 if file["type"].startswith("x"):
655 data
= self
.p4File(depotPath
)
657 if self
.isWindows
and file["type"].endswith("text"):
658 data
= data
.replace("\r\n", "\n")
660 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
661 self
.gitStream
.write("data %s\n" % len(data
))
662 self
.gitStream
.write(data
)
663 self
.gitStream
.write("\n")
665 self
.gitStream
.write("\n")
667 change
= int(details
["change"])
669 if self
.labels
.has_key(change
):
670 label
= self
.labels
[change
]
671 labelDetails
= label
[0]
672 labelRevisions
= label
[1]
674 print "Change %s is labelled %s" % (change
, labelDetails
)
676 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
678 if len(files
) == len(labelRevisions
):
682 if info
["action"] == "delete":
684 cleanedFiles
[info
["depotFile"]] = info
["rev"]
686 if cleanedFiles
== labelRevisions
:
687 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
688 self
.gitStream
.write("from %s\n" % branch
)
690 owner
= labelDetails
["Owner"]
692 if author
in self
.users
:
693 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
695 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
696 self
.gitStream
.write("tagger %s\n" % tagger
)
697 self
.gitStream
.write("data <<EOT\n")
698 self
.gitStream
.write(labelDetails
["Description"])
699 self
.gitStream
.write("EOT\n\n")
703 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
707 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
709 def getUserMapFromPerforceServer(self
):
710 if self
.userMapFromPerforceServer
:
714 for output
in p4CmdList("users"):
715 if not output
.has_key("User"):
717 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
719 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
720 for user
in self
.users
.keys():
721 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
723 self
.userMapFromPerforceServer
= True
725 def loadUserMapFromCache(self
):
727 self
.userMapFromPerforceServer
= False
729 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
730 lines
= cache
.readlines()
733 entry
= line
[:-1].split("\t")
734 self
.users
[entry
[0]] = entry
[1]
736 self
.getUserMapFromPerforceServer()
741 l
= p4CmdList("labels %s..." % self
.depotPath
)
742 if len(l
) > 0 and not self
.silent
:
743 print "Finding files belonging to labels in %s" % self
.depotPath
746 label
= output
["label"]
750 print "Querying files for label %s" % label
751 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
752 revisions
[file["depotFile"]] = file["rev"]
753 change
= int(file["change"])
754 if change
> newestChange
:
755 newestChange
= change
757 self
.labels
[newestChange
] = [output
, revisions
]
760 print "Label changes: %s" % self
.labels
.keys()
762 def getBranchMapping(self
):
763 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
765 for info
in p4CmdList("branches"):
766 details
= p4Cmd("branch -o %s" % info
["branch"])
768 while details
.has_key("View%s" % viewIdx
):
769 paths
= details
["View%s" % viewIdx
].split(" ")
770 viewIdx
= viewIdx
+ 1
771 # require standard //depot/foo/... //depot/bar/... mapping
772 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
775 destination
= paths
[1]
776 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
777 source
= source
[len(self
.depotPath
):-4]
778 destination
= destination
[len(self
.depotPath
):-4]
779 if destination
not in self
.knownBranches
:
780 self
.knownBranches
[destination
] = source
781 if source
not in self
.knownBranches
:
782 self
.knownBranches
[source
] = source
784 def listExistingP4GitBranches(self
):
785 self
.p4BranchesInGit
= []
787 cmdline
= "git rev-parse --symbolic "
788 if self
.importIntoRemotes
:
789 cmdline
+= " --remotes"
791 cmdline
+= " --branches"
793 for line
in mypopen(cmdline
).readlines():
794 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
796 if self
.importIntoRemotes
:
801 self
.p4BranchesInGit
.append(branch
)
802 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
[:-1])
804 def createOrUpdateBranchesFromOrigin(self
):
806 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
808 for line
in mypopen("git rev-parse --symbolic --remotes"):
809 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
812 headName
= line
[len("origin/"):-1]
813 remoteHead
= self
.refPrefix
+ headName
814 originHead
= "origin/" + headName
816 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
817 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
821 if not gitBranchExists(remoteHead
):
823 print "creating %s" % remoteHead
826 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
827 if len(p4Change
) > 0:
828 if originPreviousDepotPath
== p4PreviousDepotPath
:
829 originP4Change
= int(originP4Change
)
830 p4Change
= int(p4Change
)
831 if originP4Change
> p4Change
:
832 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
835 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
838 system("git update-ref %s %s" % (remoteHead
, originHead
))
842 self
.changeRange
= ""
843 self
.initialParent
= ""
844 self
.previousDepotPath
= ""
845 # map from branch depot path to parent branch
846 self
.knownBranches
= {}
847 self
.initialParents
= {}
848 self
.hasOrigin
= gitBranchExists("origin")
850 if self
.importIntoRemotes
:
851 self
.refPrefix
= "refs/remotes/p4/"
853 self
.refPrefix
= "refs/heads/"
855 if self
.syncWithOrigin
:
858 print "Syncing with origin first by calling git fetch origin"
859 system("git fetch origin")
861 createP4HeadRef
= False;
863 if len(self
.branch
) == 0:
864 self
.branch
= self
.refPrefix
+ "master"
865 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
866 system("git update-ref %s refs/heads/p4" % self
.branch
)
867 system("git branch -D p4");
868 # create it /after/ importing, when master exists
869 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
870 createP4HeadRef
= True
874 self
.createOrUpdateBranchesFromOrigin()
875 self
.listExistingP4GitBranches()
877 if len(self
.p4BranchesInGit
) > 1:
879 print "Importing from/into multiple branches"
880 self
.detectBranches
= True
883 print "branches: %s" % self
.p4BranchesInGit
886 for branch
in self
.p4BranchesInGit
:
887 depotPath
, change
= extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(self
.refPrefix
+ branch
))
890 print "path %s change %s" % (depotPath
, change
)
892 if len(depotPath
) > 0 and len(change
) > 0:
893 change
= int(change
) + 1
894 p4Change
= max(p4Change
, change
)
896 if len(self
.previousDepotPath
) == 0:
897 self
.previousDepotPath
= depotPath
900 l
= min(len(self
.previousDepotPath
), len(depotPath
))
901 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
903 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
906 self
.depotPath
= self
.previousDepotPath
907 self
.changeRange
= "@%s,#head" % p4Change
908 self
.initialParent
= parseRevision(self
.branch
)
909 if not self
.silent
and not self
.detectBranches
:
910 print "Performing incremental import into %s git branch" % self
.branch
912 if not self
.branch
.startswith("refs/"):
913 self
.branch
= "refs/heads/" + self
.branch
915 if len(self
.depotPath
) != 0:
916 self
.depotPath
= self
.depotPath
[:-1]
918 if len(args
) == 0 and len(self
.depotPath
) != 0:
920 print "Depot path: %s" % self
.depotPath
924 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
925 print "previous import used depot path %s and now %s was specified. this doesn't work!" % (self
.depotPath
, args
[0])
927 self
.depotPath
= args
[0]
932 if self
.depotPath
.find("@") != -1:
933 atIdx
= self
.depotPath
.index("@")
934 self
.changeRange
= self
.depotPath
[atIdx
:]
935 if self
.changeRange
== "@all":
936 self
.changeRange
= ""
937 elif self
.changeRange
.find(",") == -1:
938 self
.revision
= self
.changeRange
939 self
.changeRange
= ""
940 self
.depotPath
= self
.depotPath
[0:atIdx
]
941 elif self
.depotPath
.find("#") != -1:
942 hashIdx
= self
.depotPath
.index("#")
943 self
.revision
= self
.depotPath
[hashIdx
:]
944 self
.depotPath
= self
.depotPath
[0:hashIdx
]
945 elif len(self
.previousDepotPath
) == 0:
946 self
.revision
= "#head"
948 if self
.depotPath
.endswith("..."):
949 self
.depotPath
= self
.depotPath
[:-3]
951 if not self
.depotPath
.endswith("/"):
952 self
.depotPath
+= "/"
954 self
.loadUserMapFromCache()
956 if self
.detectLabels
:
959 if self
.detectBranches
:
960 self
.getBranchMapping();
962 print "p4-git branches: %s" % self
.p4BranchesInGit
963 print "initial parents: %s" % self
.initialParents
964 for b
in self
.p4BranchesInGit
:
966 b
= b
[len(self
.projectName
):]
967 self
.createdBranches
.add(b
)
969 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
971 importProcess
= subprocess
.Popen(["git", "fast-import"], stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
972 self
.gitOutput
= importProcess
.stdout
973 self
.gitStream
= importProcess
.stdin
974 self
.gitError
= importProcess
.stderr
976 if len(self
.revision
) > 0:
977 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
979 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
980 details
["desc"] = "Initial import of %s from the state at revision %s" % (self
.depotPath
, self
.revision
)
981 details
["change"] = self
.revision
985 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
986 change
= int(info
["change"])
987 if change
> newestRevision
:
988 newestRevision
= change
990 if info
["action"] == "delete":
991 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
992 #fileCnt = fileCnt + 1
995 for prop
in [ "depotFile", "rev", "action", "type" ]:
996 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
998 fileCnt
= fileCnt
+ 1
1000 details
["change"] = newestRevision
1003 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
1005 print "IO error with git fast-import. Is your git version recent enough?"
1006 print self
.gitError
.read()
1011 if len(self
.changesFile
) > 0:
1012 output
= open(self
.changesFile
).readlines()
1015 changeSet
.add(int(line
))
1017 for change
in changeSet
:
1018 changes
.append(change
)
1023 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
1024 output
= mypopen("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
)).readlines()
1027 changeNum
= line
.split(" ")[1]
1028 changes
.append(changeNum
)
1032 if len(self
.maxChanges
) > 0:
1033 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1035 if len(changes
) == 0:
1037 print "No changes to import!"
1040 self
.updatedBranches
= set()
1043 for change
in changes
:
1044 description
= p4Cmd("describe %s" % change
)
1047 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1052 if self
.detectBranches
:
1053 branches
= self
.splitFilesIntoBranches(description
)
1054 for branch
in branches
.keys():
1055 branchPrefix
= self
.depotPath
+ branch
+ "/"
1059 filesForCommit
= branches
[branch
]
1062 print "branch is %s" % branch
1064 self
.updatedBranches
.add(branch
)
1066 if branch
not in self
.createdBranches
:
1067 self
.createdBranches
.add(branch
)
1068 parent
= self
.knownBranches
[branch
]
1069 if parent
== branch
:
1072 print "parent determined through known branches: %s" % parent
1074 # main branch? use master
1075 if branch
== "main":
1078 branch
= self
.projectName
+ branch
1080 if parent
== "main":
1082 elif len(parent
) > 0:
1083 parent
= self
.projectName
+ parent
1085 branch
= self
.refPrefix
+ branch
1087 parent
= self
.refPrefix
+ parent
1090 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1092 if len(parent
) == 0 and branch
in self
.initialParents
:
1093 parent
= self
.initialParents
[branch
]
1094 del self
.initialParents
[branch
]
1096 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1098 files
= self
.extractFilesFromCommit(description
)
1099 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1100 self
.initialParent
= ""
1102 print self
.gitError
.read()
1107 if len(self
.updatedBranches
) > 0:
1108 sys
.stdout
.write("Updated branches: ")
1109 for b
in self
.updatedBranches
:
1110 sys
.stdout
.write("%s " % b
)
1111 sys
.stdout
.write("\n")
1114 self
.gitStream
.close()
1115 if importProcess
.wait() != 0:
1116 die("fast-import failed: %s" % self
.gitError
.read())
1117 self
.gitOutput
.close()
1118 self
.gitError
.close()
1121 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1125 class P4Rebase(Command
):
1127 Command
.__init
__(self
)
1129 self
.description
= "Fetches the latest revision from perforce and rebases the current work (branch) against it"
1131 def run(self
, args
):
1134 print "Rebasing the current branch"
1135 oldHead
= mypopen("git rev-parse HEAD").read()[:-1]
1136 system("git rebase p4")
1137 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1140 class P4Clone(P4Sync
):
1142 P4Sync
.__init
__(self
)
1143 self
.description
= "Creates a new git repository and imports from Perforce into it"
1144 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1145 self
.needsGit
= False
1147 def run(self
, args
):
1159 if not depotPath
.startswith("//"):
1164 atPos
= dir.rfind("@")
1167 hashPos
= dir.rfind("#")
1169 dir = dir[0:hashPos
]
1171 if dir.endswith("..."):
1174 if dir.endswith("/"):
1177 slashPos
= dir.rfind("/")
1179 dir = dir[slashPos
+ 1:]
1181 print "Importing from %s into %s" % (depotPath
, dir)
1185 gitdir
= os
.getcwd() + "/.git"
1186 if not P4Sync
.run(self
, [depotPath
]):
1188 if self
.branch
!= "master":
1189 if gitBranchExists("refs/remotes/p4/master"):
1190 system("git branch master refs/remotes/p4/master")
1191 system("git checkout -f")
1193 print "Could not detect main branch. No checkout/master branch created."
1196 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1198 optparse
.IndentedHelpFormatter
.__init
__(self
)
1200 def format_description(self
, description
):
1202 return description
+ "\n"
1206 def printUsage(commands
):
1207 print "usage: %s <command> [options]" % sys
.argv
[0]
1209 print "valid commands: %s" % ", ".join(commands
)
1211 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1215 "debug" : P4Debug(),
1216 "submit" : P4Submit(),
1218 "rebase" : P4Rebase(),
1219 "clone" : P4Clone(),
1220 "rollback" : P4RollBack()
1223 if len(sys
.argv
[1:]) == 0:
1224 printUsage(commands
.keys())
1228 cmdName
= sys
.argv
[1]
1230 cmd
= commands
[cmdName
]
1232 print "unknown command %s" % cmdName
1234 printUsage(commands
.keys())
1237 options
= cmd
.options
1242 if len(options
) > 0:
1243 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1245 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1247 description
= cmd
.description
,
1248 formatter
= HelpFormatter())
1250 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1254 if len(gitdir
) == 0:
1256 if not isValidGitDir(gitdir
):
1257 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1258 if os
.path
.exists(gitdir
):
1259 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1263 if not isValidGitDir(gitdir
):
1264 if isValidGitDir(gitdir
+ "/.git"):
1267 die("fatal: cannot locate git repository at %s" % gitdir
)
1269 os
.environ
["GIT_DIR"] = gitdir
1271 if not cmd
.run(args
):