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
19 def write_pipe(c
, str):
21 sys
.stderr
.write('writing pipe: %s\n' % c
)
23 pipe
= os
.popen(c
, 'w')
26 sys
.stderr
.write('Command failed: %s' % c
)
31 def read_pipe(c
, ignore_error
=False):
33 sys
.stderr
.write('reading pipe: %s\n' % c
)
35 pipe
= os
.popen(c
, 'rb')
37 if pipe
.close() and not ignore_error
:
38 sys
.stderr
.write('Command failed: %s\n' % c
)
44 def read_pipe_lines(c
):
46 sys
.stderr
.write('reading pipe: %s\n' % c
)
47 ## todo: check return status
48 pipe
= os
.popen(c
, 'rb')
49 val
= pipe
.readlines()
51 sys
.stderr
.write('Command failed: %s\n' % c
)
58 sys
.stderr
.write("executing %s\n" % cmd
)
59 if os
.system(cmd
) != 0:
60 die("command failed: %s" % cmd
)
63 cmd
= "p4 -G %s" % cmd
64 pipe
= os
.popen(cmd
, "rb")
69 entry
= marshal
.load(pipe
)
73 exitCode
= pipe
.close()
76 entry
["p4ExitCode"] = exitCode
88 def p4Where(depotPath
):
89 if not depotPath
.endswith("/"):
91 output
= p4Cmd("where %s..." % depotPath
)
92 if output
["code"] == "error":
96 clientPath
= output
.get("path")
97 elif "data" in output
:
98 data
= output
.get("data")
99 lastSpace
= data
.rfind(" ")
100 clientPath
= data
[lastSpace
+ 1:]
102 if clientPath
.endswith("..."):
103 clientPath
= clientPath
[:-3]
107 sys
.stderr
.write(msg
+ "\n")
110 def currentGitBranch():
111 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
113 def isValidGitDir(path
):
114 if (os
.path
.exists(path
+ "/HEAD")
115 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
).strip()
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 extractSettingsGitLog(log
):
138 for line
in log
.split("\n"):
140 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
144 assignments
= m
.group(1).split (':')
145 for a
in assignments
:
147 key
= vals
[0].strip()
148 val
= ('='.join (vals
[1:])).strip()
149 if val
.endswith ('\"') and val
.startswith('"'):
154 values
['depot-paths'] = values
.get("depot-paths").split(',')
157 def gitBranchExists(branch
):
158 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
159 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
160 return proc
.wait() == 0;
163 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
167 self
.usage
= "usage: %prog [options]"
170 class P4Debug(Command
):
172 Command
.__init
__(self
)
174 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
176 self
.description
= "A tool to debug the output of p4 -G."
177 self
.needsGit
= False
180 for output
in p4CmdList(" ".join(args
)):
184 class P4RollBack(Command
):
186 Command
.__init
__(self
)
188 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
189 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
191 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
193 self
.rollbackLocalBranches
= False
198 maxChange
= int(args
[0])
200 if "p4ExitCode" in p4Cmd("changes -m 1"):
201 die("Problems executing p4");
203 if self
.rollbackLocalBranches
:
204 refPrefix
= "refs/heads/"
205 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
207 refPrefix
= "refs/remotes/"
208 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
211 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
213 ref
= refPrefix
+ line
214 log
= extractLogMessageFromGitCommit(ref
)
215 settings
= extractSettingsGitLog(log
)
217 depotPaths
= settings
['depot-paths']
218 change
= settings
['change']
222 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
223 for p
in depotPaths
]))) == 0:
224 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
225 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
228 while change
and int(change
) > maxChange
:
231 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
232 system("git update-ref %s \"%s^\"" % (ref
, ref
))
233 log
= extractLogMessageFromGitCommit(ref
)
234 settings
= extractSettingsGitLog(log
)
237 depotPaths
= settings
['depot-paths']
238 change
= settings
['change']
241 print "%s rewound to %s" % (ref
, change
)
245 class P4Submit(Command
):
247 Command
.__init
__(self
)
249 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
250 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
251 optparse
.make_option("--origin", dest
="origin"),
252 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
253 optparse
.make_option("--log-substitutions", dest
="substFile"),
254 optparse
.make_option("--dry-run", action
="store_true"),
255 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
256 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
258 self
.description
= "Submit changes from git to the perforce depot."
259 self
.usage
+= " [name of git branch to submit into perforce depot]"
260 self
.firstTime
= True
262 self
.interactive
= True
265 self
.firstTime
= True
267 self
.directSubmit
= False
268 self
.trustMeLikeAFool
= False
270 self
.logSubstitutions
= {}
271 self
.logSubstitutions
["<enter description here>"] = "%log%"
272 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
275 if len(p4CmdList("opened ...")) > 0:
276 die("You have files opened with perforce! Close them before starting the sync.")
279 if len(self
.config
) > 0 and not self
.reset
:
280 die("Cannot start sync. Previous sync config found at %s\n"
281 "If you want to start submitting again from scratch "
282 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
285 if self
.directSubmit
:
288 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
289 commits
.append(line
.strip())
292 self
.config
["commits"] = commits
294 def prepareLogMessage(self
, template
, message
):
297 for line
in template
.split("\n"):
298 if line
.startswith("#"):
299 result
+= line
+ "\n"
303 for key
in self
.logSubstitutions
.keys():
304 if line
.find(key
) != -1:
305 value
= self
.logSubstitutions
[key
]
306 value
= value
.replace("%log%", message
)
307 if value
!= "@remove@":
308 result
+= line
.replace(key
, value
) + "\n"
313 result
+= line
+ "\n"
317 def applyCommit(self
, id):
318 if self
.directSubmit
:
319 print "Applying local change in working directory/index"
320 diff
= self
.diffStatus
322 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
323 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
325 filesToDelete
= set()
329 path
= line
[1:].strip()
331 system("p4 edit \"%s\"" % path
)
332 editedFiles
.add(path
)
333 elif modifier
== "A":
335 if path
in filesToDelete
:
336 filesToDelete
.remove(path
)
337 elif modifier
== "D":
338 filesToDelete
.add(path
)
339 if path
in filesToAdd
:
340 filesToAdd
.remove(path
)
342 die("unknown modifier %s for %s" % (modifier
, path
))
344 if self
.directSubmit
:
345 diffcmd
= "cat \"%s\"" % self
.diffFile
347 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
348 patchcmd
= diffcmd
+ " | git apply "
349 tryPatchCmd
= patchcmd
+ "--check -"
350 applyPatchCmd
= patchcmd
+ "--check --apply -"
352 if os
.system(tryPatchCmd
) != 0:
353 print "Unfortunately applying the change failed!"
354 print "What do you want to do?"
356 while response
!= "s" and response
!= "a" and response
!= "w":
357 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
358 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
360 print "Skipping! Good luck with the next patches..."
362 elif response
== "a":
363 os
.system(applyPatchCmd
)
364 if len(filesToAdd
) > 0:
365 print "You may also want to call p4 add on the following files:"
366 print " ".join(filesToAdd
)
367 if len(filesToDelete
):
368 print "The following files should be scheduled for deletion with p4 delete:"
369 print " ".join(filesToDelete
)
370 die("Please resolve and submit the conflict manually and "
371 + "continue afterwards with git-p4 submit --continue")
372 elif response
== "w":
373 system(diffcmd
+ " > patch.txt")
374 print "Patch saved to patch.txt in %s !" % self
.clientPath
375 die("Please resolve and submit the conflict manually and "
376 "continue afterwards with git-p4 submit --continue")
378 system(applyPatchCmd
)
381 system("p4 add %s" % f
)
382 for f
in filesToDelete
:
383 system("p4 revert %s" % f
)
384 system("p4 delete %s" % f
)
387 if not self
.directSubmit
:
388 logMessage
= extractLogMessageFromGitCommit(id)
389 logMessage
= logMessage
.replace("\n", "\n\t")
390 logMessage
= logMessage
.strip()
392 template
= read_pipe("p4 change -o")
395 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
396 diff
= read_pipe("p4 diff -du ...")
398 for newFile
in filesToAdd
:
399 diff
+= "==== new file ====\n"
400 diff
+= "--- /dev/null\n"
401 diff
+= "+++ %s\n" % newFile
402 f
= open(newFile
, "r")
403 for line
in f
.readlines():
407 separatorLine
= "######## everything below this line is just the diff #######"
408 if platform
.system() == "Windows":
409 separatorLine
+= "\r"
410 separatorLine
+= "\n"
413 if self
.trustMeLikeAFool
:
416 firstIteration
= True
417 while response
== "e":
418 if not firstIteration
:
419 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
420 firstIteration
= False
422 [handle
, fileName
] = tempfile
.mkstemp()
423 tmpFile
= os
.fdopen(handle
, "w+")
424 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
427 if platform
.system() == "Windows":
428 defaultEditor
= "notepad"
429 editor
= os
.environ
.get("EDITOR", defaultEditor
);
430 system(editor
+ " " + fileName
)
431 tmpFile
= open(fileName
, "rb")
432 message
= tmpFile
.read()
435 submitTemplate
= message
[:message
.index(separatorLine
)]
437 if response
== "y" or response
== "yes":
440 raw_input("Press return to continue...")
442 if self
.directSubmit
:
443 print "Submitting to git first"
444 os
.chdir(self
.oldWorkingDirectory
)
445 write_pipe("git commit -a -F -", submitTemplate
)
446 os
.chdir(self
.clientPath
)
448 write_pipe("p4 submit -i", submitTemplate
)
449 elif response
== "s":
450 for f
in editedFiles
:
451 system("p4 revert \"%s\"" % f
);
453 system("p4 revert \"%s\"" % f
);
455 for f
in filesToDelete
:
456 system("p4 delete \"%s\"" % f
);
459 print "Not submitting!"
460 self
.interactive
= False
462 fileName
= "submit.txt"
463 file = open(fileName
, "w+")
464 file.write(self
.prepareLogMessage(template
, logMessage
))
466 print ("Perforce submit template written as %s. "
467 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
468 % (fileName
, fileName
))
471 # make gitdir absolute so we can cd out into the perforce checkout
472 os
.environ
["GIT_DIR"] = gitdir
475 self
.master
= currentGitBranch()
476 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
477 die("Detecting current git branch failed!")
479 self
.master
= args
[0]
485 if gitBranchExists("p4"):
486 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
487 if len(depotPath
) == 0 and gitBranchExists("origin"):
488 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
489 depotPaths
= settings
['depot-paths']
491 if len(depotPath
) == 0:
492 print "Internal error: cannot locate perforce depot path from existing branches"
495 self
.clientPath
= p4Where(depotPath
)
497 if len(self
.clientPath
) == 0:
498 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
501 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
502 self
.oldWorkingDirectory
= os
.getcwd()
504 if self
.directSubmit
:
505 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
506 if len(self
.diffStatus
) == 0:
507 print "No changes in working directory to submit."
509 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
510 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
511 f
= open(self
.diffFile
, "wb")
515 os
.chdir(self
.clientPath
)
516 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
517 if response
== "y" or response
== "yes":
518 system("p4 sync ...")
520 if len(self
.origin
) == 0:
521 if gitBranchExists("p4"):
524 self
.origin
= "origin"
527 self
.firstTime
= True
529 if len(self
.substFile
) > 0:
530 for line
in open(self
.substFile
, "r").readlines():
531 tokens
= line
.strip().split("=")
532 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
535 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
536 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
541 commits
= self
.config
.get("commits", [])
543 while len(commits
) > 0:
544 self
.firstTime
= False
546 commits
= commits
[1:]
547 self
.config
["commits"] = commits
548 self
.applyCommit(commit
)
549 if not self
.interactive
:
554 if self
.directSubmit
:
555 os
.remove(self
.diffFile
)
557 if len(commits
) == 0:
559 print "No changes found to apply between %s and current HEAD" % self
.origin
561 print "All changes applied!"
562 os
.chdir(self
.oldWorkingDirectory
)
563 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
564 if response
== "y" or response
== "yes":
567 os
.remove(self
.configFile
)
571 class P4Sync(Command
):
573 Command
.__init
__(self
)
575 optparse
.make_option("--branch", dest
="branch"),
576 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
577 optparse
.make_option("--changesfile", dest
="changesFile"),
578 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
579 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
580 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
581 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
582 optparse
.make_option("--max-changes", dest
="maxChanges"),
583 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true')
585 self
.description
= """Imports from Perforce into a git repository.\n
587 //depot/my/project/ -- to import the current head
588 //depot/my/project/@all -- to import everything
589 //depot/my/project/@1,6 -- to import only from revision 1 to 6
591 (a ... is not needed in the path p4 specification, it's added implicitly)"""
593 self
.usage
+= " //depot/path[@revRange]"
595 self
.createdBranches
= Set()
596 self
.committedChanges
= Set()
598 self
.detectBranches
= False
599 self
.detectLabels
= False
600 self
.changesFile
= ""
601 self
.syncWithOrigin
= True
603 self
.importIntoRemotes
= True
605 self
.isWindows
= (platform
.system() == "Windows")
606 self
.keepRepoPath
= False
607 self
.depotPaths
= None
609 if gitConfig("git-p4.syncFromOrigin") == "false":
610 self
.syncWithOrigin
= False
612 def p4File(self
, depotPath
):
613 return read_pipe("p4 print -q \"%s\"" % depotPath
)
615 def extractFilesFromCommit(self
, commit
):
618 while commit
.has_key("depotFile%s" % fnum
):
619 path
= commit
["depotFile%s" % fnum
]
621 found
= [p
for p
in self
.depotPaths
622 if path
.startswith (p
)]
629 file["rev"] = commit
["rev%s" % fnum
]
630 file["action"] = commit
["action%s" % fnum
]
631 file["type"] = commit
["type%s" % fnum
]
636 def stripRepoPath(self
, path
, prefixes
):
637 if self
.keepRepoPath
:
638 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
641 if path
.startswith(p
):
646 def splitFilesIntoBranches(self
, commit
):
649 while commit
.has_key("depotFile%s" % fnum
):
650 path
= commit
["depotFile%s" % fnum
]
651 found
= [p
for p
in self
.depotPaths
652 if path
.startswith (p
)]
659 file["rev"] = commit
["rev%s" % fnum
]
660 file["action"] = commit
["action%s" % fnum
]
661 file["type"] = commit
["type%s" % fnum
]
664 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
666 for branch
in self
.knownBranches
.keys():
668 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
669 if relPath
.startswith(branch
+ "/"):
670 if branch
not in branches
:
671 branches
[branch
] = []
672 branches
[branch
].append(file)
676 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
677 epoch
= details
["time"]
678 author
= details
["user"]
681 print "commit into %s" % branch
683 self
.gitStream
.write("commit %s\n" % branch
)
684 # gitStream.write("mark :%s\n" % details["change"])
685 self
.committedChanges
.add(int(details
["change"]))
687 if author
not in self
.users
:
688 self
.getUserMapFromPerforceServer()
689 if author
in self
.users
:
690 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
692 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
694 self
.gitStream
.write("committer %s\n" % committer
)
696 self
.gitStream
.write("data <<EOT\n")
697 self
.gitStream
.write(details
["desc"])
698 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
700 % (','.join (branchPrefixes
), details
["change"],
703 self
.gitStream
.write("EOT\n\n")
707 print "parent %s" % parent
708 self
.gitStream
.write("from %s\n" % parent
)
714 if not [p
for p
in branchPrefixes
if path
.startswith(p
)]:
717 depotPath
= path
+ "#" + rev
718 relPath
= self
.stripRepoPath(path
, branchPrefixes
)
719 action
= file["action"]
721 if file["type"] == "apple":
722 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
725 if action
== "delete":
726 self
.gitStream
.write("D %s\n" % relPath
)
729 if file["type"].startswith("x"):
732 data
= self
.p4File(depotPath
)
734 if self
.isWindows
and file["type"].endswith("text"):
735 data
= data
.replace("\r\n", "\n")
737 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
738 self
.gitStream
.write("data %s\n" % len(data
))
739 self
.gitStream
.write(data
)
740 self
.gitStream
.write("\n")
742 self
.gitStream
.write("\n")
744 change
= int(details
["change"])
746 if self
.labels
.has_key(change
):
747 label
= self
.labels
[change
]
748 labelDetails
= label
[0]
749 labelRevisions
= label
[1]
751 print "Change %s is labelled %s" % (change
, labelDetails
)
753 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
754 for p
in branchPrefixes
]))
756 if len(files
) == len(labelRevisions
):
760 if info
["action"] == "delete":
762 cleanedFiles
[info
["depotFile"]] = info
["rev"]
764 if cleanedFiles
== labelRevisions
:
765 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
766 self
.gitStream
.write("from %s\n" % branch
)
768 owner
= labelDetails
["Owner"]
770 if author
in self
.users
:
771 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
773 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
774 self
.gitStream
.write("tagger %s\n" % tagger
)
775 self
.gitStream
.write("data <<EOT\n")
776 self
.gitStream
.write(labelDetails
["Description"])
777 self
.gitStream
.write("EOT\n\n")
781 print ("Tag %s does not match with change %s: files do not match."
782 % (labelDetails
["label"], change
))
786 print ("Tag %s does not match with change %s: file count is different."
787 % (labelDetails
["label"], change
))
789 def getUserMapFromPerforceServer(self
):
790 if self
.userMapFromPerforceServer
:
794 for output
in p4CmdList("users"):
795 if not output
.has_key("User"):
797 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
799 cache
= open(self
.gitdir
+ "/p4-usercache.txt", "wb")
800 for user
in self
.users
.keys():
801 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
803 self
.userMapFromPerforceServer
= True
805 def loadUserMapFromCache(self
):
807 self
.userMapFromPerforceServer
= False
809 cache
= open(self
.gitdir
+ "/p4-usercache.txt", "rb")
810 lines
= cache
.readlines()
813 entry
= line
.strip().split("\t")
814 self
.users
[entry
[0]] = entry
[1]
816 self
.getUserMapFromPerforceServer()
821 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
822 if len(l
) > 0 and not self
.silent
:
823 print "Finding files belonging to labels in %s" % `self
.depotPath`
826 label
= output
["label"]
830 print "Querying files for label %s" % label
831 for file in p4CmdList("files "
832 + ' '.join (["%s...@%s" % (p
, label
)
833 for p
in self
.depotPaths
])):
834 revisions
[file["depotFile"]] = file["rev"]
835 change
= int(file["change"])
836 if change
> newestChange
:
837 newestChange
= change
839 self
.labels
[newestChange
] = [output
, revisions
]
842 print "Label changes: %s" % self
.labels
.keys()
844 def getBranchMapping(self
):
846 ## FIXME - what's a P4 projectName ?
847 self
.projectName
= self
.depotPath
[self
.depotPath
.strip().rfind("/") + 1:]
849 for info
in p4CmdList("branches"):
850 details
= p4Cmd("branch -o %s" % info
["branch"])
852 while details
.has_key("View%s" % viewIdx
):
853 paths
= details
["View%s" % viewIdx
].split(" ")
854 viewIdx
= viewIdx
+ 1
855 # require standard //depot/foo/... //depot/bar/... mapping
856 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
859 destination
= paths
[1]
860 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
861 source
= source
[len(self
.depotPath
):-4]
862 destination
= destination
[len(self
.depotPath
):-4]
863 if destination
not in self
.knownBranches
:
864 self
.knownBranches
[destination
] = source
865 if source
not in self
.knownBranches
:
866 self
.knownBranches
[source
] = source
868 def listExistingP4GitBranches(self
):
869 self
.p4BranchesInGit
= []
871 cmdline
= "git rev-parse --symbolic "
872 if self
.importIntoRemotes
:
873 cmdline
+= " --remotes"
875 cmdline
+= " --branches"
877 for line
in read_pipe_lines(cmdline
):
879 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD"):
882 if self
.importIntoRemotes
:
884 branch
= re
.sub ("^p4/", "", line
)
886 self
.p4BranchesInGit
.append(branch
)
887 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
889 def createOrUpdateBranchesFromOrigin(self
):
891 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
893 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
895 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
898 headName
= line
[len("origin/"):]
899 remoteHead
= self
.refPrefix
+ headName
900 originHead
= "origin/" + headName
902 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
903 if (not original
.has_key('depot-paths')
904 or not original
.has_key('change')):
908 if not gitBranchExists(remoteHead
):
910 print "creating %s" % remoteHead
913 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
914 if settings
.has_key('change') > 0:
915 if settings
['depot-paths'] == original
['depot-paths']:
916 originP4Change
= int(original
['change'])
917 p4Change
= int(settings
['change'])
918 if originP4Change
> p4Change
:
919 print ("%s (%s) is newer than %s (%s). "
920 "Updating p4 branch from origin."
921 % (originHead
, originP4Change
,
922 remoteHead
, p4Change
))
925 print ("Ignoring: %s was imported from %s while "
926 "%s was imported from %s"
927 % (originHead
, ','.join(original
['depot-paths']),
928 remoteHead
, ','.join(settings
['depot-paths'])))
931 system("git update-ref %s %s" % (remoteHead
, originHead
))
933 def updateOptionDict(self
, d
):
935 if self
.keepRepoPath
:
936 option_keys
['keepRepoPath'] = 1
938 d
["options"] = ' '.join(sorted(option_keys
.keys()))
940 def readOptions(self
, d
):
941 self
.keepRepoPath
= (d
.has_key('options')
942 and ('keepRepoPath' in d
['options']))
946 self
.changeRange
= ""
947 self
.initialParent
= ""
948 self
.previousDepotPaths
= []
950 # map from branch depot path to parent branch
951 self
.knownBranches
= {}
952 self
.initialParents
= {}
953 self
.hasOrigin
= gitBranchExists("origin")
955 if self
.importIntoRemotes
:
956 self
.refPrefix
= "refs/remotes/p4/"
958 self
.refPrefix
= "refs/heads/"
960 if self
.syncWithOrigin
and self
.hasOrigin
:
962 print "Syncing with origin first by calling git fetch origin"
963 system("git fetch origin")
965 if len(self
.branch
) == 0:
966 self
.branch
= self
.refPrefix
+ "master"
967 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
968 system("git update-ref %s refs/heads/p4" % self
.branch
)
969 system("git branch -D p4");
970 # create it /after/ importing, when master exists
971 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
972 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
977 self
.createOrUpdateBranchesFromOrigin()
978 self
.listExistingP4GitBranches()
980 if len(self
.p4BranchesInGit
) > 1:
982 print "Importing from/into multiple branches"
983 self
.detectBranches
= True
986 print "branches: %s" % self
.p4BranchesInGit
989 for branch
in self
.p4BranchesInGit
:
990 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
992 settings
= extractSettingsGitLog(logMsg
)
995 print "path %s change %s" % (','.join(depotPaths
), change
)
997 self
.readOptions(settings
)
998 if (settings
.has_key('depot-paths')
999 and settings
.has_key ('change')):
1000 change
= int(settings
['change']) + 1
1001 p4Change
= max(p4Change
, change
)
1003 depotPaths
= sorted(settings
['depot-paths'])
1004 if self
.previousDepotPaths
== []:
1005 self
.previousDepotPaths
= depotPaths
1008 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1009 for i
in range(0, max(len(cur
), len(prev
))):
1010 if cur
[i
] <> prev
[i
]:
1013 paths
.append (cur
[:i
])
1015 self
.previousDepotPaths
= paths
1018 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1019 self
.changeRange
= "@%s,#head" % p4Change
1020 self
.initialParent
= parseRevision(self
.branch
)
1021 if not self
.silent
and not self
.detectBranches
:
1022 print "Performing incremental import into %s git branch" % self
.branch
1024 if not self
.branch
.startswith("refs/"):
1025 self
.branch
= "refs/heads/" + self
.branch
1027 if len(args
) == 0 and self
.depotPaths
:
1029 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1031 if self
.depotPaths
and self
.depotPaths
!= args
:
1032 print ("previous import used depot path %s and now %s was specified. "
1033 "This doesn't work!" % (' '.join (self
.depotPaths
),
1037 self
.depotPaths
= sorted(args
)
1043 for p
in self
.depotPaths
:
1044 if p
.find("@") != -1:
1045 atIdx
= p
.index("@")
1046 self
.changeRange
= p
[atIdx
:]
1047 if self
.changeRange
== "@all":
1048 self
.changeRange
= ""
1049 elif self
.changeRange
.find(",") == -1:
1050 self
.revision
= self
.changeRange
1051 self
.changeRange
= ""
1053 elif p
.find("#") != -1:
1054 hashIdx
= p
.index("#")
1055 self
.revision
= p
[hashIdx
:]
1057 elif self
.previousDepotPaths
== []:
1058 self
.revision
= "#head"
1060 p
= re
.sub ("\.\.\.$", "", p
)
1061 if not p
.endswith("/"):
1066 self
.depotPaths
= newPaths
1069 self
.loadUserMapFromCache()
1071 if self
.detectLabels
:
1074 if self
.detectBranches
:
1075 self
.getBranchMapping();
1077 print "p4-git branches: %s" % self
.p4BranchesInGit
1078 print "initial parents: %s" % self
.initialParents
1079 for b
in self
.p4BranchesInGit
:
1083 b
= b
[len(self
.projectName
):]
1084 self
.createdBranches
.add(b
)
1086 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1088 importProcess
= subprocess
.Popen(["git", "fast-import"],
1089 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1090 stderr
=subprocess
.PIPE
);
1091 self
.gitOutput
= importProcess
.stdout
1092 self
.gitStream
= importProcess
.stdin
1093 self
.gitError
= importProcess
.stderr
1095 if len(self
.revision
) > 0:
1096 print "Doing initial import of %s from revision %s" % (' '.join(self
.depotPaths
), self
.revision
)
1098 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1099 details
["desc"] = ("Initial import of %s from the state at revision %s"
1100 % (' '.join(self
.depotPaths
), self
.revision
))
1101 details
["change"] = self
.revision
1105 for info
in p4CmdList("files "
1106 + ' '.join(["%s...%s"
1107 % (p
, self
.revision
)
1108 for p
in self
.depotPaths
])):
1109 change
= int(info
["change"])
1110 if change
> newestRevision
:
1111 newestRevision
= change
1113 if info
["action"] == "delete":
1114 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1115 #fileCnt = fileCnt + 1
1118 for prop
in [ "depotFile", "rev", "action", "type" ]:
1119 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1121 fileCnt
= fileCnt
+ 1
1123 details
["change"] = newestRevision
1124 self
.updateOptionDict(details
)
1126 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1128 print "IO error with git fast-import. Is your git version recent enough?"
1129 print self
.gitError
.read()
1134 if len(self
.changesFile
) > 0:
1135 output
= open(self
.changesFile
).readlines()
1138 changeSet
.add(int(line
))
1140 for change
in changeSet
:
1141 changes
.append(change
)
1146 print "Getting p4 changes for %s...%s" % (`self
.depotPaths`
,
1148 assert self
.depotPaths
1149 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1150 for p
in self
.depotPaths
]))
1153 changeNum
= line
.split(" ")[1]
1154 changes
.append(changeNum
)
1158 if len(self
.maxChanges
) > 0:
1159 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1161 if len(changes
) == 0:
1163 print "No changes to import!"
1166 self
.updatedBranches
= set()
1169 for change
in changes
:
1170 description
= p4Cmd("describe %s" % change
)
1171 self
.updateOptionDict(description
)
1174 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1179 if self
.detectBranches
:
1180 branches
= self
.splitFilesIntoBranches(description
)
1181 for branch
in branches
.keys():
1183 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1187 filesForCommit
= branches
[branch
]
1190 print "branch is %s" % branch
1192 self
.updatedBranches
.add(branch
)
1194 if branch
not in self
.createdBranches
:
1195 self
.createdBranches
.add(branch
)
1196 parent
= self
.knownBranches
[branch
]
1197 if parent
== branch
:
1200 print "parent determined through known branches: %s" % parent
1202 # main branch? use master
1203 if branch
== "main":
1208 branch
= self
.projectName
+ branch
1210 if parent
== "main":
1212 elif len(parent
) > 0:
1214 parent
= self
.projectName
+ parent
1216 branch
= self
.refPrefix
+ branch
1218 parent
= self
.refPrefix
+ parent
1221 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1223 if len(parent
) == 0 and branch
in self
.initialParents
:
1224 parent
= self
.initialParents
[branch
]
1225 del self
.initialParents
[branch
]
1227 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1229 files
= self
.extractFilesFromCommit(description
)
1230 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1232 self
.initialParent
= ""
1234 print self
.gitError
.read()
1239 if len(self
.updatedBranches
) > 0:
1240 sys
.stdout
.write("Updated branches: ")
1241 for b
in self
.updatedBranches
:
1242 sys
.stdout
.write("%s " % b
)
1243 sys
.stdout
.write("\n")
1246 self
.gitStream
.close()
1247 if importProcess
.wait() != 0:
1248 die("fast-import failed: %s" % self
.gitError
.read())
1249 self
.gitOutput
.close()
1250 self
.gitError
.close()
1254 class P4Rebase(Command
):
1256 Command
.__init
__(self
)
1258 self
.description
= ("Fetches the latest revision from perforce and "
1259 + "rebases the current work (branch) against it")
1261 def run(self
, args
):
1264 print "Rebasing the current branch"
1265 oldHead
= read_pipe("git rev-parse HEAD").strip()
1266 system("git rebase p4")
1267 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1270 class P4Clone(P4Sync
):
1272 P4Sync
.__init
__(self
)
1273 self
.description
= "Creates a new git repository and imports from Perforce into it"
1274 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1275 self
.options
.append(
1276 optparse
.make_option("--destination", dest
="cloneDestination",
1277 action
='store', default
=None,
1278 help="where to leave result of the clone"))
1279 self
.cloneDestination
= None
1280 self
.needsGit
= False
1282 def run(self
, args
):
1286 if self
.keepRepoPath
and not self
.cloneDestination
:
1287 sys
.stderr
.write("Must specify destination for --keep-path\n")
1291 for p
in depotPaths
:
1292 if not p
.startswith("//"):
1295 if not self
.cloneDestination
:
1297 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1298 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1299 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1300 depotDir
= re
.sub(r
"/$", "", depotDir
)
1302 self
.cloneDestination
= os
.path
.split(depotDir
)[1]
1304 print "Importing from %s into %s" % (`depotPaths`
, self
.cloneDestination
)
1305 os
.makedirs(self
.cloneDestination
)
1306 os
.chdir(self
.cloneDestination
)
1308 self
.gitdir
= os
.getcwd() + "/.git"
1309 if not P4Sync
.run(self
, depotPaths
):
1311 if self
.branch
!= "master":
1312 if gitBranchExists("refs/remotes/p4/master"):
1313 system("git branch master refs/remotes/p4/master")
1314 system("git checkout -f")
1316 print "Could not detect main branch. No checkout/master branch created."
1319 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1321 optparse
.IndentedHelpFormatter
.__init
__(self
)
1323 def format_description(self
, description
):
1325 return description
+ "\n"
1329 def printUsage(commands
):
1330 print "usage: %s <command> [options]" % sys
.argv
[0]
1332 print "valid commands: %s" % ", ".join(commands
)
1334 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1339 "submit" : P4Submit
,
1341 "rebase" : P4Rebase
,
1343 "rollback" : P4RollBack
1348 if len(sys
.argv
[1:]) == 0:
1349 printUsage(commands
.keys())
1353 cmdName
= sys
.argv
[1]
1355 klass
= commands
[cmdName
]
1358 print "unknown command %s" % cmdName
1360 printUsage(commands
.keys())
1363 options
= cmd
.options
1364 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1368 if len(options
) > 0:
1369 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1371 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1373 description
= cmd
.description
,
1374 formatter
= HelpFormatter())
1376 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1378 verbose
= cmd
.verbose
1380 if cmd
.gitdir
== None:
1381 cmd
.gitdir
= os
.path
.abspath(".git")
1382 if not isValidGitDir(cmd
.gitdir
):
1383 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1384 if os
.path
.exists(cmd
.gitdir
):
1385 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1389 if not isValidGitDir(cmd
.gitdir
):
1390 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1391 cmd
.gitdir
+= "/.git"
1393 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1395 os
.environ
["GIT_DIR"] = cmd
.gitdir
1397 if not cmd
.run(args
):
1401 if __name__
== '__main__':