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
23 sys
.stderr
.write(msg
+ "\n")
26 def write_pipe(c
, str):
28 sys
.stderr
.write('Writing pipe: %s\n' % c
)
30 pipe
= os
.popen(c
, 'w')
33 die('Command failed: %s' % c
)
37 def read_pipe(c
, ignore_error
=False):
39 sys
.stderr
.write('Reading pipe: %s\n' % c
)
41 pipe
= os
.popen(c
, 'rb')
43 if pipe
.close() and not ignore_error
:
44 die('Command failed: %s' % c
)
49 def read_pipe_lines(c
):
51 sys
.stderr
.write('Reading pipe: %s\n' % c
)
52 ## todo: check return status
53 pipe
= os
.popen(c
, 'rb')
54 val
= pipe
.readlines()
56 die('Command failed: %s' % c
)
62 sys
.stderr
.write("executing %s\n" % cmd
)
63 if os
.system(cmd
) != 0:
64 die("command failed: %s" % cmd
)
67 """Determine if a Perforce 'kind' should have execute permission
69 'p4 help filetypes' gives a list of the types. If it starts with 'x',
70 or x follows one of a few letters. Otherwise, if there is an 'x' after
71 a plus sign, it is also executable"""
72 return (re
.search(r
"(^[cku]?x)|\+.*x", kind
) != None)
74 def p4CmdList(cmd
, stdin
=None, stdin_mode
='w+b'):
75 cmd
= "p4 -G %s" % cmd
77 sys
.stderr
.write("Opening pipe: %s\n" % cmd
)
79 # Use a temporary file to avoid deadlocks without
80 # subprocess.communicate(), which would put another copy
81 # of stdout into memory.
84 stdin_file
= tempfile
.TemporaryFile(prefix
='p4-stdin', mode
=stdin_mode
)
85 stdin_file
.write(stdin
)
89 p4
= subprocess
.Popen(cmd
, shell
=True,
91 stdout
=subprocess
.PIPE
)
96 entry
= marshal
.load(p4
.stdout
)
103 entry
["p4ExitCode"] = exitCode
109 list = p4CmdList(cmd
)
115 def p4Where(depotPath
):
116 if not depotPath
.endswith("/"):
118 output
= p4Cmd("where %s..." % depotPath
)
119 if output
["code"] == "error":
123 clientPath
= output
.get("path")
124 elif "data" in output
:
125 data
= output
.get("data")
126 lastSpace
= data
.rfind(" ")
127 clientPath
= data
[lastSpace
+ 1:]
129 if clientPath
.endswith("..."):
130 clientPath
= clientPath
[:-3]
133 def currentGitBranch():
134 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
136 def isValidGitDir(path
):
137 if (os
.path
.exists(path
+ "/HEAD")
138 and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects")):
142 def parseRevision(ref
):
143 return read_pipe("git rev-parse %s" % ref
).strip()
145 def extractLogMessageFromGitCommit(commit
):
148 ## fixme: title is first line of commit, not 1st paragraph.
150 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
159 def extractSettingsGitLog(log
):
161 for line
in log
.split("\n"):
163 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
167 assignments
= m
.group(1).split (':')
168 for a
in assignments
:
170 key
= vals
[0].strip()
171 val
= ('='.join (vals
[1:])).strip()
172 if val
.endswith ('\"') and val
.startswith('"'):
177 paths
= values
.get("depot-paths")
179 paths
= values
.get("depot-path")
181 values
['depot-paths'] = paths
.split(',')
184 def gitBranchExists(branch
):
185 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
186 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
187 return proc
.wait() == 0;
190 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
192 def p4BranchesInGit(branchesAreInRemotes
= True):
195 cmdline
= "git rev-parse --symbolic "
196 if branchesAreInRemotes
:
197 cmdline
+= " --remotes"
199 cmdline
+= " --branches"
201 for line
in read_pipe_lines(cmdline
):
204 ## only import to p4/
205 if not line
.startswith('p4/') or line
== "p4/HEAD":
210 branch
= re
.sub ("^p4/", "", line
)
212 branches
[branch
] = parseRevision(line
)
215 def findUpstreamBranchPoint(head
= "HEAD"):
216 branches
= p4BranchesInGit()
217 # map from depot-path to branch name
218 branchByDepotPath
= {}
219 for branch
in branches
.keys():
220 tip
= branches
[branch
]
221 log
= extractLogMessageFromGitCommit(tip
)
222 settings
= extractSettingsGitLog(log
)
223 if settings
.has_key("depot-paths"):
224 paths
= ",".join(settings
["depot-paths"])
225 branchByDepotPath
[paths
] = "remotes/p4/" + branch
229 while parent
< 65535:
230 commit
= head
+ "~%s" % parent
231 log
= extractLogMessageFromGitCommit(commit
)
232 settings
= extractSettingsGitLog(log
)
233 if settings
.has_key("depot-paths"):
234 paths
= ",".join(settings
["depot-paths"])
235 if branchByDepotPath
.has_key(paths
):
236 return [branchByDepotPath
[paths
], settings
]
240 return ["", settings
]
242 def createOrUpdateBranchesFromOrigin(localRefPrefix
= "refs/remotes/p4/", silent
=True):
244 print ("Creating/updating branch(es) in %s based on origin branch(es)"
247 originPrefix
= "origin/p4/"
249 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
251 if (not line
.startswith(originPrefix
)) or line
.endswith("HEAD"):
254 headName
= line
[len(originPrefix
):]
255 remoteHead
= localRefPrefix
+ headName
258 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
259 if (not original
.has_key('depot-paths')
260 or not original
.has_key('change')):
264 if not gitBranchExists(remoteHead
):
266 print "creating %s" % remoteHead
269 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
270 if settings
.has_key('change') > 0:
271 if settings
['depot-paths'] == original
['depot-paths']:
272 originP4Change
= int(original
['change'])
273 p4Change
= int(settings
['change'])
274 if originP4Change
> p4Change
:
275 print ("%s (%s) is newer than %s (%s). "
276 "Updating p4 branch from origin."
277 % (originHead
, originP4Change
,
278 remoteHead
, p4Change
))
281 print ("Ignoring: %s was imported from %s while "
282 "%s was imported from %s"
283 % (originHead
, ','.join(original
['depot-paths']),
284 remoteHead
, ','.join(settings
['depot-paths'])))
287 system("git update-ref %s %s" % (remoteHead
, originHead
))
289 def originP4BranchesExist():
290 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
294 self
.usage
= "usage: %prog [options]"
297 class P4Debug(Command
):
299 Command
.__init
__(self
)
301 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
304 self
.description
= "A tool to debug the output of p4 -G."
305 self
.needsGit
= False
310 for output
in p4CmdList(" ".join(args
)):
311 print 'Element: %d' % j
316 class P4RollBack(Command
):
318 Command
.__init
__(self
)
320 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
321 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
323 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
325 self
.rollbackLocalBranches
= False
330 maxChange
= int(args
[0])
332 if "p4ExitCode" in p4Cmd("changes -m 1"):
333 die("Problems executing p4");
335 if self
.rollbackLocalBranches
:
336 refPrefix
= "refs/heads/"
337 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
339 refPrefix
= "refs/remotes/"
340 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
343 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
345 ref
= refPrefix
+ line
346 log
= extractLogMessageFromGitCommit(ref
)
347 settings
= extractSettingsGitLog(log
)
349 depotPaths
= settings
['depot-paths']
350 change
= settings
['change']
354 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
355 for p
in depotPaths
]))) == 0:
356 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
357 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
360 while change
and int(change
) > maxChange
:
363 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
364 system("git update-ref %s \"%s^\"" % (ref
, ref
))
365 log
= extractLogMessageFromGitCommit(ref
)
366 settings
= extractSettingsGitLog(log
)
369 depotPaths
= settings
['depot-paths']
370 change
= settings
['change']
373 print "%s rewound to %s" % (ref
, change
)
377 class P4Submit(Command
):
379 Command
.__init
__(self
)
381 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
382 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
383 optparse
.make_option("--origin", dest
="origin"),
384 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
385 optparse
.make_option("--log-substitutions", dest
="substFile"),
386 optparse
.make_option("--dry-run", action
="store_true"),
387 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
388 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
390 self
.description
= "Submit changes from git to the perforce depot."
391 self
.usage
+= " [name of git branch to submit into perforce depot]"
392 self
.firstTime
= True
394 self
.interactive
= True
397 self
.firstTime
= True
399 self
.directSubmit
= False
400 self
.trustMeLikeAFool
= False
402 self
.isWindows
= (platform
.system() == "Windows")
404 self
.logSubstitutions
= {}
405 self
.logSubstitutions
["<enter description here>"] = "%log%"
406 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
409 if len(p4CmdList("opened ...")) > 0:
410 die("You have files opened with perforce! Close them before starting the sync.")
413 if len(self
.config
) > 0 and not self
.reset
:
414 die("Cannot start sync. Previous sync config found at %s\n"
415 "If you want to start submitting again from scratch "
416 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
419 if self
.directSubmit
:
422 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
423 commits
.append(line
.strip())
426 self
.config
["commits"] = commits
428 def prepareLogMessage(self
, template
, message
):
431 for line
in template
.split("\n"):
432 if line
.startswith("#"):
433 result
+= line
+ "\n"
437 for key
in self
.logSubstitutions
.keys():
438 if line
.find(key
) != -1:
439 value
= self
.logSubstitutions
[key
]
440 value
= value
.replace("%log%", message
)
441 if value
!= "@remove@":
442 result
+= line
.replace(key
, value
) + "\n"
447 result
+= line
+ "\n"
451 def prepareSubmitTemplate(self
):
452 # remove lines in the Files section that show changes to files outside the depot path we're committing into
454 inFilesSection
= False
455 for line
in read_pipe_lines("p4 change -o"):
457 if line
.startswith("\t"):
458 # path starts and ends with a tab
460 lastTab
= path
.rfind("\t")
462 path
= path
[:lastTab
]
463 if not path
.startswith(self
.depotPath
):
466 inFilesSection
= False
468 if line
.startswith("Files:"):
469 inFilesSection
= True
475 def applyCommit(self
, id):
476 if self
.directSubmit
:
477 print "Applying local change in working directory/index"
478 diff
= self
.diffStatus
480 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
481 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
483 filesToDelete
= set()
487 path
= line
[1:].strip()
489 system("p4 edit \"%s\"" % path
)
490 editedFiles
.add(path
)
491 elif modifier
== "A":
493 if path
in filesToDelete
:
494 filesToDelete
.remove(path
)
495 elif modifier
== "D":
496 filesToDelete
.add(path
)
497 if path
in filesToAdd
:
498 filesToAdd
.remove(path
)
500 die("unknown modifier %s for %s" % (modifier
, path
))
502 if self
.directSubmit
:
503 diffcmd
= "cat \"%s\"" % self
.diffFile
505 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
506 patchcmd
= diffcmd
+ " | git apply "
507 tryPatchCmd
= patchcmd
+ "--check -"
508 applyPatchCmd
= patchcmd
+ "--check --apply -"
510 if os
.system(tryPatchCmd
) != 0:
511 print "Unfortunately applying the change failed!"
512 print "What do you want to do?"
514 while response
!= "s" and response
!= "a" and response
!= "w":
515 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
516 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
518 print "Skipping! Good luck with the next patches..."
520 elif response
== "a":
521 os
.system(applyPatchCmd
)
522 if len(filesToAdd
) > 0:
523 print "You may also want to call p4 add on the following files:"
524 print " ".join(filesToAdd
)
525 if len(filesToDelete
):
526 print "The following files should be scheduled for deletion with p4 delete:"
527 print " ".join(filesToDelete
)
528 die("Please resolve and submit the conflict manually and "
529 + "continue afterwards with git-p4 submit --continue")
530 elif response
== "w":
531 system(diffcmd
+ " > patch.txt")
532 print "Patch saved to patch.txt in %s !" % self
.clientPath
533 die("Please resolve and submit the conflict manually and "
534 "continue afterwards with git-p4 submit --continue")
536 system(applyPatchCmd
)
539 system("p4 add \"%s\"" % f
)
540 for f
in filesToDelete
:
541 system("p4 revert \"%s\"" % f
)
542 system("p4 delete \"%s\"" % f
)
545 if not self
.directSubmit
:
546 logMessage
= extractLogMessageFromGitCommit(id)
547 logMessage
= logMessage
.replace("\n", "\n\t")
549 logMessage
= logMessage
.replace("\n", "\r\n")
550 logMessage
= logMessage
.strip()
552 template
= self
.prepareSubmitTemplate()
555 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
556 diff
= read_pipe("p4 diff -du ...")
558 for newFile
in filesToAdd
:
559 diff
+= "==== new file ====\n"
560 diff
+= "--- /dev/null\n"
561 diff
+= "+++ %s\n" % newFile
562 f
= open(newFile
, "r")
563 for line
in f
.readlines():
567 separatorLine
= "######## everything below this line is just the diff #######"
568 if platform
.system() == "Windows":
569 separatorLine
+= "\r"
570 separatorLine
+= "\n"
573 if self
.trustMeLikeAFool
:
576 firstIteration
= True
577 while response
== "e":
578 if not firstIteration
:
579 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
580 firstIteration
= False
582 [handle
, fileName
] = tempfile
.mkstemp()
583 tmpFile
= os
.fdopen(handle
, "w+")
584 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
587 if platform
.system() == "Windows":
588 defaultEditor
= "notepad"
589 editor
= os
.environ
.get("EDITOR", defaultEditor
);
590 system(editor
+ " " + fileName
)
591 tmpFile
= open(fileName
, "rb")
592 message
= tmpFile
.read()
595 submitTemplate
= message
[:message
.index(separatorLine
)]
597 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
599 if response
== "y" or response
== "yes":
602 raw_input("Press return to continue...")
604 if self
.directSubmit
:
605 print "Submitting to git first"
606 os
.chdir(self
.oldWorkingDirectory
)
607 write_pipe("git commit -a -F -", submitTemplate
)
608 os
.chdir(self
.clientPath
)
610 write_pipe("p4 submit -i", submitTemplate
)
611 elif response
== "s":
612 for f
in editedFiles
:
613 system("p4 revert \"%s\"" % f
);
615 system("p4 revert \"%s\"" % f
);
617 for f
in filesToDelete
:
618 system("p4 delete \"%s\"" % f
);
621 print "Not submitting!"
622 self
.interactive
= False
624 fileName
= "submit.txt"
625 file = open(fileName
, "w+")
626 file.write(self
.prepareLogMessage(template
, logMessage
))
628 print ("Perforce submit template written as %s. "
629 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
630 % (fileName
, fileName
))
634 self
.master
= currentGitBranch()
635 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
636 die("Detecting current git branch failed!")
638 self
.master
= args
[0]
642 [upstream
, settings
] = findUpstreamBranchPoint()
643 self
.depotPath
= settings
['depot-paths'][0]
644 if len(self
.origin
) == 0:
645 self
.origin
= upstream
648 print "Origin branch is " + self
.origin
650 if len(self
.depotPath
) == 0:
651 print "Internal error: cannot locate perforce depot path from existing branches"
654 self
.clientPath
= p4Where(self
.depotPath
)
656 if len(self
.clientPath
) == 0:
657 print "Error: Cannot locate perforce checkout of %s in client view" % self
.depotPath
660 print "Perforce checkout for depot path %s located at %s" % (self
.depotPath
, self
.clientPath
)
661 self
.oldWorkingDirectory
= os
.getcwd()
663 if self
.directSubmit
:
664 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
665 if len(self
.diffStatus
) == 0:
666 print "No changes in working directory to submit."
668 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
669 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
670 f
= open(self
.diffFile
, "wb")
674 os
.chdir(self
.clientPath
)
675 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
676 if response
== "y" or response
== "yes":
677 system("p4 sync ...")
680 self
.firstTime
= True
682 if len(self
.substFile
) > 0:
683 for line
in open(self
.substFile
, "r").readlines():
684 tokens
= line
.strip().split("=")
685 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
688 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
689 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
694 commits
= self
.config
.get("commits", [])
696 while len(commits
) > 0:
697 self
.firstTime
= False
699 commits
= commits
[1:]
700 self
.config
["commits"] = commits
701 self
.applyCommit(commit
)
702 if not self
.interactive
:
707 if self
.directSubmit
:
708 os
.remove(self
.diffFile
)
710 if len(commits
) == 0:
712 print "No changes found to apply between %s and current HEAD" % self
.origin
714 print "All changes applied!"
715 os
.chdir(self
.oldWorkingDirectory
)
716 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
717 if response
== "y" or response
== "yes":
720 os
.remove(self
.configFile
)
724 class P4Sync(Command
):
726 Command
.__init
__(self
)
728 optparse
.make_option("--branch", dest
="branch"),
729 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
730 optparse
.make_option("--changesfile", dest
="changesFile"),
731 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
732 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
733 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
734 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
735 help="Import into refs/heads/ , not refs/remotes"),
736 optparse
.make_option("--max-changes", dest
="maxChanges"),
737 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
738 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
740 self
.description
= """Imports from Perforce into a git repository.\n
742 //depot/my/project/ -- to import the current head
743 //depot/my/project/@all -- to import everything
744 //depot/my/project/@1,6 -- to import only from revision 1 to 6
746 (a ... is not needed in the path p4 specification, it's added implicitly)"""
748 self
.usage
+= " //depot/path[@revRange]"
750 self
.createdBranches
= Set()
751 self
.committedChanges
= Set()
753 self
.detectBranches
= False
754 self
.detectLabels
= False
755 self
.changesFile
= ""
756 self
.syncWithOrigin
= True
758 self
.importIntoRemotes
= True
760 self
.isWindows
= (platform
.system() == "Windows")
761 self
.keepRepoPath
= False
762 self
.depotPaths
= None
763 self
.p4BranchesInGit
= []
765 if gitConfig("git-p4.syncFromOrigin") == "false":
766 self
.syncWithOrigin
= False
768 def extractFilesFromCommit(self
, commit
):
771 while commit
.has_key("depotFile%s" % fnum
):
772 path
= commit
["depotFile%s" % fnum
]
774 found
= [p
for p
in self
.depotPaths
775 if path
.startswith (p
)]
782 file["rev"] = commit
["rev%s" % fnum
]
783 file["action"] = commit
["action%s" % fnum
]
784 file["type"] = commit
["type%s" % fnum
]
789 def stripRepoPath(self
, path
, prefixes
):
790 if self
.keepRepoPath
:
791 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
794 if path
.startswith(p
):
799 def splitFilesIntoBranches(self
, commit
):
802 while commit
.has_key("depotFile%s" % fnum
):
803 path
= commit
["depotFile%s" % fnum
]
804 found
= [p
for p
in self
.depotPaths
805 if path
.startswith (p
)]
812 file["rev"] = commit
["rev%s" % fnum
]
813 file["action"] = commit
["action%s" % fnum
]
814 file["type"] = commit
["type%s" % fnum
]
817 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
819 for branch
in self
.knownBranches
.keys():
821 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
822 if relPath
.startswith(branch
+ "/"):
823 if branch
not in branches
:
824 branches
[branch
] = []
825 branches
[branch
].append(file)
830 ## Should move this out, doesn't use SELF.
831 def readP4Files(self
, files
):
832 files
= [f
for f
in files
833 if f
['action'] != 'delete']
838 filedata
= p4CmdList('-x - print',
839 stdin
='\n'.join(['%s#%s' % (f
['path'], f
['rev'])
842 if "p4ExitCode" in filedata
[0]:
843 die("Problems executing p4. Error: [%d]."
844 % (filedata
[0]['p4ExitCode']));
848 while j
< len(filedata
):
852 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
854 text
+= filedata
[j
]['data']
858 if not stat
.has_key('depotFile'):
859 sys
.stderr
.write("p4 print fails with: %s\n" % repr(stat
))
862 contents
[stat
['depotFile']] = text
865 assert not f
.has_key('data')
866 f
['data'] = contents
[f
['path']]
868 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
869 epoch
= details
["time"]
870 author
= details
["user"]
873 print "commit into %s" % branch
875 # start with reading files; if that fails, we should not
879 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
882 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
884 self
.readP4Files(files
)
889 self
.gitStream
.write("commit %s\n" % branch
)
890 # gitStream.write("mark :%s\n" % details["change"])
891 self
.committedChanges
.add(int(details
["change"]))
893 if author
not in self
.users
:
894 self
.getUserMapFromPerforceServer()
895 if author
in self
.users
:
896 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
898 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
900 self
.gitStream
.write("committer %s\n" % committer
)
902 self
.gitStream
.write("data <<EOT\n")
903 self
.gitStream
.write(details
["desc"])
904 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s"
905 % (','.join (branchPrefixes
), details
["change"]))
906 if len(details
['options']) > 0:
907 self
.gitStream
.write(": options = %s" % details
['options'])
908 self
.gitStream
.write("]\nEOT\n\n")
912 print "parent %s" % parent
913 self
.gitStream
.write("from %s\n" % parent
)
916 if file["type"] == "apple":
917 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
920 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
921 if file["action"] == "delete":
922 self
.gitStream
.write("D %s\n" % relPath
)
927 if isP4Exec(file["type"]):
929 elif file["type"] == "symlink":
931 # p4 print on a symlink contains "target\n", so strip it off
934 if self
.isWindows
and file["type"].endswith("text"):
935 data
= data
.replace("\r\n", "\n")
937 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
938 self
.gitStream
.write("data %s\n" % len(data
))
939 self
.gitStream
.write(data
)
940 self
.gitStream
.write("\n")
942 self
.gitStream
.write("\n")
944 change
= int(details
["change"])
946 if self
.labels
.has_key(change
):
947 label
= self
.labels
[change
]
948 labelDetails
= label
[0]
949 labelRevisions
= label
[1]
951 print "Change %s is labelled %s" % (change
, labelDetails
)
953 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
954 for p
in branchPrefixes
]))
956 if len(files
) == len(labelRevisions
):
960 if info
["action"] == "delete":
962 cleanedFiles
[info
["depotFile"]] = info
["rev"]
964 if cleanedFiles
== labelRevisions
:
965 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
966 self
.gitStream
.write("from %s\n" % branch
)
968 owner
= labelDetails
["Owner"]
970 if author
in self
.users
:
971 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
973 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
974 self
.gitStream
.write("tagger %s\n" % tagger
)
975 self
.gitStream
.write("data <<EOT\n")
976 self
.gitStream
.write(labelDetails
["Description"])
977 self
.gitStream
.write("EOT\n\n")
981 print ("Tag %s does not match with change %s: files do not match."
982 % (labelDetails
["label"], change
))
986 print ("Tag %s does not match with change %s: file count is different."
987 % (labelDetails
["label"], change
))
989 def getUserCacheFilename(self
):
990 home
= os
.environ
.get("HOME", os
.environ
.get("USERPROFILE"))
991 return home
+ "/.gitp4-usercache.txt"
993 def getUserMapFromPerforceServer(self
):
994 if self
.userMapFromPerforceServer
:
998 for output
in p4CmdList("users"):
999 if not output
.has_key("User"):
1001 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
1005 for (key
, val
) in self
.users
.items():
1006 s
+= "%s\t%s\n" % (key
, val
)
1008 open(self
.getUserCacheFilename(), "wb").write(s
)
1009 self
.userMapFromPerforceServer
= True
1011 def loadUserMapFromCache(self
):
1013 self
.userMapFromPerforceServer
= False
1015 cache
= open(self
.getUserCacheFilename(), "rb")
1016 lines
= cache
.readlines()
1019 entry
= line
.strip().split("\t")
1020 self
.users
[entry
[0]] = entry
[1]
1022 self
.getUserMapFromPerforceServer()
1024 def getLabels(self
):
1027 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
1028 if len(l
) > 0 and not self
.silent
:
1029 print "Finding files belonging to labels in %s" % `self
.depotPath`
1032 label
= output
["label"]
1036 print "Querying files for label %s" % label
1037 for file in p4CmdList("files "
1038 + ' '.join (["%s...@%s" % (p
, label
)
1039 for p
in self
.depotPaths
])):
1040 revisions
[file["depotFile"]] = file["rev"]
1041 change
= int(file["change"])
1042 if change
> newestChange
:
1043 newestChange
= change
1045 self
.labels
[newestChange
] = [output
, revisions
]
1048 print "Label changes: %s" % self
.labels
.keys()
1050 def guessProjectName(self
):
1051 for p
in self
.depotPaths
:
1054 p
= p
[p
.strip().rfind("/") + 1:]
1055 if not p
.endswith("/"):
1059 def getBranchMapping(self
):
1060 lostAndFoundBranches
= set()
1062 for info
in p4CmdList("branches"):
1063 details
= p4Cmd("branch -o %s" % info
["branch"])
1065 while details
.has_key("View%s" % viewIdx
):
1066 paths
= details
["View%s" % viewIdx
].split(" ")
1067 viewIdx
= viewIdx
+ 1
1068 # require standard //depot/foo/... //depot/bar/... mapping
1069 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
1072 destination
= paths
[1]
1074 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
1075 source
= source
[len(self
.depotPaths
[0]):-4]
1076 destination
= destination
[len(self
.depotPaths
[0]):-4]
1078 if destination
in self
.knownBranches
:
1080 print "p4 branch %s defines a mapping from %s to %s" % (info
["branch"], source
, destination
)
1081 print "but there exists another mapping from %s to %s already!" % (self
.knownBranches
[destination
], destination
)
1084 self
.knownBranches
[destination
] = source
1086 lostAndFoundBranches
.discard(destination
)
1088 if source
not in self
.knownBranches
:
1089 lostAndFoundBranches
.add(source
)
1092 for branch
in lostAndFoundBranches
:
1093 self
.knownBranches
[branch
] = branch
1095 def listExistingP4GitBranches(self
):
1096 # branches holds mapping from name to commit
1097 branches
= p4BranchesInGit(self
.importIntoRemotes
)
1098 self
.p4BranchesInGit
= branches
.keys()
1099 for branch
in branches
.keys():
1100 self
.initialParents
[self
.refPrefix
+ branch
] = branches
[branch
]
1102 def updateOptionDict(self
, d
):
1104 if self
.keepRepoPath
:
1105 option_keys
['keepRepoPath'] = 1
1107 d
["options"] = ' '.join(sorted(option_keys
.keys()))
1109 def readOptions(self
, d
):
1110 self
.keepRepoPath
= (d
.has_key('options')
1111 and ('keepRepoPath' in d
['options']))
1113 def run(self
, args
):
1114 self
.depotPaths
= []
1115 self
.changeRange
= ""
1116 self
.initialParent
= ""
1117 self
.previousDepotPaths
= []
1119 # map from branch depot path to parent branch
1120 self
.knownBranches
= {}
1121 self
.initialParents
= {}
1122 self
.hasOrigin
= originP4BranchesExist()
1123 if not self
.syncWithOrigin
:
1124 self
.hasOrigin
= False
1126 if self
.importIntoRemotes
:
1127 self
.refPrefix
= "refs/remotes/p4/"
1129 self
.refPrefix
= "refs/heads/p4/"
1131 if self
.syncWithOrigin
and self
.hasOrigin
:
1133 print "Syncing with origin first by calling git fetch origin"
1134 system("git fetch origin")
1136 if len(self
.branch
) == 0:
1137 self
.branch
= self
.refPrefix
+ "master"
1138 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1139 system("git update-ref %s refs/heads/p4" % self
.branch
)
1140 system("git branch -D p4");
1141 # create it /after/ importing, when master exists
1142 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
and gitBranchExists(self
.branch
):
1143 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1145 # TODO: should always look at previous commits,
1146 # merge with previous imports, if possible.
1149 createOrUpdateBranchesFromOrigin(self
.refPrefix
, self
.silent
)
1150 self
.listExistingP4GitBranches()
1152 if len(self
.p4BranchesInGit
) > 1:
1154 print "Importing from/into multiple branches"
1155 self
.detectBranches
= True
1158 print "branches: %s" % self
.p4BranchesInGit
1161 for branch
in self
.p4BranchesInGit
:
1162 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1164 settings
= extractSettingsGitLog(logMsg
)
1166 self
.readOptions(settings
)
1167 if (settings
.has_key('depot-paths')
1168 and settings
.has_key ('change')):
1169 change
= int(settings
['change']) + 1
1170 p4Change
= max(p4Change
, change
)
1172 depotPaths
= sorted(settings
['depot-paths'])
1173 if self
.previousDepotPaths
== []:
1174 self
.previousDepotPaths
= depotPaths
1177 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1178 for i
in range(0, min(len(cur
), len(prev
))):
1179 if cur
[i
] <> prev
[i
]:
1183 paths
.append (cur
[:i
+ 1])
1185 self
.previousDepotPaths
= paths
1188 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1189 self
.changeRange
= "@%s,#head" % p4Change
1190 if not self
.detectBranches
:
1191 self
.initialParent
= parseRevision(self
.branch
)
1192 if not self
.silent
and not self
.detectBranches
:
1193 print "Performing incremental import into %s git branch" % self
.branch
1195 if not self
.branch
.startswith("refs/"):
1196 self
.branch
= "refs/heads/" + self
.branch
1198 if len(args
) == 0 and self
.depotPaths
:
1200 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1202 if self
.depotPaths
and self
.depotPaths
!= args
:
1203 print ("previous import used depot path %s and now %s was specified. "
1204 "This doesn't work!" % (' '.join (self
.depotPaths
),
1208 self
.depotPaths
= sorted(args
)
1214 for p
in self
.depotPaths
:
1215 if p
.find("@") != -1:
1216 atIdx
= p
.index("@")
1217 self
.changeRange
= p
[atIdx
:]
1218 if self
.changeRange
== "@all":
1219 self
.changeRange
= ""
1220 elif ',' not in self
.changeRange
:
1221 self
.revision
= self
.changeRange
1222 self
.changeRange
= ""
1224 elif p
.find("#") != -1:
1225 hashIdx
= p
.index("#")
1226 self
.revision
= p
[hashIdx
:]
1228 elif self
.previousDepotPaths
== []:
1229 self
.revision
= "#head"
1231 p
= re
.sub ("\.\.\.$", "", p
)
1232 if not p
.endswith("/"):
1237 self
.depotPaths
= newPaths
1240 self
.loadUserMapFromCache()
1242 if self
.detectLabels
:
1245 if self
.detectBranches
:
1246 ## FIXME - what's a P4 projectName ?
1247 self
.projectName
= self
.guessProjectName()
1249 if not self
.hasOrigin
:
1250 self
.getBranchMapping();
1252 print "p4-git branches: %s" % self
.p4BranchesInGit
1253 print "initial parents: %s" % self
.initialParents
1254 for b
in self
.p4BranchesInGit
:
1258 b
= b
[len(self
.projectName
):]
1259 self
.createdBranches
.add(b
)
1261 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1263 importProcess
= subprocess
.Popen(["git", "fast-import"],
1264 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1265 stderr
=subprocess
.PIPE
);
1266 self
.gitOutput
= importProcess
.stdout
1267 self
.gitStream
= importProcess
.stdin
1268 self
.gitError
= importProcess
.stderr
1271 print "Doing initial import of %s from revision %s into %s" % (' '.join(self
.depotPaths
), self
.revision
, self
.branch
)
1273 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1274 details
["desc"] = ("Initial import of %s from the state at revision %s"
1275 % (' '.join(self
.depotPaths
), self
.revision
))
1276 details
["change"] = self
.revision
1280 for info
in p4CmdList("files "
1281 + ' '.join(["%s...%s"
1282 % (p
, self
.revision
)
1283 for p
in self
.depotPaths
])):
1285 if info
['code'] == 'error':
1286 sys
.stderr
.write("p4 returned an error: %s\n"
1291 change
= int(info
["change"])
1292 if change
> newestRevision
:
1293 newestRevision
= change
1295 if info
["action"] == "delete":
1296 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1297 #fileCnt = fileCnt + 1
1300 for prop
in ["depotFile", "rev", "action", "type" ]:
1301 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1303 fileCnt
= fileCnt
+ 1
1305 details
["change"] = newestRevision
1306 self
.updateOptionDict(details
)
1308 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1310 print "IO error with git fast-import. Is your git version recent enough?"
1311 print self
.gitError
.read()
1316 if len(self
.changesFile
) > 0:
1317 output
= open(self
.changesFile
).readlines()
1320 changeSet
.add(int(line
))
1322 for change
in changeSet
:
1323 changes
.append(change
)
1328 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1330 assert self
.depotPaths
1331 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1332 for p
in self
.depotPaths
]))
1335 changeNum
= line
.split(" ")[1]
1336 changes
.append(int(changeNum
))
1340 if len(self
.maxChanges
) > 0:
1341 changes
= changes
[:min(int(self
.maxChanges
), len(changes
))]
1343 if len(changes
) == 0:
1345 print "No changes to import!"
1348 if not self
.silent
and not self
.detectBranches
:
1349 print "Import destination: %s" % self
.branch
1351 self
.updatedBranches
= set()
1354 for change
in changes
:
1355 description
= p4Cmd("describe %s" % change
)
1356 self
.updateOptionDict(description
)
1359 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1364 if self
.detectBranches
:
1365 branches
= self
.splitFilesIntoBranches(description
)
1366 for branch
in branches
.keys():
1368 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1372 filesForCommit
= branches
[branch
]
1375 print "branch is %s" % branch
1377 self
.updatedBranches
.add(branch
)
1379 if branch
not in self
.createdBranches
:
1380 self
.createdBranches
.add(branch
)
1381 parent
= self
.knownBranches
[branch
]
1382 if parent
== branch
:
1385 print "parent determined through known branches: %s" % parent
1387 # main branch? use master
1388 if branch
== "main":
1393 branch
= self
.projectName
+ branch
1395 if parent
== "main":
1397 elif len(parent
) > 0:
1399 parent
= self
.projectName
+ parent
1401 branch
= self
.refPrefix
+ branch
1403 parent
= self
.refPrefix
+ parent
1406 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1408 if len(parent
) == 0 and branch
in self
.initialParents
:
1409 parent
= self
.initialParents
[branch
]
1410 del self
.initialParents
[branch
]
1412 self
.commit(description
, filesForCommit
, branch
, [branchPrefix
], parent
)
1414 files
= self
.extractFilesFromCommit(description
)
1415 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1417 self
.initialParent
= ""
1419 print self
.gitError
.read()
1424 if len(self
.updatedBranches
) > 0:
1425 sys
.stdout
.write("Updated branches: ")
1426 for b
in self
.updatedBranches
:
1427 sys
.stdout
.write("%s " % b
)
1428 sys
.stdout
.write("\n")
1431 self
.gitStream
.close()
1432 if importProcess
.wait() != 0:
1433 die("fast-import failed: %s" % self
.gitError
.read())
1434 self
.gitOutput
.close()
1435 self
.gitError
.close()
1439 class P4Rebase(Command
):
1441 Command
.__init
__(self
)
1443 self
.description
= ("Fetches the latest revision from perforce and "
1444 + "rebases the current work (branch) against it")
1445 self
.verbose
= False
1447 def run(self
, args
):
1451 [upstream
, settings
] = findUpstreamBranchPoint()
1452 if len(upstream
) == 0:
1453 die("Cannot find upstream branchpoint for rebase")
1455 # the branchpoint may be p4/foo~3, so strip off the parent
1456 upstream
= re
.sub("~[0-9]+$", "", upstream
)
1458 print "Rebasing the current branch onto %s" % upstream
1459 oldHead
= read_pipe("git rev-parse HEAD").strip()
1460 system("git rebase %s" % upstream
)
1461 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1464 class P4Clone(P4Sync
):
1466 P4Sync
.__init
__(self
)
1467 self
.description
= "Creates a new git repository and imports from Perforce into it"
1468 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1469 self
.options
.append(
1470 optparse
.make_option("--destination", dest
="cloneDestination",
1471 action
='store', default
=None,
1472 help="where to leave result of the clone"))
1473 self
.cloneDestination
= None
1474 self
.needsGit
= False
1476 def defaultDestination(self
, args
):
1477 ## TODO: use common prefix of args?
1479 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1480 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1481 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1482 depotDir
= re
.sub(r
"/$", "", depotDir
)
1483 return os
.path
.split(depotDir
)[1]
1485 def run(self
, args
):
1489 if self
.keepRepoPath
and not self
.cloneDestination
:
1490 sys
.stderr
.write("Must specify destination for --keep-path\n")
1495 if not self
.cloneDestination
and len(depotPaths
) > 1:
1496 self
.cloneDestination
= depotPaths
[-1]
1497 depotPaths
= depotPaths
[:-1]
1499 for p
in depotPaths
:
1500 if not p
.startswith("//"):
1503 if not self
.cloneDestination
:
1504 self
.cloneDestination
= self
.defaultDestination(args
)
1506 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1507 if not os
.path
.exists(self
.cloneDestination
):
1508 os
.makedirs(self
.cloneDestination
)
1509 os
.chdir(self
.cloneDestination
)
1511 self
.gitdir
= os
.getcwd() + "/.git"
1512 if not P4Sync
.run(self
, depotPaths
):
1514 if self
.branch
!= "master":
1515 if gitBranchExists("refs/remotes/p4/master"):
1516 system("git branch master refs/remotes/p4/master")
1517 system("git checkout -f")
1519 print "Could not detect main branch. No checkout/master branch created."
1523 class P4Branches(Command
):
1525 Command
.__init
__(self
)
1527 self
.description
= ("Shows the git branches that hold imports and their "
1528 + "corresponding perforce depot paths")
1529 self
.verbose
= False
1531 def run(self
, args
):
1532 if originP4BranchesExist():
1533 createOrUpdateBranchesFromOrigin()
1535 cmdline
= "git rev-parse --symbolic "
1536 cmdline
+= " --remotes"
1538 for line
in read_pipe_lines(cmdline
):
1541 if not line
.startswith('p4/') or line
== "p4/HEAD":
1545 log
= extractLogMessageFromGitCommit("refs/remotes/%s" % branch
)
1546 settings
= extractSettingsGitLog(log
)
1548 print "%s <= %s (%s)" % (branch
, ",".join(settings
["depot-paths"]), settings
["change"])
1551 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1553 optparse
.IndentedHelpFormatter
.__init
__(self
)
1555 def format_description(self
, description
):
1557 return description
+ "\n"
1561 def printUsage(commands
):
1562 print "usage: %s <command> [options]" % sys
.argv
[0]
1564 print "valid commands: %s" % ", ".join(commands
)
1566 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1571 "submit" : P4Submit
,
1573 "rebase" : P4Rebase
,
1575 "rollback" : P4RollBack
,
1576 "branches" : P4Branches
1581 if len(sys
.argv
[1:]) == 0:
1582 printUsage(commands
.keys())
1586 cmdName
= sys
.argv
[1]
1588 klass
= commands
[cmdName
]
1591 print "unknown command %s" % cmdName
1593 printUsage(commands
.keys())
1596 options
= cmd
.options
1597 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1601 if len(options
) > 0:
1602 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1604 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1606 description
= cmd
.description
,
1607 formatter
= HelpFormatter())
1609 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1611 verbose
= cmd
.verbose
1613 if cmd
.gitdir
== None:
1614 cmd
.gitdir
= os
.path
.abspath(".git")
1615 if not isValidGitDir(cmd
.gitdir
):
1616 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1617 if os
.path
.exists(cmd
.gitdir
):
1618 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1622 if not isValidGitDir(cmd
.gitdir
):
1623 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1624 cmd
.gitdir
+= "/.git"
1626 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1628 os
.environ
["GIT_DIR"] = cmd
.gitdir
1630 if not cmd
.run(args
):
1634 if __name__
== '__main__':