3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
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
17 gitdir
= os
.environ
.get("GIT_DIR", "")
20 def write_pipe(c
, str):
22 sys
.stderr
.write('writing pipe: %s\n' % c
)
24 pipe
= os
.popen(c
, 'w')
27 sys
.stderr
.write('Command failed')
34 sys
.stderr
.write('reading pipe: %s\n' % c
)
36 pipe
= os
.popen(c
, 'rb')
39 sys
.stderr
.write('Command failed')
45 def read_pipe_lines(c
):
47 sys
.stderr
.write('reading pipe: %s\n' % c
)
48 ## todo: check return status
49 pipe
= os
.popen(c
, 'rb')
50 val
= pipe
.readlines()
52 sys
.stderr
.write('Command failed')
59 sys
.stderr
.write("executing %s" % cmd
)
60 if os
.system(cmd
) != 0:
61 die("command failed: %s" % cmd
)
64 cmd
= "p4 -G %s" % cmd
65 pipe
= os
.popen(cmd
, "rb")
70 entry
= marshal
.load(pipe
)
74 exitCode
= pipe
.close()
77 entry
["p4ExitCode"] = exitCode
89 def p4Where(depotPath
):
90 if not depotPath
.endswith("/"):
92 output
= p4Cmd("where %s..." % depotPath
)
93 if output
["code"] == "error":
97 clientPath
= output
.get("path")
98 elif "data" in output
:
99 data
= output
.get("data")
100 lastSpace
= data
.rfind(" ")
101 clientPath
= data
[lastSpace
+ 1:]
103 if clientPath
.endswith("..."):
104 clientPath
= clientPath
[:-3]
108 sys
.stderr
.write(msg
+ "\n")
111 def currentGitBranch():
112 return read_pipe("git name-rev HEAD").split(" ")[1][:-1]
114 def isValidGitDir(path
):
115 if os
.path
.exists(path
+ "/HEAD") and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects"):
119 def parseRevision(ref
):
120 return read_pipe("git rev-parse %s" % ref
)[:-1]
122 def extractLogMessageFromGitCommit(commit
):
125 ## fixme: title is first line of commit, not 1st paragraph.
127 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
136 def extractDepotPathAndChangeFromGitLog(log
):
138 for line
in log
.split("\n"):
140 if line
.startswith("[git-p4:") and line
.endswith("]"):
141 line
= line
[8:-1].strip()
142 for assignment
in line
.split(":"):
143 variable
= assignment
.strip()
145 equalPos
= assignment
.find("=")
147 variable
= assignment
[:equalPos
].strip()
148 value
= assignment
[equalPos
+ 1:].strip()
149 if value
.startswith("\"") and value
.endswith("\""):
151 values
[variable
] = value
153 return values
.get("depot-path"), values
.get("change")
155 def gitBranchExists(branch
):
156 proc
= subprocess
.Popen(["git", "rev-parse", branch
], stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
157 return proc
.wait() == 0;
160 return mypopen("git config %s" % key
).read()[:-1]
164 self
.usage
= "usage: %prog [options]"
167 class P4Debug(Command
):
169 Command
.__init
__(self
)
172 self
.description
= "A tool to debug the output of p4 -G."
173 self
.needsGit
= False
176 for output
in p4CmdList(" ".join(args
)):
180 class P4RollBack(Command
):
182 Command
.__init
__(self
)
184 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
185 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
187 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
189 self
.rollbackLocalBranches
= False
194 maxChange
= int(args
[0])
196 if "p4ExitCode" in p4Cmd("changes -m 1"):
197 die("Problems executing p4");
199 if self
.rollbackLocalBranches
:
200 refPrefix
= "refs/heads/"
201 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
203 refPrefix
= "refs/remotes/"
204 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
207 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
208 ref
= refPrefix
+ line
[:-1]
209 log
= extractLogMessageFromGitCommit(ref
)
210 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
213 if len(p4Cmd("changes -m 1 %s...@%s" % (depotPath
, maxChange
))) == 0:
214 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
215 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
218 while len(change
) > 0 and int(change
) > maxChange
:
221 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
222 system("git update-ref %s \"%s^\"" % (ref
, ref
))
223 log
= extractLogMessageFromGitCommit(ref
)
224 depotPath
, change
= extractDepotPathAndChangeFromGitLog(log
)
227 print "%s rewound to %s" % (ref
, change
)
231 class P4Submit(Command
):
233 Command
.__init
__(self
)
235 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
236 optparse
.make_option("--origin", dest
="origin"),
237 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
238 optparse
.make_option("--log-substitutions", dest
="substFile"),
239 optparse
.make_option("--dry-run", action
="store_true"),
240 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
241 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
243 self
.description
= "Submit changes from git to the perforce depot."
244 self
.usage
+= " [name of git branch to submit into perforce depot]"
245 self
.firstTime
= True
247 self
.interactive
= True
250 self
.firstTime
= True
252 self
.directSubmit
= False
253 self
.trustMeLikeAFool
= False
255 self
.logSubstitutions
= {}
256 self
.logSubstitutions
["<enter description here>"] = "%log%"
257 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
260 if len(p4CmdList("opened ...")) > 0:
261 die("You have files opened with perforce! Close them before starting the sync.")
264 if len(self
.config
) > 0 and not self
.reset
:
265 die("Cannot start sync. Previous sync config found at %s\n"
266 "If you want to start submitting again from scratch "
267 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
270 if self
.directSubmit
:
273 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
274 commits
.append(line
[:-1])
277 self
.config
["commits"] = commits
279 def prepareLogMessage(self
, template
, message
):
282 for line
in template
.split("\n"):
283 if line
.startswith("#"):
284 result
+= line
+ "\n"
288 for key
in self
.logSubstitutions
.keys():
289 if line
.find(key
) != -1:
290 value
= self
.logSubstitutions
[key
]
291 value
= value
.replace("%log%", message
)
292 if value
!= "@remove@":
293 result
+= line
.replace(key
, value
) + "\n"
298 result
+= line
+ "\n"
302 def applyCommit(self
, id):
303 if self
.directSubmit
:
304 print "Applying local change in working directory/index"
305 diff
= self
.diffStatus
307 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
308 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
310 filesToDelete
= set()
314 path
= line
[1:].strip()
316 system("p4 edit \"%s\"" % path
)
317 editedFiles
.add(path
)
318 elif modifier
== "A":
320 if path
in filesToDelete
:
321 filesToDelete
.remove(path
)
322 elif modifier
== "D":
323 filesToDelete
.add(path
)
324 if path
in filesToAdd
:
325 filesToAdd
.remove(path
)
327 die("unknown modifier %s for %s" % (modifier
, path
))
329 if self
.directSubmit
:
330 diffcmd
= "cat \"%s\"" % self
.diffFile
332 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
333 patchcmd
= diffcmd
+ " | git apply "
334 tryPatchCmd
= patchcmd
+ "--check -"
335 applyPatchCmd
= patchcmd
+ "--check --apply -"
337 if os
.system(tryPatchCmd
) != 0:
338 print "Unfortunately applying the change failed!"
339 print "What do you want to do?"
341 while response
!= "s" and response
!= "a" and response
!= "w":
342 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
343 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
345 print "Skipping! Good luck with the next patches..."
347 elif response
== "a":
348 os
.system(applyPatchCmd
)
349 if len(filesToAdd
) > 0:
350 print "You may also want to call p4 add on the following files:"
351 print " ".join(filesToAdd
)
352 if len(filesToDelete
):
353 print "The following files should be scheduled for deletion with p4 delete:"
354 print " ".join(filesToDelete
)
355 die("Please resolve and submit the conflict manually and "
356 + "continue afterwards with git-p4 submit --continue")
357 elif response
== "w":
358 system(diffcmd
+ " > patch.txt")
359 print "Patch saved to patch.txt in %s !" % self
.clientPath
360 die("Please resolve and submit the conflict manually and "
361 "continue afterwards with git-p4 submit --continue")
363 system(applyPatchCmd
)
366 system("p4 add %s" % f
)
367 for f
in filesToDelete
:
368 system("p4 revert %s" % f
)
369 system("p4 delete %s" % f
)
372 if not self
.directSubmit
:
373 logMessage
= extractLogMessageFromGitCommit(id)
374 logMessage
= logMessage
.replace("\n", "\n\t")
375 logMessage
= logMessage
[:-1]
377 template
= read_pipe("p4 change -o")
380 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
381 diff
= read_pipe("p4 diff -du ...")
383 for newFile
in filesToAdd
:
384 diff
+= "==== new file ====\n"
385 diff
+= "--- /dev/null\n"
386 diff
+= "+++ %s\n" % newFile
387 f
= open(newFile
, "r")
388 for line
in f
.readlines():
392 separatorLine
= "######## everything below this line is just the diff #######"
393 if platform
.system() == "Windows":
394 separatorLine
+= "\r"
395 separatorLine
+= "\n"
398 if self
.trustMeLikeAFool
:
401 firstIteration
= True
402 while response
== "e":
403 if not firstIteration
:
404 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
405 firstIteration
= False
407 [handle
, fileName
] = tempfile
.mkstemp()
408 tmpFile
= os
.fdopen(handle
, "w+")
409 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
412 if platform
.system() == "Windows":
413 defaultEditor
= "notepad"
414 editor
= os
.environ
.get("EDITOR", defaultEditor
);
415 system(editor
+ " " + fileName
)
416 tmpFile
= open(fileName
, "rb")
417 message
= tmpFile
.read()
420 submitTemplate
= message
[:message
.index(separatorLine
)]
422 if response
== "y" or response
== "yes":
425 raw_input("Press return to continue...")
427 if self
.directSubmit
:
428 print "Submitting to git first"
429 os
.chdir(self
.oldWorkingDirectory
)
430 write_pipe("git commit -a -F -", submitTemplate
)
431 os
.chdir(self
.clientPath
)
433 write_pipe("p4 submit -i", submitTemplate
)
434 elif response
== "s":
435 for f
in editedFiles
:
436 system("p4 revert \"%s\"" % f
);
438 system("p4 revert \"%s\"" % f
);
440 for f
in filesToDelete
:
441 system("p4 delete \"%s\"" % f
);
444 print "Not submitting!"
445 self
.interactive
= False
447 fileName
= "submit.txt"
448 file = open(fileName
, "w+")
449 file.write(self
.prepareLogMessage(template
, logMessage
))
451 print ("Perforce submit template written as %s. "
452 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
453 % (fileName
, fileName
))
457 # make gitdir absolute so we can cd out into the perforce checkout
458 gitdir
= os
.path
.abspath(gitdir
)
459 os
.environ
["GIT_DIR"] = gitdir
462 self
.master
= currentGitBranch()
463 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
464 die("Detecting current git branch failed!")
466 self
.master
= args
[0]
471 if gitBranchExists("p4"):
472 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("p4"))
473 if len(depotPath
) == 0 and gitBranchExists("origin"):
474 [depotPath
, dummy
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit("origin"))
476 if len(depotPath
) == 0:
477 print "Internal error: cannot locate perforce depot path from existing branches"
480 self
.clientPath
= p4Where(depotPath
)
482 if len(self
.clientPath
) == 0:
483 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
486 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
487 self
.oldWorkingDirectory
= os
.getcwd()
489 if self
.directSubmit
:
490 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
491 if len(self
.diffStatus
) == 0:
492 print "No changes in working directory to submit."
494 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
495 self
.diffFile
= gitdir
+ "/p4-git-diff"
496 f
= open(self
.diffFile
, "wb")
500 os
.chdir(self
.clientPath
)
501 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
502 if response
== "y" or response
== "yes":
503 system("p4 sync ...")
505 if len(self
.origin
) == 0:
506 if gitBranchExists("p4"):
509 self
.origin
= "origin"
512 self
.firstTime
= True
514 if len(self
.substFile
) > 0:
515 for line
in open(self
.substFile
, "r").readlines():
516 tokens
= line
[:-1].split("=")
517 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
520 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
521 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
526 commits
= self
.config
.get("commits", [])
528 while len(commits
) > 0:
529 self
.firstTime
= False
531 commits
= commits
[1:]
532 self
.config
["commits"] = commits
533 self
.applyCommit(commit
)
534 if not self
.interactive
:
539 if self
.directSubmit
:
540 os
.remove(self
.diffFile
)
542 if len(commits
) == 0:
544 print "No changes found to apply between %s and current HEAD" % self
.origin
546 print "All changes applied!"
547 os
.chdir(self
.oldWorkingDirectory
)
548 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
549 if response
== "y" or response
== "yes":
552 os
.remove(self
.configFile
)
556 class P4Sync(Command
):
558 Command
.__init
__(self
)
560 optparse
.make_option("--branch", dest
="branch"),
561 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
562 optparse
.make_option("--changesfile", dest
="changesFile"),
563 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
564 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
565 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
566 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
567 optparse
.make_option("--max-changes", dest
="maxChanges"),
568 optparse
.make_option("--keep-path", dest
="keepRepoPath")
570 self
.description
= """Imports from Perforce into a git repository.\n
572 //depot/my/project/ -- to import the current head
573 //depot/my/project/@all -- to import everything
574 //depot/my/project/@1,6 -- to import only from revision 1 to 6
576 (a ... is not needed in the path p4 specification, it's added implicitly)"""
578 self
.usage
+= " //depot/path[@revRange]"
580 self
.createdBranches
= Set()
581 self
.committedChanges
= Set()
583 self
.detectBranches
= False
584 self
.detectLabels
= False
585 self
.changesFile
= ""
586 self
.syncWithOrigin
= True
588 self
.importIntoRemotes
= True
590 self
.isWindows
= (platform
.system() == "Windows")
591 self
.depotPath
= None
592 self
.keepRepoPath
= False
594 if gitConfig("git-p4.syncFromOrigin") == "false":
595 self
.syncWithOrigin
= False
597 def p4File(self
, depotPath
):
598 return read_pipe("p4 print -q \"%s\"" % depotPath
)
600 def extractFilesFromCommit(self
, commit
):
603 while commit
.has_key("depotFile%s" % fnum
):
604 path
= commit
["depotFile%s" % fnum
]
605 if not path
.startswith(self
.depotPath
):
606 # if not self.silent:
607 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
613 file["rev"] = commit
["rev%s" % fnum
]
614 file["action"] = commit
["action%s" % fnum
]
615 file["type"] = commit
["type%s" % fnum
]
620 def stripRepoPath(self
, path
, prefix
):
621 if self
.keepRepoPath
:
622 prefix
= re
.sub("^(//[^/]+/).*", r
'\1', prefix
)
624 return path
[len(prefix
):]
626 def splitFilesIntoBranches(self
, commit
):
629 while commit
.has_key("depotFile%s" % fnum
):
630 path
= commit
["depotFile%s" % fnum
]
631 if not path
.startswith(self
.depotPath
):
632 # if not self.silent:
633 # print "\nchanged files: ignoring path %s outside of %s in change %s" % (path, self.depotPath, change)
639 file["rev"] = commit
["rev%s" % fnum
]
640 file["action"] = commit
["action%s" % fnum
]
641 file["type"] = commit
["type%s" % fnum
]
644 relPath
= self
.stripRepoPath(path
, self
.depotPath
)
646 for branch
in self
.knownBranches
.keys():
648 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
649 if relPath
.startswith(branch
+ "/"):
650 if branch
not in branches
:
651 branches
[branch
] = []
652 branches
[branch
].append(file)
656 def commit(self
, details
, files
, branch
, branchPrefix
, parent
= ""):
657 epoch
= details
["time"]
658 author
= details
["user"]
661 print "commit into %s" % branch
663 self
.gitStream
.write("commit %s\n" % branch
)
664 # gitStream.write("mark :%s\n" % details["change"])
665 self
.committedChanges
.add(int(details
["change"]))
667 if author
not in self
.users
:
668 self
.getUserMapFromPerforceServer()
669 if author
in self
.users
:
670 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
672 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
674 self
.gitStream
.write("committer %s\n" % committer
)
676 self
.gitStream
.write("data <<EOT\n")
677 self
.gitStream
.write(details
["desc"])
678 self
.gitStream
.write("\n[git-p4: depot-path = \"%s\": change = %s]\n" % (branchPrefix
, details
["change"]))
679 self
.gitStream
.write("EOT\n\n")
683 print "parent %s" % parent
684 self
.gitStream
.write("from %s\n" % parent
)
688 if not path
.startswith(branchPrefix
):
689 # print "\nchanged files: ignoring path %s outside of branch prefix %s in change %s" % (path, branchPrefix, details["change"])
692 depotPath
= path
+ "#" + rev
693 relPath
= self
.stripRepoPath(path
, branchPrefix
)
694 action
= file["action"]
696 if file["type"] == "apple":
697 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
700 if action
== "delete":
701 self
.gitStream
.write("D %s\n" % relPath
)
704 if file["type"].startswith("x"):
707 data
= self
.p4File(depotPath
)
709 if self
.isWindows
and file["type"].endswith("text"):
710 data
= data
.replace("\r\n", "\n")
712 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
713 self
.gitStream
.write("data %s\n" % len(data
))
714 self
.gitStream
.write(data
)
715 self
.gitStream
.write("\n")
717 self
.gitStream
.write("\n")
719 change
= int(details
["change"])
721 if self
.labels
.has_key(change
):
722 label
= self
.labels
[change
]
723 labelDetails
= label
[0]
724 labelRevisions
= label
[1]
726 print "Change %s is labelled %s" % (change
, labelDetails
)
728 files
= p4CmdList("files %s...@%s" % (branchPrefix
, change
))
730 if len(files
) == len(labelRevisions
):
734 if info
["action"] == "delete":
736 cleanedFiles
[info
["depotFile"]] = info
["rev"]
738 if cleanedFiles
== labelRevisions
:
739 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
740 self
.gitStream
.write("from %s\n" % branch
)
742 owner
= labelDetails
["Owner"]
744 if author
in self
.users
:
745 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
747 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
748 self
.gitStream
.write("tagger %s\n" % tagger
)
749 self
.gitStream
.write("data <<EOT\n")
750 self
.gitStream
.write(labelDetails
["Description"])
751 self
.gitStream
.write("EOT\n\n")
755 print ("Tag %s does not match with change %s: files do not match."
756 % (labelDetails
["label"], change
))
760 print ("Tag %s does not match with change %s: file count is different."
761 % (labelDetails
["label"], change
))
763 def getUserMapFromPerforceServer(self
):
764 if self
.userMapFromPerforceServer
:
768 for output
in p4CmdList("users"):
769 if not output
.has_key("User"):
771 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
773 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
774 for user
in self
.users
.keys():
775 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
777 self
.userMapFromPerforceServer
= True
779 def loadUserMapFromCache(self
):
781 self
.userMapFromPerforceServer
= False
783 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
784 lines
= cache
.readlines()
787 entry
= line
[:-1].split("\t")
788 self
.users
[entry
[0]] = entry
[1]
790 self
.getUserMapFromPerforceServer()
795 l
= p4CmdList("labels %s..." % self
.depotPath
)
796 if len(l
) > 0 and not self
.silent
:
797 print "Finding files belonging to labels in %s" % self
.depotPath
800 label
= output
["label"]
804 print "Querying files for label %s" % label
805 for file in p4CmdList("files %s...@%s" % (self
.depotPath
, label
)):
806 revisions
[file["depotFile"]] = file["rev"]
807 change
= int(file["change"])
808 if change
> newestChange
:
809 newestChange
= change
811 self
.labels
[newestChange
] = [output
, revisions
]
814 print "Label changes: %s" % self
.labels
.keys()
816 def getBranchMapping(self
):
817 self
.projectName
= self
.depotPath
[self
.depotPath
[:-1].rfind("/") + 1:]
819 for info
in p4CmdList("branches"):
820 details
= p4Cmd("branch -o %s" % info
["branch"])
822 while details
.has_key("View%s" % viewIdx
):
823 paths
= details
["View%s" % viewIdx
].split(" ")
824 viewIdx
= viewIdx
+ 1
825 # require standard //depot/foo/... //depot/bar/... mapping
826 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
829 destination
= paths
[1]
830 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
831 source
= source
[len(self
.depotPath
):-4]
832 destination
= destination
[len(self
.depotPath
):-4]
833 if destination
not in self
.knownBranches
:
834 self
.knownBranches
[destination
] = source
835 if source
not in self
.knownBranches
:
836 self
.knownBranches
[source
] = source
838 def listExistingP4GitBranches(self
):
839 self
.p4BranchesInGit
= []
841 cmdline
= "git rev-parse --symbolic "
842 if self
.importIntoRemotes
:
843 cmdline
+= " --remotes"
845 cmdline
+= " --branches"
847 for line
in read_pipe_lines(cmdline
):
849 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD\n"):
851 if self
.importIntoRemotes
:
853 branch
= re
.sub ("^p4/", "", line
)
855 self
.p4BranchesInGit
.append(branch
)
856 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
858 def createOrUpdateBranchesFromOrigin(self
):
860 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
862 for line
in mypopen("git rev-parse --symbolic --remotes"):
863 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
866 headName
= line
[len("origin/"):-1]
867 remoteHead
= self
.refPrefix
+ headName
868 originHead
= "origin/" + headName
870 [originPreviousDepotPath
, originP4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(originHead
))
871 if len(originPreviousDepotPath
) == 0 or len(originP4Change
) == 0:
875 if not gitBranchExists(remoteHead
):
877 print "creating %s" % remoteHead
880 [p4PreviousDepotPath
, p4Change
] = extractDepotPathAndChangeFromGitLog(extractLogMessageFromGitCommit(remoteHead
))
881 if len(p4Change
) > 0:
882 if originPreviousDepotPath
== p4PreviousDepotPath
:
883 originP4Change
= int(originP4Change
)
884 p4Change
= int(p4Change
)
885 if originP4Change
> p4Change
:
886 print "%s (%s) is newer than %s (%s). Updating p4 branch from origin." % (originHead
, originP4Change
, remoteHead
, p4Change
)
889 print "Ignoring: %s was imported from %s while %s was imported from %s" % (originHead
, originPreviousDepotPath
, remoteHead
, p4PreviousDepotPath
)
892 system("git update-ref %s %s" % (remoteHead
, originHead
))
896 self
.changeRange
= ""
897 self
.initialParent
= ""
898 self
.previousDepotPath
= ""
900 # map from branch depot path to parent branch
901 self
.knownBranches
= {}
902 self
.initialParents
= {}
903 self
.hasOrigin
= gitBranchExists("origin")
905 if self
.importIntoRemotes
:
906 self
.refPrefix
= "refs/remotes/p4/"
908 self
.refPrefix
= "refs/heads/"
910 if self
.syncWithOrigin
and self
.hasOrigin
:
912 print "Syncing with origin first by calling git fetch origin"
913 system("git fetch origin")
915 if len(self
.branch
) == 0:
916 self
.branch
= self
.refPrefix
+ "master"
917 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
918 system("git update-ref %s refs/heads/p4" % self
.branch
)
919 system("git branch -D p4");
920 # create it /after/ importing, when master exists
921 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
922 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
926 self
.createOrUpdateBranchesFromOrigin()
927 self
.listExistingP4GitBranches()
929 if len(self
.p4BranchesInGit
) > 1:
931 print "Importing from/into multiple branches"
932 self
.detectBranches
= True
935 print "branches: %s" % self
.p4BranchesInGit
938 for branch
in self
.p4BranchesInGit
:
939 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
940 (depotPath
, change
) = extractDepotPathAndChangeFromGitLog(logMsg
)
943 print "path %s change %s" % (depotPath
, change
)
945 if len(depotPath
) > 0 and len(change
) > 0:
946 change
= int(change
) + 1
947 p4Change
= max(p4Change
, change
)
949 if len(self
.previousDepotPath
) == 0:
950 self
.previousDepotPath
= depotPath
953 l
= min(len(self
.previousDepotPath
), len(depotPath
))
954 while i
< l
and self
.previousDepotPath
[i
] == depotPath
[i
]:
956 self
.previousDepotPath
= self
.previousDepotPath
[:i
]
959 self
.depotPath
= self
.previousDepotPath
960 self
.changeRange
= "@%s,#head" % p4Change
961 self
.initialParent
= parseRevision(self
.branch
)
962 if not self
.silent
and not self
.detectBranches
:
963 print "Performing incremental import into %s git branch" % self
.branch
965 if not self
.branch
.startswith("refs/"):
966 self
.branch
= "refs/heads/" + self
.branch
968 if len(self
.depotPath
) != 0:
969 self
.depotPath
= self
.depotPath
[:-1]
971 if len(args
) == 0 and len(self
.depotPath
) != 0:
973 print "Depot path: %s" % self
.depotPath
977 if len(self
.depotPath
) != 0 and self
.depotPath
!= args
[0]:
978 print ("previous import used depot path %s and now %s was specified. "
979 "This doesn't work!" % (self
.depotPath
, args
[0]))
981 self
.depotPath
= args
[0]
986 if self
.depotPath
.find("@") != -1:
987 atIdx
= self
.depotPath
.index("@")
988 self
.changeRange
= self
.depotPath
[atIdx
:]
989 if self
.changeRange
== "@all":
990 self
.changeRange
= ""
991 elif self
.changeRange
.find(",") == -1:
992 self
.revision
= self
.changeRange
993 self
.changeRange
= ""
994 self
.depotPath
= self
.depotPath
[0:atIdx
]
995 elif self
.depotPath
.find("#") != -1:
996 hashIdx
= self
.depotPath
.index("#")
997 self
.revision
= self
.depotPath
[hashIdx
:]
998 self
.depotPath
= self
.depotPath
[0:hashIdx
]
999 elif len(self
.previousDepotPath
) == 0:
1000 self
.revision
= "#head"
1002 self
.depotPath
= re
.sub ("\.\.\.$", "", self
.depotPath
)
1003 if not self
.depotPath
.endswith("/"):
1004 self
.depotPath
+= "/"
1006 self
.loadUserMapFromCache()
1008 if self
.detectLabels
:
1011 if self
.detectBranches
:
1012 self
.getBranchMapping();
1014 print "p4-git branches: %s" % self
.p4BranchesInGit
1015 print "initial parents: %s" % self
.initialParents
1016 for b
in self
.p4BranchesInGit
:
1018 b
= b
[len(self
.projectName
):]
1019 self
.createdBranches
.add(b
)
1021 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1023 importProcess
= subprocess
.Popen(["git", "fast-import"],
1024 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
, stderr
=subprocess
.PIPE
);
1025 self
.gitOutput
= importProcess
.stdout
1026 self
.gitStream
= importProcess
.stdin
1027 self
.gitError
= importProcess
.stderr
1029 if len(self
.revision
) > 0:
1030 print "Doing initial import of %s from revision %s" % (self
.depotPath
, self
.revision
)
1032 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1033 details
["desc"] = ("Initial import of %s from the state at revision %s"
1034 % (self
.depotPath
, self
.revision
))
1035 details
["change"] = self
.revision
1039 for info
in p4CmdList("files %s...%s" % (self
.depotPath
, self
.revision
)):
1040 change
= int(info
["change"])
1041 if change
> newestRevision
:
1042 newestRevision
= change
1044 if info
["action"] == "delete":
1045 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1046 #fileCnt = fileCnt + 1
1049 for prop
in [ "depotFile", "rev", "action", "type" ]:
1050 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1052 fileCnt
= fileCnt
+ 1
1054 details
["change"] = newestRevision
1057 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPath
)
1059 print "IO error with git fast-import. Is your git version recent enough?"
1060 print self
.gitError
.read()
1065 if len(self
.changesFile
) > 0:
1066 output
= open(self
.changesFile
).readlines()
1069 changeSet
.add(int(line
))
1071 for change
in changeSet
:
1072 changes
.append(change
)
1077 print "Getting p4 changes for %s...%s" % (self
.depotPath
, self
.changeRange
)
1078 output
= read_pipe_lines("p4 changes %s...%s" % (self
.depotPath
, self
.changeRange
))
1081 changeNum
= line
.split(" ")[1]
1082 changes
.append(changeNum
)
1086 if len(self
.maxChanges
) > 0:
1087 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1089 if len(changes
) == 0:
1091 print "No changes to import!"
1094 self
.updatedBranches
= set()
1097 for change
in changes
:
1098 description
= p4Cmd("describe %s" % change
)
1101 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1106 if self
.detectBranches
:
1107 branches
= self
.splitFilesIntoBranches(description
)
1108 for branch
in branches
.keys():
1109 branchPrefix
= self
.depotPath
+ branch
+ "/"
1113 filesForCommit
= branches
[branch
]
1116 print "branch is %s" % branch
1118 self
.updatedBranches
.add(branch
)
1120 if branch
not in self
.createdBranches
:
1121 self
.createdBranches
.add(branch
)
1122 parent
= self
.knownBranches
[branch
]
1123 if parent
== branch
:
1126 print "parent determined through known branches: %s" % parent
1128 # main branch? use master
1129 if branch
== "main":
1132 branch
= self
.projectName
+ branch
1134 if parent
== "main":
1136 elif len(parent
) > 0:
1137 parent
= self
.projectName
+ parent
1139 branch
= self
.refPrefix
+ branch
1141 parent
= self
.refPrefix
+ parent
1144 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1146 if len(parent
) == 0 and branch
in self
.initialParents
:
1147 parent
= self
.initialParents
[branch
]
1148 del self
.initialParents
[branch
]
1150 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1152 files
= self
.extractFilesFromCommit(description
)
1153 self
.commit(description
, files
, self
.branch
, self
.depotPath
, self
.initialParent
)
1154 self
.initialParent
= ""
1156 print self
.gitError
.read()
1161 if len(self
.updatedBranches
) > 0:
1162 sys
.stdout
.write("Updated branches: ")
1163 for b
in self
.updatedBranches
:
1164 sys
.stdout
.write("%s " % b
)
1165 sys
.stdout
.write("\n")
1168 self
.gitStream
.close()
1169 if importProcess
.wait() != 0:
1170 die("fast-import failed: %s" % self
.gitError
.read())
1171 self
.gitOutput
.close()
1172 self
.gitError
.close()
1176 class P4Rebase(Command
):
1178 Command
.__init
__(self
)
1180 self
.description
= ("Fetches the latest revision from perforce and "
1181 + "rebases the current work (branch) against it")
1183 def run(self
, args
):
1186 print "Rebasing the current branch"
1187 oldHead
= read_pipe("git rev-parse HEAD")[:-1]
1188 system("git rebase p4")
1189 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1192 class P4Clone(P4Sync
):
1194 P4Sync
.__init
__(self
)
1195 self
.description
= "Creates a new git repository and imports from Perforce into it"
1196 self
.usage
= "usage: %prog [options] //depot/path[@revRange] [directory]"
1197 self
.needsGit
= False
1199 def run(self
, args
):
1207 destination
= args
[1]
1211 if not depotPath
.startswith("//"):
1214 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1215 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1216 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1217 depotDir
= re
.sub(r
"/$", "", depotDir
)
1220 destination
= os
.path
.split(depotDir
)[-1]
1222 print "Importing from %s into %s" % (depotPath
, destination
)
1223 os
.makedirs(destination
)
1224 os
.chdir(destination
)
1226 gitdir
= os
.getcwd() + "/.git"
1227 if not P4Sync
.run(self
, [depotPath
]):
1229 if self
.branch
!= "master":
1230 if gitBranchExists("refs/remotes/p4/master"):
1231 system("git branch master refs/remotes/p4/master")
1232 system("git checkout -f")
1234 print "Could not detect main branch. No checkout/master branch created."
1237 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1239 optparse
.IndentedHelpFormatter
.__init
__(self
)
1241 def format_description(self
, description
):
1243 return description
+ "\n"
1247 def printUsage(commands
):
1248 print "usage: %s <command> [options]" % sys
.argv
[0]
1250 print "valid commands: %s" % ", ".join(commands
)
1252 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1256 "debug" : P4Debug(),
1257 "submit" : P4Submit(),
1259 "rebase" : P4Rebase(),
1260 "clone" : P4Clone(),
1261 "rollback" : P4RollBack()
1264 if len(sys
.argv
[1:]) == 0:
1265 printUsage(commands
.keys())
1269 cmdName
= sys
.argv
[1]
1271 cmd
= commands
[cmdName
]
1273 print "unknown command %s" % cmdName
1275 printUsage(commands
.keys())
1278 options
= cmd
.options
1283 if len(options
) > 0:
1284 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1286 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1288 description
= cmd
.description
,
1289 formatter
= HelpFormatter())
1291 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1295 if len(gitdir
) == 0:
1297 if not isValidGitDir(gitdir
):
1298 gitdir
= read_pipe("git rev-parse --git-dir")[:-1]
1299 if os
.path
.exists(gitdir
):
1300 cdup
= read_pipe("git rev-parse --show-cdup")[:-1];
1304 if not isValidGitDir(gitdir
):
1305 if isValidGitDir(gitdir
+ "/.git"):
1308 die("fatal: cannot locate git repository at %s" % gitdir
)
1310 os
.environ
["GIT_DIR"] = gitdir
1312 if not cmd
.run(args
):