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
16 gitdir
= os
.environ
.get("GIT_DIR", "")
19 return os
.popen(command
, "rb");
22 cmd
= "p4 -G %s" % cmd
23 pipe
= os
.popen(cmd
, "rb")
28 entry
= marshal
.load(pipe
)
32 exitCode
= pipe
.close()
35 entry
["p4ExitCode"] = exitCode
47 def p4Where(depotPath
):
48 if not depotPath
.endswith("/"):
50 output
= p4Cmd("where %s..." % depotPath
)
51 if output
["code"] == "error":
55 clientPath
= output
.get("path")
56 elif "data" in output
:
57 data
= output
.get("data")
58 lastSpace
= data
.rfind(" ")
59 clientPath
= data
[lastSpace
+ 1:]
61 if clientPath
.endswith("..."):
62 clientPath
= clientPath
[:-3]
66 sys
.stderr
.write(msg
+ "\n")
69 def currentGitBranch():
70 return mypopen("git name-rev HEAD").read().split(" ")[1][:-1]
72 def isValidGitDir(path
):
73 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
77 def parseRevision(ref
):
78 return mypopen("git rev-parse %s" % ref
).read()[:-1]
81 if os
.system(cmd
) != 0:
82 die("command failed: %s" % cmd
)
84 def extractLogMessageFromGitCommit(commit
):
87 for log
in mypopen("git cat-file commit %s" % commit
).readlines():
96 def extractDepotPathAndChangeFromGitLog(log
):
98 for line
in log
.split("\n"):
100 if line
.startswith("[git-p4:") and line
.endswith("]"):
101 line
= line
[8:-1].strip()
102 for assignment
in line
.split(":"):
103 variable
= assignment
.strip()
105 equalPos
= assignment
.find("=")
107 variable
= assignment
[:equalPos
].strip()
108 value
= assignment
[equalPos
+ 1:].strip()
109 if value
.startswith("\"") and value
.endswith("\""):
111 values
[variable
] = value
113 return values
.get("depot-path"), values
.get("change")
115 def gitBranchExists(branch
):
116 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
117 return proc
.wait() == 0;
120 return mypopen("git config %s" % key
).read()[:-1]
124 self
.usage
= "usage: %prog [options]"
127 class P4Debug(Command
):
129 Command
.__init
__(self
)
132 self
.description
= "A tool to debug the output of p4 -G."
133 self
.needsGit
= False
136 for output
in p4CmdList(" ".join(args
)):
140 class P4RollBack(Command
):
142 Command
.__init
__(self
)
144 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
145 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
147 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
149 self
.rollbackLocalBranches
= False
154 maxChange
= int(args
[0])
156 if "p4ExitCode" in p4Cmd("changes -m 1"):
157 die("Problems executing p4");
159 if self
.rollbackLocalBranches
:
160 refPrefix
= "refs/heads/"
161 lines
= mypopen("git rev-parse --symbolic --branches").readlines()
163 refPrefix
= "refs/remotes/"
164 lines
= mypopen("git rev-parse --symbolic --remotes").readlines()
167 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
168 ref
= refPrefix
+ line
[:-1]
169 log
= extractLogMessageFromGitCommit(ref
)
170 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
173 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath
, maxChange
))) == 0:
174 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
175 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
178 while len(change
) > 0 and int(change
) > maxChange
:
181 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
182 system("git update-ref %s \"%s^\"" % (ref
, ref
))
183 log
= extractLogMessageFromGitCommit(ref
)
184 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
187 print "%s rewound to %s" % (ref
, change
)
191 class P4Submit(Command
):
193 Command
.__init
__(self
)
195 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
196 optparse
.make_option("--origin", dest
="origin"),
197 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
198 optparse
.make_option("--log-substitutions", dest
="substFile"),
199 optparse
.make_option("--dry-run", action
="store_true"),
200 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
201 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
203 self
.description
= "Submit changes from git to the perforce depot."
204 self
.usage
+= " [name of git branch to submit into perforce depot]"
205 self
.firstTime
= True
207 self
.interactive
= True
210 self
.firstTime
= True
212 self
.directSubmit
= False
213 self
.trustMeLikeAFool
= False
215 self
.logSubstitutions
= {}
216 self
.logSubstitutions
["<enter description here>"] = "%log%"
217 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
220 if len(p4CmdList("opened ...")) > 0:
221 die("You have files opened with perforce! Close them before starting the sync.")
224 if len(self
.config
) > 0 and not self
.reset
:
225 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
)
228 if self
.directSubmit
:
231 for line
in mypopen("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)).readlines():
232 commits
.append(line
[:-1])
235 self
.config
["commits"] = commits
237 def prepareLogMessage(self
, template
, message
):
240 for line
in template
.split("\n"):
241 if line
.startswith("#"):
242 result
+= line
+ "\n"
246 for key
in self
.logSubstitutions
.keys():
247 if line
.find(key
) != -1:
248 value
= self
.logSubstitutions
[key
]
249 value
= value
.replace("%log%", message
)
250 if value
!= "@remove@":
251 result
+= line
.replace(key
, value
) + "\n"
256 result
+= line
+ "\n"
261 if self
.directSubmit
:
262 print "Applying local change in working directory/index"
263 diff
= self
.diffStatus
265 print "Applying %s" % (mypopen("git log --max-count=1 --pretty=oneline %s" % id).read())
266 diff
= mypopen("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id)).readlines()
268 filesToDelete
= set()
272 path
= line
[1:].strip()
274 system("p4 edit \"%s\"" % path
)
275 editedFiles
.add(path
)
276 elif modifier
== "A":
278 if path
in filesToDelete
:
279 filesToDelete
.remove(path
)
280 elif modifier
== "D":
281 filesToDelete
.add(path
)
282 if path
in filesToAdd
:
283 filesToAdd
.remove(path
)
285 die("unknown modifier %s for %s" % (modifier
, path
))
287 if self
.directSubmit
:
288 diffcmd
= "cat \"%s\"" % self
.diffFile
290 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
291 patchcmd
= diffcmd
+ " | git apply "
292 tryPatchCmd
= patchcmd
+ "--check -"
293 applyPatchCmd
= patchcmd
+ "--check --apply -"
295 if os
.system(tryPatchCmd
) != 0:
296 print "Unfortunately applying the change failed!"
297 print "What do you want to do?"
299 while response
!= "s" and response
!= "a" and response
!= "w":
300 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) ")
302 print "Skipping! Good luck with the next patches..."
304 elif response
== "a":
305 os
.system(applyPatchCmd
)
306 if len(filesToAdd
) > 0:
307 print "You may also want to call p4 add on the following files:"
308 print " ".join(filesToAdd
)
309 if len(filesToDelete
):
310 print "The following files should be scheduled for deletion with p4 delete:"
311 print " ".join(filesToDelete
)
312 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
313 elif response
== "w":
314 system(diffcmd
+ " > patch.txt")
315 print "Patch saved to patch.txt in %s !" % self
.clientPath
316 die("Please resolve and submit the conflict manually and continue afterwards with git-p4 submit --continue")
318 system(applyPatchCmd
)
321 system("p4 add %s" % f
)
322 for f
in filesToDelete
:
323 system("p4 revert %s" % f
)
324 system("p4 delete %s" % f
)
327 if not self
.directSubmit
:
328 logMessage
= extractLogMessageFromGitCommit(id)
329 logMessage
= logMessage
.replace("\n", "\n\t")
330 logMessage
= logMessage
[:-1]
332 template
= mypopen("p4 change -o").read()
335 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
336 diff
= mypopen("p4 diff -du ...").read()
338 for newFile
in filesToAdd
:
339 diff
+= "==== new file ====\n"
340 diff
+= "--- /dev/null\n"
341 diff
+= "+++ %s\n" % newFile
342 f
= open(newFile
, "r")
343 for line
in f
.readlines():
347 separatorLine
= "######## everything below this line is just the diff #######"
348 if platform
.system() == "Windows":
349 separatorLine
+= "\r"
350 separatorLine
+= "\n"
353 if self
.trustMeLikeAFool
:
356 firstIteration
= True
357 while response
== "e":
358 if not firstIteration
:
359 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
360 firstIteration
= False
362 [handle
, fileName
] = tempfile
.mkstemp()
363 tmpFile
= os
.fdopen(handle
, "w+")
364 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
367 if platform
.system() == "Windows":
368 defaultEditor
= "notepad"
369 editor
= os
.environ
.get("EDITOR", defaultEditor
);
370 system(editor
+ " " + fileName
)
371 tmpFile
= open(fileName
, "rb")
372 message
= tmpFile
.read()
375 submitTemplate
= message
[:message
.index(separatorLine
)]
377 if response
== "y" or response
== "yes":
380 raw_input("Press return to continue...")
382 if self
.directSubmit
:
383 print "Submitting to git first"
384 os
.chdir(self
.oldWorkingDirectory
)
385 pipe
= os
.popen("git commit -a -F -", "wb")
386 pipe
.write(submitTemplate
)
388 os
.chdir(self
.clientPath
)
390 pipe
= os
.popen("p4 submit -i", "wb")
391 pipe
.write(submitTemplate
)
393 elif response
== "s":
394 for f
in editedFiles
:
395 system("p4 revert \"%s\"" % f
);
397 system("p4 revert \"%s\"" % f
);
399 for f
in filesToDelete
:
400 system("p4 delete \"%s\"" % f
);
403 print "Not submitting!"
404 self
.interactive
= False
406 fileName
= "submit.txt"
407 file = open(fileName
, "w+")
408 file.write(self
.prepareLogMessage(template
, logMessage
))
410 print "Perforce submit template written as %s. Please review/edit and then use p4 submit -i < %s to submit directly!" % (fileName
, fileName
)
414 # make gitdir absolute so we can cd out into the perforce checkout
415 gitdir
= os
.path
.abspath(gitdir
)
416 os
.environ
["GIT_DIR"] = gitdir
419 self
.master
= currentGitBranch()
420 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
421 die("Detecting current git branch failed!")
423 self
.master
= args
[0]
428 if gitBranchExists("p4"):
429 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
430 if len(depotPath
) == 0 and gitBranchExists("origin"):
431 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
433 if len(depotPath
) == 0:
434 print "Internal error: cannot locate perforce depot path from existing branches"
437 self
.clientPath
= p4Where(depotPath
)
439 if len(self
.clientPath
) == 0:
440 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
443 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
444 self
.oldWorkingDirectory
= os
.getcwd()
446 if self
.directSubmit
:
447 self
.diffStatus
= mypopen("git diff -r --name-status HEAD").readlines()
448 if len(self
.diffStatus
) == 0:
449 print "No changes in working directory to submit."
451 patch
= mypopen("git diff -p --binary --diff-filter=ACMRTUXB HEAD").read()
452 self
.diffFile
= gitdir
+ "/p4-git-diff"
453 f
= open(self
.diffFile
, "wb")
457 os
.chdir(self
.clientPath
)
458 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
459 if response
== "y" or response
== "yes":
460 system("p4 sync ...")
462 if len(self
.origin
) == 0:
463 if gitBranchExists("p4"):
466 self
.origin
= "origin"
469 self
.firstTime
= True
471 if len(self
.substFile
) > 0:
472 for line
in open(self
.substFile
, "r").readlines():
473 tokens
= line
[:-1].split("=")
474 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
477 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
478 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
483 commits
= self
.config
.get("commits", [])
485 while len(commits
) > 0:
486 self
.firstTime
= False
488 commits
= commits
[1:]
489 self
.config
["commits"] = commits
491 if not self
.interactive
:
496 if self
.directSubmit
:
497 os
.remove(self
.diffFile
)
499 if len(commits
) == 0:
501 print "No changes found to apply between %s and current HEAD" % self
.origin
503 print "All changes applied!"
504 os
.chdir(self
.oldWorkingDirectory
)
505 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
506 if response
== "y" or response
== "yes":
509 os
.remove(self
.configFile
)
513 class P4Sync(Command
):
515 Command
.__init
__(self
)
517 optparse
.make_option("--branch", dest
="branch"),
518 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
519 optparse
.make_option("--changesfile", dest
="changesFile"),
520 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
521 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
522 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
523 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
524 optparse
.make_option("--max-changes", dest
="maxChanges")
526 self
.description
= """Imports from Perforce into a git repository.\n
528 //depot/my/project/ -- to import the current head
529 //depot/my/project/@all -- to import everything
530 //depot/my/project/@1,6 -- to import only from revision 1 to 6
532 (a ... is not needed in the path p4 specification, it's added implicitly)"""
534 self
.usage
+= " //depot/path[@revRange]"
537 self
.createdBranches
= Set()
538 self
.committedChanges
= Set()
540 self
.detectBranches
= False
541 self
.detectLabels
= False
542 self
.changesFile
= ""
543 self
.syncWithOrigin
= True
545 self
.importIntoRemotes
= True
547 self
.isWindows
= (platform
.system() == "Windows")
549 if gitConfig("git-p4.syncFromOrigin") == "false":
550 self
.syncWithOrigin
= False
552 def p4File(self
, depotPath
):
553 return os
.popen("p4 print -q \"%s\"" % depotPath
, "rb").read()
555 def extractFilesFromCommit(self
, commit
):
558 while commit
.has_key("depotFile%s" % fnum
):
559 path
= commit
["depotFile%s" % fnum
]
560 if not path
.startswith(self
.depotPath
):
561 # if not self.silent:
562 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
568 file["rev"] = commit
["rev%s" % fnum
]
569 file["action"] = commit
["action%s" % fnum
]
570 file["type"] = commit
["type%s" % fnum
]
575 def splitFilesIntoBranches(self
, commit
):
579 while commit
.has_key("depotFile%s" % fnum
):
580 path
= commit
["depotFile%s" % fnum
]
581 if not path
.startswith(self
.depotPath
):
582 # if not self.silent:
583 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
589 file["rev"] = commit
["rev%s" % fnum
]
590 file["action"] = commit
["action%s" % fnum
]
591 file["type"] = commit
["type%s" % fnum
]
594 relPath
= path
[len(self
.depotPath
):]
596 for branch
in self
.knownBranches
.keys():
597 if relPath
.startswith(branch
+ "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
598 if branch
not in branches
:
599 branches
[branch
] = []
600 branches
[branch
].append(file)
604 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
605 epoch
= details
["time"]
606 author
= details
["user"]
609 print "commit into %s" % branch
611 self
.gitStream
.write("commit %s\n" % branch
)
612 # gitStream.write("mark :%s\n" % details["change"])
613 self
.committedChanges
.add(int(details
["change"]))
615 if author
not in self
.users
:
616 self
.getUserMapFromPerforceServer()
617 if author
in self
.users
:
618 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
620 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
622 self
.gitStream
.write("committer %s\n" % committer
)
624 self
.gitStream
.write("data <<EOT\n")
625 self
.gitStream
.write(details
["desc"])
626 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
627 self
.gitStream
.write("EOT\n\n")
631 print "parent %s" % parent
632 self
.gitStream
.write("from %s\n" % parent
)
636 if not path
.startswith(branchPrefix
):
638 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
641 depotPath
= path
+ "#" + rev
642 relPath
= path
[len(branchPrefix
):]
643 action
= file["action"]
645 if file["type"] == "apple":
646 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
649 if action
== "delete":
650 self
.gitStream
.write("D %s\n" % relPath
)
653 if file["type"].startswith("x"):
656 data
= self
.p4File(depotPath
)
658 if self
.isWindows
and file["type"].endswith("text"):
659 data
= data
.replace("\r\n", "\n")
661 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
662 self
.gitStream
.write("data %s\n" % len(data
))
663 self
.gitStream
.write(data
)
664 self
.gitStream
.write("\n")
666 self
.gitStream
.write("\n")
668 change
= int(details
["change"])
670 if self
.labels
.has_key(change
):
671 label
= self
.labels
[change
]
672 labelDetails
= label
[0]
673 labelRevisions
= label
[1]
675 print "Change %s is labelled %s" % (change
, labelDetails
)
677 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
679 if len(files
) == len(labelRevisions
):
683 if info
["action"] == "delete":
685 cleanedFiles
[info
["depotFile"]] = info
["rev"]
687 if cleanedFiles
== labelRevisions
:
688 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
689 self
.gitStream
.write("from %s\n" % branch
)
691 owner
= labelDetails
["Owner"]
693 if author
in self
.users
:
694 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
696 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
697 self
.gitStream
.write("tagger %s\n" % tagger
)
698 self
.gitStream
.write("data <<EOT\n")
699 self
.gitStream
.write(labelDetails
["Description"])
700 self
.gitStream
.write("EOT\n\n")
704 print "Tag %s does not match with change %s: files do not match." % (labelDetails
["label"], change
)
708 print "Tag %s does not match with change %s: file count is different." % (labelDetails
["label"], change
)
710 def getUserMapFromPerforceServer(self
):
711 if self
.userMapFromPerforceServer
:
715 for output
in p4CmdList("users"):
716 if not output
.has_key("User"):
718 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
720 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
721 for user
in self
.users
.keys():
722 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
724 self
.userMapFromPerforceServer
= True
726 def loadUserMapFromCache(self
):
728 self
.userMapFromPerforceServer
= False
730 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
731 lines
= cache
.readlines()
734 entry
= line
[:-1].split("\t")
735 self
.users
[entry
[0]] = entry
[1]
737 self
.getUserMapFromPerforceServer()
742 l
= p4CmdList("labels %s..." % self
.depotPath
)
743 if len(l
) > 0 and not self
.silent
:
744 print "Finding files belonging to labels in %s" % self
.depotPath
747 label
= output
["label"]
751 print "Querying files for label %s" % label
752 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
753 revisions
[file["depotFile"]] = file["rev"]
754 change
= int(file["change"])
755 if change
> newestChange
:
756 newestChange
= change
758 self
.labels
[newestChange
] = [output
, revisions
]
761 print "Label changes: %s" % self
.labels
.keys()
763 def getBranchMapping(self
):
764 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
766 for info
in p4CmdList("branches"):
767 details
= p4Cmd("branch -o %s" % info
["branch"])
769 while details
.has_key("View%s" % viewIdx
):
770 paths
= details
["View%s" % viewIdx
].split(" ")
771 viewIdx
= viewIdx
+ 1
772 # require standard //depot/foo/... //depot/bar/... mapping
773 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
776 destination
= paths
[1]
777 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
778 source
= source
[len(self
.depotPath
):-4]
779 destination
= destination
[len(self
.depotPath
):-4]
780 if destination
not in self
.knownBranches
:
781 self
.knownBranches
[destination
] = source
782 if source
not in self
.knownBranches
:
783 self
.knownBranches
[source
] = source
785 def listExistingP4GitBranches(self
):
786 self
.p4BranchesInGit
= []
788 cmdline
= "git rev-parse --symbolic "
789 if self
.importIntoRemotes
:
790 cmdline
+= " --remotes"
792 cmdline
+= " --branches"
794 for line
in mypopen(cmdline
).readlines():
795 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
797 if self
.importIntoRemotes
:
802 self
.p4BranchesInGit
.append(branch
)
803 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
[:-1])
805 def createOrUpdateBranchesFromOrigin(self
):
807 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
809 for line
in mypopen("git rev-parse --symbolic --remotes"):
810 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
813 headName
= line
[len("origin/"):-1]
814 remoteHead
= self
.refPrefix
+ headName
815 originHead
= "origin/" + headName
817 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
818 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
822 if not gitBranchExists(remoteHead
):
824 print "creating %s" % remoteHead
827 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
828 if len(p4Change
) > 0:
829 if originPreviousDepotPath
== p4PreviousDepotPath
:
830 originP4Change
= int(originP4Change
)
831 p4Change
= int(p4Change
)
832 if originP4Change
> p4Change
:
833 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
836 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
839 system("git update-ref %s %s" % (remoteHead
, originHead
))
843 self
.changeRange
= ""
844 self
.initialParent
= ""
845 self
.previousDepotPath
= ""
847 # map from branch depot path to parent branch
848 self
.knownBranches
= {}
849 self
.initialParents
= {}
850 self
.hasOrigin
= gitBranchExists("origin")
852 if self
.importIntoRemotes
:
853 self
.refPrefix
= "refs/remotes/p4/"
855 self
.refPrefix
= "refs/heads/"
857 if self
.syncWithOrigin
:
860 print "Syncing with origin first by calling git fetch origin"
861 system("git fetch origin")
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 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
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()
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
):
1152 destination
= args
[1]
1156 if not depotPath
.startswith("//"):
1159 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1160 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1161 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1162 depotDir
= re
.sub(r
"/$", "", depotDir
)
1165 destination
= os
.path
.split(depotDir
)[-1]
1167 print "Importing from %s into %s" % (depotPath
, destination
)
1168 os
.makedirs(destination
)
1169 os
.chdir(destination
)
1171 gitdir
= os
.getcwd() + "/.git"
1172 if not P4Sync
.run(self
, [depotPath
]):
1174 if self
.branch
!= "master":
1175 if gitBranchExists("refs/remotes/p4/master"):
1176 system("git branch master refs/remotes/p4/master")
1177 system("git checkout -f")
1179 print "Could not detect main branch. No checkout/master branch created."
1182 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1184 optparse
.IndentedHelpFormatter
.__init
__(self
)
1186 def format_description(self
, description
):
1188 return description
+ "\n"
1192 def printUsage(commands
):
1193 print "usage: %s <command> [options]" % sys
.argv
[0]
1195 print "valid commands: %s" % ", ".join(commands
)
1197 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1201 "debug" : P4Debug(),
1202 "submit" : P4Submit(),
1204 "rebase" : P4Rebase(),
1205 "clone" : P4Clone(),
1206 "rollback" : P4RollBack()
1209 if len(sys
.argv
[1:]) == 0:
1210 printUsage(commands
.keys())
1214 cmdName
= sys
.argv
[1]
1216 cmd
= commands
[cmdName
]
1218 print "unknown command %s" % cmdName
1220 printUsage(commands
.keys())
1223 options
= cmd
.options
1228 if len(options
) > 0:
1229 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1231 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1233 description
= cmd
.description
,
1234 formatter
= HelpFormatter())
1236 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1240 if len(gitdir
) == 0:
1242 if not isValidGitDir(gitdir
):
1243 gitdir
= mypopen("git rev-parse --git-dir").read()[:-1]
1244 if os
.path
.exists(gitdir
):
1245 cdup
= mypopen("git rev-parse --show-cdup").read()[:-1];
1249 if not isValidGitDir(gitdir
):
1250 if isValidGitDir(gitdir
+ "/.git"):
1253 die("fatal: cannot locate git repository at %s" % gitdir
)
1255 os
.environ
["GIT_DIR"] = gitdir
1257 if not cmd
.run(args
):