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
)
66 def p4CmdList(cmd
, stdin
=None, stdin_mode
='w+b'):
67 cmd
= "p4 -G %s" % cmd
69 sys
.stderr
.write("Opening pipe: %s\n" % cmd
)
71 # Use a temporary file to avoid deadlocks without
72 # subprocess.communicate(), which would put another copy
73 # of stdout into memory.
76 stdin_file
= tempfile
.TemporaryFile(prefix
='p4-stdin', mode
=stdin_mode
)
77 stdin_file
.write(stdin
)
81 p4
= subprocess
.Popen(cmd
, shell
=True,
83 stdout
=subprocess
.PIPE
)
88 entry
= marshal
.load(p4
.stdout
)
95 entry
["p4ExitCode"] = exitCode
101 list = p4CmdList(cmd
)
107 def p4Where(depotPath
):
108 if not depotPath
.endswith("/"):
110 output
= p4Cmd("where %s..." % depotPath
)
111 if output
["code"] == "error":
115 clientPath
= output
.get("path")
116 elif "data" in output
:
117 data
= output
.get("data")
118 lastSpace
= data
.rfind(" ")
119 clientPath
= data
[lastSpace
+ 1:]
121 if clientPath
.endswith("..."):
122 clientPath
= clientPath
[:-3]
125 def currentGitBranch():
126 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
128 def isValidGitDir(path
):
129 if (os
.path
.exists(path
+ "/HEAD")
130 and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects")):
134 def parseRevision(ref
):
135 return read_pipe("git rev-parse %s" % ref
).strip()
137 def extractLogMessageFromGitCommit(commit
):
140 ## fixme: title is first line of commit, not 1st paragraph.
142 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
151 def extractSettingsGitLog(log
):
153 for line
in log
.split("\n"):
155 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
159 assignments
= m
.group(1).split (':')
160 for a
in assignments
:
162 key
= vals
[0].strip()
163 val
= ('='.join (vals
[1:])).strip()
164 if val
.endswith ('\"') and val
.startswith('"'):
169 paths
= values
.get("depot-paths")
171 paths
= values
.get("depot-path")
173 values
['depot-paths'] = paths
.split(',')
176 def gitBranchExists(branch
):
177 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
178 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
179 return proc
.wait() == 0;
182 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
184 def p4BranchesInGit(branchesAreInRemotes
= True):
187 cmdline
= "git rev-parse --symbolic "
188 if branchesAreInRemotes
:
189 cmdline
+= " --remotes"
191 cmdline
+= " --branches"
193 for line
in read_pipe_lines(cmdline
):
196 ## only import to p4/
197 if not line
.startswith('p4/') or line
== "p4/HEAD":
202 branch
= re
.sub ("^p4/", "", line
)
204 branches
[branch
] = parseRevision(line
)
207 def findUpstreamBranchPoint(head
= "HEAD"):
208 branches
= p4BranchesInGit()
209 # map from depot-path to branch name
210 branchByDepotPath
= {}
211 for branch
in branches
.keys():
212 tip
= branches
[branch
]
213 log
= extractLogMessageFromGitCommit(tip
)
214 settings
= extractSettingsGitLog(log
)
215 if settings
.has_key("depot-paths"):
216 paths
= ",".join(settings
["depot-paths"])
217 branchByDepotPath
[paths
] = "remotes/p4/" + branch
221 while parent
< 65535:
222 commit
= head
+ "~%s" % parent
223 log
= extractLogMessageFromGitCommit(commit
)
224 settings
= extractSettingsGitLog(log
)
225 if settings
.has_key("depot-paths"):
226 paths
= ",".join(settings
["depot-paths"])
227 if branchByDepotPath
.has_key(paths
):
228 return [branchByDepotPath
[paths
], settings
]
232 return ["", settings
]
234 def createOrUpdateBranchesFromOrigin(localRefPrefix
= "refs/remotes/p4/", silent
=True):
236 print ("Creating/updating branch(es) in %s based on origin branch(es)"
239 originPrefix
= "origin/p4/"
241 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
243 if (not line
.startswith(originPrefix
)) or line
.endswith("HEAD"):
246 headName
= line
[len(originPrefix
):]
247 remoteHead
= localRefPrefix
+ headName
250 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
251 if (not original
.has_key('depot-paths')
252 or not original
.has_key('change')):
256 if not gitBranchExists(remoteHead
):
258 print "creating %s" % remoteHead
261 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
262 if settings
.has_key('change') > 0:
263 if settings
['depot-paths'] == original
['depot-paths']:
264 originP4Change
= int(original
['change'])
265 p4Change
= int(settings
['change'])
266 if originP4Change
> p4Change
:
267 print ("%s (%s) is newer than %s (%s). "
268 "Updating p4 branch from origin."
269 % (originHead
, originP4Change
,
270 remoteHead
, p4Change
))
273 print ("Ignoring: %s was imported from %s while "
274 "%s was imported from %s"
275 % (originHead
, ','.join(original
['depot-paths']),
276 remoteHead
, ','.join(settings
['depot-paths'])))
279 system("git update-ref %s %s" % (remoteHead
, originHead
))
281 def originP4BranchesExist():
282 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
286 self
.usage
= "usage: %prog [options]"
289 class P4Debug(Command
):
291 Command
.__init
__(self
)
293 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
296 self
.description
= "A tool to debug the output of p4 -G."
297 self
.needsGit
= False
302 for output
in p4CmdList(" ".join(args
)):
303 print 'Element: %d' % j
308 class P4RollBack(Command
):
310 Command
.__init
__(self
)
312 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
313 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
315 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
317 self
.rollbackLocalBranches
= False
322 maxChange
= int(args
[0])
324 if "p4ExitCode" in p4Cmd("changes -m 1"):
325 die("Problems executing p4");
327 if self
.rollbackLocalBranches
:
328 refPrefix
= "refs/heads/"
329 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
331 refPrefix
= "refs/remotes/"
332 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
335 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
337 ref
= refPrefix
+ line
338 log
= extractLogMessageFromGitCommit(ref
)
339 settings
= extractSettingsGitLog(log
)
341 depotPaths
= settings
['depot-paths']
342 change
= settings
['change']
346 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
347 for p
in depotPaths
]))) == 0:
348 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
349 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
352 while change
and int(change
) > maxChange
:
355 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
356 system("git update-ref %s \"%s^\"" % (ref
, ref
))
357 log
= extractLogMessageFromGitCommit(ref
)
358 settings
= extractSettingsGitLog(log
)
361 depotPaths
= settings
['depot-paths']
362 change
= settings
['change']
365 print "%s rewound to %s" % (ref
, change
)
369 class P4Submit(Command
):
371 Command
.__init
__(self
)
373 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
374 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
375 optparse
.make_option("--origin", dest
="origin"),
376 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
377 optparse
.make_option("--log-substitutions", dest
="substFile"),
378 optparse
.make_option("--dry-run", action
="store_true"),
379 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
380 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
382 self
.description
= "Submit changes from git to the perforce depot."
383 self
.usage
+= " [name of git branch to submit into perforce depot]"
384 self
.firstTime
= True
386 self
.interactive
= True
389 self
.firstTime
= True
391 self
.directSubmit
= False
392 self
.trustMeLikeAFool
= False
394 self
.isWindows
= (platform
.system() == "Windows")
396 self
.logSubstitutions
= {}
397 self
.logSubstitutions
["<enter description here>"] = "%log%"
398 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
401 if len(p4CmdList("opened ...")) > 0:
402 die("You have files opened with perforce! Close them before starting the sync.")
405 if len(self
.config
) > 0 and not self
.reset
:
406 die("Cannot start sync. Previous sync config found at %s\n"
407 "If you want to start submitting again from scratch "
408 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
411 if self
.directSubmit
:
414 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
415 commits
.append(line
.strip())
418 self
.config
["commits"] = commits
420 def prepareLogMessage(self
, template
, message
):
423 for line
in template
.split("\n"):
424 if line
.startswith("#"):
425 result
+= line
+ "\n"
429 for key
in self
.logSubstitutions
.keys():
430 if line
.find(key
) != -1:
431 value
= self
.logSubstitutions
[key
]
432 value
= value
.replace("%log%", message
)
433 if value
!= "@remove@":
434 result
+= line
.replace(key
, value
) + "\n"
439 result
+= line
+ "\n"
443 def prepareSubmitTemplate(self
):
444 # remove lines in the Files section that show changes to files outside the depot path we're committing into
446 inFilesSection
= False
447 for line
in read_pipe_lines("p4 change -o"):
449 if line
.startswith("\t"):
450 # path starts and ends with a tab
452 lastTab
= path
.rfind("\t")
454 path
= path
[:lastTab
]
455 if not path
.startswith(self
.depotPath
):
458 inFilesSection
= False
460 if line
.startswith("Files:"):
461 inFilesSection
= True
467 def applyCommit(self
, id):
468 if self
.directSubmit
:
469 print "Applying local change in working directory/index"
470 diff
= self
.diffStatus
472 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
473 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
475 filesToDelete
= set()
479 path
= line
[1:].strip()
481 system("p4 edit \"%s\"" % path
)
482 editedFiles
.add(path
)
483 elif modifier
== "A":
485 if path
in filesToDelete
:
486 filesToDelete
.remove(path
)
487 elif modifier
== "D":
488 filesToDelete
.add(path
)
489 if path
in filesToAdd
:
490 filesToAdd
.remove(path
)
492 die("unknown modifier %s for %s" % (modifier
, path
))
494 if self
.directSubmit
:
495 diffcmd
= "cat \"%s\"" % self
.diffFile
497 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
498 patchcmd
= diffcmd
+ " | git apply "
499 tryPatchCmd
= patchcmd
+ "--check -"
500 applyPatchCmd
= patchcmd
+ "--check --apply -"
502 if os
.system(tryPatchCmd
) != 0:
503 print "Unfortunately applying the change failed!"
504 print "What do you want to do?"
506 while response
!= "s" and response
!= "a" and response
!= "w":
507 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
508 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
510 print "Skipping! Good luck with the next patches..."
512 elif response
== "a":
513 os
.system(applyPatchCmd
)
514 if len(filesToAdd
) > 0:
515 print "You may also want to call p4 add on the following files:"
516 print " ".join(filesToAdd
)
517 if len(filesToDelete
):
518 print "The following files should be scheduled for deletion with p4 delete:"
519 print " ".join(filesToDelete
)
520 die("Please resolve and submit the conflict manually and "
521 + "continue afterwards with git-p4 submit --continue")
522 elif response
== "w":
523 system(diffcmd
+ " > patch.txt")
524 print "Patch saved to patch.txt in %s !" % self
.clientPath
525 die("Please resolve and submit the conflict manually and "
526 "continue afterwards with git-p4 submit --continue")
528 system(applyPatchCmd
)
531 system("p4 add \"%s\"" % f
)
532 for f
in filesToDelete
:
533 system("p4 revert \"%s\"" % f
)
534 system("p4 delete \"%s\"" % f
)
537 if not self
.directSubmit
:
538 logMessage
= extractLogMessageFromGitCommit(id)
539 logMessage
= logMessage
.replace("\n", "\n\t")
541 logMessage
= logMessage
.replace("\n", "\r\n")
542 logMessage
= logMessage
.strip()
544 template
= self
.prepareSubmitTemplate()
547 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
548 diff
= read_pipe("p4 diff -du ...")
550 for newFile
in filesToAdd
:
551 diff
+= "==== new file ====\n"
552 diff
+= "--- /dev/null\n"
553 diff
+= "+++ %s\n" % newFile
554 f
= open(newFile
, "r")
555 for line
in f
.readlines():
559 separatorLine
= "######## everything below this line is just the diff #######"
560 if platform
.system() == "Windows":
561 separatorLine
+= "\r"
562 separatorLine
+= "\n"
565 if self
.trustMeLikeAFool
:
568 firstIteration
= True
569 while response
== "e":
570 if not firstIteration
:
571 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
572 firstIteration
= False
574 [handle
, fileName
] = tempfile
.mkstemp()
575 tmpFile
= os
.fdopen(handle
, "w+")
576 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
579 if platform
.system() == "Windows":
580 defaultEditor
= "notepad"
581 editor
= os
.environ
.get("EDITOR", defaultEditor
);
582 system(editor
+ " " + fileName
)
583 tmpFile
= open(fileName
, "rb")
584 message
= tmpFile
.read()
587 submitTemplate
= message
[:message
.index(separatorLine
)]
589 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
591 if response
== "y" or response
== "yes":
594 raw_input("Press return to continue...")
596 if self
.directSubmit
:
597 print "Submitting to git first"
598 os
.chdir(self
.oldWorkingDirectory
)
599 write_pipe("git commit -a -F -", submitTemplate
)
600 os
.chdir(self
.clientPath
)
602 write_pipe("p4 submit -i", submitTemplate
)
603 elif response
== "s":
604 for f
in editedFiles
:
605 system("p4 revert \"%s\"" % f
);
607 system("p4 revert \"%s\"" % f
);
609 for f
in filesToDelete
:
610 system("p4 delete \"%s\"" % f
);
613 print "Not submitting!"
614 self
.interactive
= False
616 fileName
= "submit.txt"
617 file = open(fileName
, "w+")
618 file.write(self
.prepareLogMessage(template
, logMessage
))
620 print ("Perforce submit template written as %s. "
621 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
622 % (fileName
, fileName
))
626 self
.master
= currentGitBranch()
627 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
628 die("Detecting current git branch failed!")
630 self
.master
= args
[0]
634 [upstream
, settings
] = findUpstreamBranchPoint()
635 self
.depotPath
= settings
['depot-paths'][0]
636 if len(self
.origin
) == 0:
637 self
.origin
= upstream
640 print "Origin branch is " + self
.origin
642 if len(self
.depotPath
) == 0:
643 print "Internal error: cannot locate perforce depot path from existing branches"
646 self
.clientPath
= p4Where(self
.depotPath
)
648 if len(self
.clientPath
) == 0:
649 print "Error: Cannot locate perforce checkout of %s in client view" % self
.depotPath
652 print "Perforce checkout for depot path %s located at %s" % (self
.depotPath
, self
.clientPath
)
653 self
.oldWorkingDirectory
= os
.getcwd()
655 if self
.directSubmit
:
656 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
657 if len(self
.diffStatus
) == 0:
658 print "No changes in working directory to submit."
660 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
661 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
662 f
= open(self
.diffFile
, "wb")
666 os
.chdir(self
.clientPath
)
667 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
668 if response
== "y" or response
== "yes":
669 system("p4 sync ...")
672 self
.firstTime
= True
674 if len(self
.substFile
) > 0:
675 for line
in open(self
.substFile
, "r").readlines():
676 tokens
= line
.strip().split("=")
677 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
680 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
681 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
686 commits
= self
.config
.get("commits", [])
688 while len(commits
) > 0:
689 self
.firstTime
= False
691 commits
= commits
[1:]
692 self
.config
["commits"] = commits
693 self
.applyCommit(commit
)
694 if not self
.interactive
:
699 if self
.directSubmit
:
700 os
.remove(self
.diffFile
)
702 if len(commits
) == 0:
704 print "No changes found to apply between %s and current HEAD" % self
.origin
706 print "All changes applied!"
707 os
.chdir(self
.oldWorkingDirectory
)
708 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
709 if response
== "y" or response
== "yes":
712 os
.remove(self
.configFile
)
716 class P4Sync(Command
):
718 Command
.__init
__(self
)
720 optparse
.make_option("--branch", dest
="branch"),
721 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
722 optparse
.make_option("--changesfile", dest
="changesFile"),
723 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
724 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
725 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
726 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
727 help="Import into refs/heads/ , not refs/remotes"),
728 optparse
.make_option("--max-changes", dest
="maxChanges"),
729 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
730 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
732 self
.description
= """Imports from Perforce into a git repository.\n
734 //depot/my/project/ -- to import the current head
735 //depot/my/project/@all -- to import everything
736 //depot/my/project/@1,6 -- to import only from revision 1 to 6
738 (a ... is not needed in the path p4 specification, it's added implicitly)"""
740 self
.usage
+= " //depot/path[@revRange]"
742 self
.createdBranches
= Set()
743 self
.committedChanges
= Set()
745 self
.detectBranches
= False
746 self
.detectLabels
= False
747 self
.changesFile
= ""
748 self
.syncWithOrigin
= True
750 self
.importIntoRemotes
= True
752 self
.isWindows
= (platform
.system() == "Windows")
753 self
.keepRepoPath
= False
754 self
.depotPaths
= None
755 self
.p4BranchesInGit
= []
757 if gitConfig("git-p4.syncFromOrigin") == "false":
758 self
.syncWithOrigin
= False
760 def extractFilesFromCommit(self
, commit
):
763 while commit
.has_key("depotFile%s" % fnum
):
764 path
= commit
["depotFile%s" % fnum
]
766 found
= [p
for p
in self
.depotPaths
767 if path
.startswith (p
)]
774 file["rev"] = commit
["rev%s" % fnum
]
775 file["action"] = commit
["action%s" % fnum
]
776 file["type"] = commit
["type%s" % fnum
]
781 def stripRepoPath(self
, path
, prefixes
):
782 if self
.keepRepoPath
:
783 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
786 if path
.startswith(p
):
791 def splitFilesIntoBranches(self
, commit
):
794 while commit
.has_key("depotFile%s" % fnum
):
795 path
= commit
["depotFile%s" % fnum
]
796 found
= [p
for p
in self
.depotPaths
797 if path
.startswith (p
)]
804 file["rev"] = commit
["rev%s" % fnum
]
805 file["action"] = commit
["action%s" % fnum
]
806 file["type"] = commit
["type%s" % fnum
]
809 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
811 for branch
in self
.knownBranches
.keys():
813 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
814 if relPath
.startswith(branch
+ "/"):
815 if branch
not in branches
:
816 branches
[branch
] = []
817 branches
[branch
].append(file)
822 ## Should move this out, doesn't use SELF.
823 def readP4Files(self
, files
):
824 files
= [f
for f
in files
825 if f
['action'] != 'delete']
830 filedata
= p4CmdList('-x - print',
831 stdin
='\n'.join(['%s#%s' % (f
['path'], f
['rev'])
834 if "p4ExitCode" in filedata
[0]:
835 die("Problems executing p4. Error: [%d]."
836 % (filedata
[0]['p4ExitCode']));
840 while j
< len(filedata
):
844 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
846 text
+= filedata
[j
]['data']
850 if not stat
.has_key('depotFile'):
851 sys
.stderr
.write("p4 print fails with: %s\n" % repr(stat
))
854 contents
[stat
['depotFile']] = text
857 assert not f
.has_key('data')
858 f
['data'] = contents
[f
['path']]
860 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
861 epoch
= details
["time"]
862 author
= details
["user"]
865 print "commit into %s" % branch
867 # start with reading files; if that fails, we should not
871 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
874 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
876 self
.readP4Files(files
)
881 self
.gitStream
.write("commit %s\n" % branch
)
882 # gitStream.write("mark :%s\n" % details["change"])
883 self
.committedChanges
.add(int(details
["change"]))
885 if author
not in self
.users
:
886 self
.getUserMapFromPerforceServer()
887 if author
in self
.users
:
888 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
890 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
892 self
.gitStream
.write("committer %s\n" % committer
)
894 self
.gitStream
.write("data <<EOT\n")
895 self
.gitStream
.write(details
["desc"])
896 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s"
897 % (','.join (branchPrefixes
), details
["change"]))
898 if len(details
['options']) > 0:
899 self
.gitStream
.write(": options = %s" % details
['options'])
900 self
.gitStream
.write("]\nEOT\n\n")
904 print "parent %s" % parent
905 self
.gitStream
.write("from %s\n" % parent
)
908 if file["type"] == "apple":
909 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
912 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
913 if file["action"] == "delete":
914 self
.gitStream
.write("D %s\n" % relPath
)
919 if file["type"].startswith("x"):
921 elif file["type"] == "symlink":
923 # p4 print on a symlink contains "target\n", so strip it off
926 if self
.isWindows
and file["type"].endswith("text"):
927 data
= data
.replace("\r\n", "\n")
929 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
930 self
.gitStream
.write("data %s\n" % len(data
))
931 self
.gitStream
.write(data
)
932 self
.gitStream
.write("\n")
934 self
.gitStream
.write("\n")
936 change
= int(details
["change"])
938 if self
.labels
.has_key(change
):
939 label
= self
.labels
[change
]
940 labelDetails
= label
[0]
941 labelRevisions
= label
[1]
943 print "Change %s is labelled %s" % (change
, labelDetails
)
945 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
946 for p
in branchPrefixes
]))
948 if len(files
) == len(labelRevisions
):
952 if info
["action"] == "delete":
954 cleanedFiles
[info
["depotFile"]] = info
["rev"]
956 if cleanedFiles
== labelRevisions
:
957 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
958 self
.gitStream
.write("from %s\n" % branch
)
960 owner
= labelDetails
["Owner"]
962 if author
in self
.users
:
963 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
965 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
966 self
.gitStream
.write("tagger %s\n" % tagger
)
967 self
.gitStream
.write("data <<EOT\n")
968 self
.gitStream
.write(labelDetails
["Description"])
969 self
.gitStream
.write("EOT\n\n")
973 print ("Tag %s does not match with change %s: files do not match."
974 % (labelDetails
["label"], change
))
978 print ("Tag %s does not match with change %s: file count is different."
979 % (labelDetails
["label"], change
))
981 def getUserCacheFilename(self
):
982 home
= os
.environ
.get("HOME", os
.environ
.get("USERPROFILE"))
983 return home
+ "/.gitp4-usercache.txt"
985 def getUserMapFromPerforceServer(self
):
986 if self
.userMapFromPerforceServer
:
990 for output
in p4CmdList("users"):
991 if not output
.has_key("User"):
993 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
997 for (key
, val
) in self
.users
.items():
998 s
+= "%s\t%s\n" % (key
, val
)
1000 open(self
.getUserCacheFilename(), "wb").write(s
)
1001 self
.userMapFromPerforceServer
= True
1003 def loadUserMapFromCache(self
):
1005 self
.userMapFromPerforceServer
= False
1007 cache
= open(self
.getUserCacheFilename(), "rb")
1008 lines
= cache
.readlines()
1011 entry
= line
.strip().split("\t")
1012 self
.users
[entry
[0]] = entry
[1]
1014 self
.getUserMapFromPerforceServer()
1016 def getLabels(self
):
1019 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
1020 if len(l
) > 0 and not self
.silent
:
1021 print "Finding files belonging to labels in %s" % `self
.depotPath`
1024 label
= output
["label"]
1028 print "Querying files for label %s" % label
1029 for file in p4CmdList("files "
1030 + ' '.join (["%s...@%s" % (p
, label
)
1031 for p
in self
.depotPaths
])):
1032 revisions
[file["depotFile"]] = file["rev"]
1033 change
= int(file["change"])
1034 if change
> newestChange
:
1035 newestChange
= change
1037 self
.labels
[newestChange
] = [output
, revisions
]
1040 print "Label changes: %s" % self
.labels
.keys()
1042 def guessProjectName(self
):
1043 for p
in self
.depotPaths
:
1046 p
= p
[p
.strip().rfind("/") + 1:]
1047 if not p
.endswith("/"):
1051 def getBranchMapping(self
):
1052 lostAndFoundBranches
= set()
1054 for info
in p4CmdList("branches"):
1055 details
= p4Cmd("branch -o %s" % info
["branch"])
1057 while details
.has_key("View%s" % viewIdx
):
1058 paths
= details
["View%s" % viewIdx
].split(" ")
1059 viewIdx
= viewIdx
+ 1
1060 # require standard //depot/foo/... //depot/bar/... mapping
1061 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
1064 destination
= paths
[1]
1066 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
1067 source
= source
[len(self
.depotPaths
[0]):-4]
1068 destination
= destination
[len(self
.depotPaths
[0]):-4]
1070 if destination
in self
.knownBranches
:
1072 print "p4 branch %s defines a mapping from %s to %s" % (info
["branch"], source
, destination
)
1073 print "but there exists another mapping from %s to %s already!" % (self
.knownBranches
[destination
], destination
)
1076 self
.knownBranches
[destination
] = source
1078 lostAndFoundBranches
.discard(destination
)
1080 if source
not in self
.knownBranches
:
1081 lostAndFoundBranches
.add(source
)
1084 for branch
in lostAndFoundBranches
:
1085 self
.knownBranches
[branch
] = branch
1087 def listExistingP4GitBranches(self
):
1088 # branches holds mapping from name to commit
1089 branches
= p4BranchesInGit(self
.importIntoRemotes
)
1090 self
.p4BranchesInGit
= branches
.keys()
1091 for branch
in branches
.keys():
1092 self
.initialParents
[self
.refPrefix
+ branch
] = branches
[branch
]
1094 def updateOptionDict(self
, d
):
1096 if self
.keepRepoPath
:
1097 option_keys
['keepRepoPath'] = 1
1099 d
["options"] = ' '.join(sorted(option_keys
.keys()))
1101 def readOptions(self
, d
):
1102 self
.keepRepoPath
= (d
.has_key('options')
1103 and ('keepRepoPath' in d
['options']))
1105 def run(self
, args
):
1106 self
.depotPaths
= []
1107 self
.changeRange
= ""
1108 self
.initialParent
= ""
1109 self
.previousDepotPaths
= []
1111 # map from branch depot path to parent branch
1112 self
.knownBranches
= {}
1113 self
.initialParents
= {}
1114 self
.hasOrigin
= originP4BranchesExist()
1115 if not self
.syncWithOrigin
:
1116 self
.hasOrigin
= False
1118 if self
.importIntoRemotes
:
1119 self
.refPrefix
= "refs/remotes/p4/"
1121 self
.refPrefix
= "refs/heads/p4/"
1123 if self
.syncWithOrigin
and self
.hasOrigin
:
1125 print "Syncing with origin first by calling git fetch origin"
1126 system("git fetch origin")
1128 if len(self
.branch
) == 0:
1129 self
.branch
= self
.refPrefix
+ "master"
1130 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1131 system("git update-ref %s refs/heads/p4" % self
.branch
)
1132 system("git branch -D p4");
1133 # create it /after/ importing, when master exists
1134 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
and gitBranchExists(self
.branch
):
1135 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1137 # TODO: should always look at previous commits,
1138 # merge with previous imports, if possible.
1141 createOrUpdateBranchesFromOrigin(self
.refPrefix
, self
.silent
)
1142 self
.listExistingP4GitBranches()
1144 if len(self
.p4BranchesInGit
) > 1:
1146 print "Importing from/into multiple branches"
1147 self
.detectBranches
= True
1150 print "branches: %s" % self
.p4BranchesInGit
1153 for branch
in self
.p4BranchesInGit
:
1154 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1156 settings
= extractSettingsGitLog(logMsg
)
1158 self
.readOptions(settings
)
1159 if (settings
.has_key('depot-paths')
1160 and settings
.has_key ('change')):
1161 change
= int(settings
['change']) + 1
1162 p4Change
= max(p4Change
, change
)
1164 depotPaths
= sorted(settings
['depot-paths'])
1165 if self
.previousDepotPaths
== []:
1166 self
.previousDepotPaths
= depotPaths
1169 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1170 for i
in range(0, min(len(cur
), len(prev
))):
1171 if cur
[i
] <> prev
[i
]:
1175 paths
.append (cur
[:i
+ 1])
1177 self
.previousDepotPaths
= paths
1180 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1181 self
.changeRange
= "@%s,#head" % p4Change
1182 if not self
.detectBranches
:
1183 self
.initialParent
= parseRevision(self
.branch
)
1184 if not self
.silent
and not self
.detectBranches
:
1185 print "Performing incremental import into %s git branch" % self
.branch
1187 if not self
.branch
.startswith("refs/"):
1188 self
.branch
= "refs/heads/" + self
.branch
1190 if len(args
) == 0 and self
.depotPaths
:
1192 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1194 if self
.depotPaths
and self
.depotPaths
!= args
:
1195 print ("previous import used depot path %s and now %s was specified. "
1196 "This doesn't work!" % (' '.join (self
.depotPaths
),
1200 self
.depotPaths
= sorted(args
)
1206 for p
in self
.depotPaths
:
1207 if p
.find("@") != -1:
1208 atIdx
= p
.index("@")
1209 self
.changeRange
= p
[atIdx
:]
1210 if self
.changeRange
== "@all":
1211 self
.changeRange
= ""
1212 elif ',' not in self
.changeRange
:
1213 self
.revision
= self
.changeRange
1214 self
.changeRange
= ""
1216 elif p
.find("#") != -1:
1217 hashIdx
= p
.index("#")
1218 self
.revision
= p
[hashIdx
:]
1220 elif self
.previousDepotPaths
== []:
1221 self
.revision
= "#head"
1223 p
= re
.sub ("\.\.\.$", "", p
)
1224 if not p
.endswith("/"):
1229 self
.depotPaths
= newPaths
1232 self
.loadUserMapFromCache()
1234 if self
.detectLabels
:
1237 if self
.detectBranches
:
1238 ## FIXME - what's a P4 projectName ?
1239 self
.projectName
= self
.guessProjectName()
1241 if not self
.hasOrigin
:
1242 self
.getBranchMapping();
1244 print "p4-git branches: %s" % self
.p4BranchesInGit
1245 print "initial parents: %s" % self
.initialParents
1246 for b
in self
.p4BranchesInGit
:
1250 b
= b
[len(self
.projectName
):]
1251 self
.createdBranches
.add(b
)
1253 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1255 importProcess
= subprocess
.Popen(["git", "fast-import"],
1256 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1257 stderr
=subprocess
.PIPE
);
1258 self
.gitOutput
= importProcess
.stdout
1259 self
.gitStream
= importProcess
.stdin
1260 self
.gitError
= importProcess
.stderr
1263 print "Doing initial import of %s from revision %s into %s" % (' '.join(self
.depotPaths
), self
.revision
, self
.branch
)
1265 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1266 details
["desc"] = ("Initial import of %s from the state at revision %s"
1267 % (' '.join(self
.depotPaths
), self
.revision
))
1268 details
["change"] = self
.revision
1272 for info
in p4CmdList("files "
1273 + ' '.join(["%s...%s"
1274 % (p
, self
.revision
)
1275 for p
in self
.depotPaths
])):
1277 if info
['code'] == 'error':
1278 sys
.stderr
.write("p4 returned an error: %s\n"
1283 change
= int(info
["change"])
1284 if change
> newestRevision
:
1285 newestRevision
= change
1287 if info
["action"] == "delete":
1288 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1289 #fileCnt = fileCnt + 1
1292 for prop
in ["depotFile", "rev", "action", "type" ]:
1293 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1295 fileCnt
= fileCnt
+ 1
1297 details
["change"] = newestRevision
1298 self
.updateOptionDict(details
)
1300 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1302 print "IO error with git fast-import. Is your git version recent enough?"
1303 print self
.gitError
.read()
1308 if len(self
.changesFile
) > 0:
1309 output
= open(self
.changesFile
).readlines()
1312 changeSet
.add(int(line
))
1314 for change
in changeSet
:
1315 changes
.append(change
)
1320 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1322 assert self
.depotPaths
1323 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1324 for p
in self
.depotPaths
]))
1327 changeNum
= line
.split(" ")[1]
1328 changes
.append(int(changeNum
))
1332 if len(self
.maxChanges
) > 0:
1333 changes
= changes
[:min(int(self
.maxChanges
), len(changes
))]
1335 if len(changes
) == 0:
1337 print "No changes to import!"
1340 if not self
.silent
and not self
.detectBranches
:
1341 print "Import destination: %s" % self
.branch
1343 self
.updatedBranches
= set()
1346 for change
in changes
:
1347 description
= p4Cmd("describe %s" % change
)
1348 self
.updateOptionDict(description
)
1351 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1356 if self
.detectBranches
:
1357 branches
= self
.splitFilesIntoBranches(description
)
1358 for branch
in branches
.keys():
1360 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1364 filesForCommit
= branches
[branch
]
1367 print "branch is %s" % branch
1369 self
.updatedBranches
.add(branch
)
1371 if branch
not in self
.createdBranches
:
1372 self
.createdBranches
.add(branch
)
1373 parent
= self
.knownBranches
[branch
]
1374 if parent
== branch
:
1377 print "parent determined through known branches: %s" % parent
1379 # main branch? use master
1380 if branch
== "main":
1385 branch
= self
.projectName
+ branch
1387 if parent
== "main":
1389 elif len(parent
) > 0:
1391 parent
= self
.projectName
+ parent
1393 branch
= self
.refPrefix
+ branch
1395 parent
= self
.refPrefix
+ parent
1398 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1400 if len(parent
) == 0 and branch
in self
.initialParents
:
1401 parent
= self
.initialParents
[branch
]
1402 del self
.initialParents
[branch
]
1404 self
.commit(description
, filesForCommit
, branch
, [branchPrefix
], parent
)
1406 files
= self
.extractFilesFromCommit(description
)
1407 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1409 self
.initialParent
= ""
1411 print self
.gitError
.read()
1416 if len(self
.updatedBranches
) > 0:
1417 sys
.stdout
.write("Updated branches: ")
1418 for b
in self
.updatedBranches
:
1419 sys
.stdout
.write("%s " % b
)
1420 sys
.stdout
.write("\n")
1423 self
.gitStream
.close()
1424 if importProcess
.wait() != 0:
1425 die("fast-import failed: %s" % self
.gitError
.read())
1426 self
.gitOutput
.close()
1427 self
.gitError
.close()
1431 class P4Rebase(Command
):
1433 Command
.__init
__(self
)
1435 self
.description
= ("Fetches the latest revision from perforce and "
1436 + "rebases the current work (branch) against it")
1437 self
.verbose
= False
1439 def run(self
, args
):
1443 [upstream
, settings
] = findUpstreamBranchPoint()
1444 if len(upstream
) == 0:
1445 die("Cannot find upstream branchpoint for rebase")
1447 # the branchpoint may be p4/foo~3, so strip off the parent
1448 upstream
= re
.sub("~[0-9]+$", "", upstream
)
1450 print "Rebasing the current branch onto %s" % upstream
1451 oldHead
= read_pipe("git rev-parse HEAD").strip()
1452 system("git rebase %s" % upstream
)
1453 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1456 class P4Clone(P4Sync
):
1458 P4Sync
.__init
__(self
)
1459 self
.description
= "Creates a new git repository and imports from Perforce into it"
1460 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1461 self
.options
.append(
1462 optparse
.make_option("--destination", dest
="cloneDestination",
1463 action
='store', default
=None,
1464 help="where to leave result of the clone"))
1465 self
.cloneDestination
= None
1466 self
.needsGit
= False
1468 def defaultDestination(self
, args
):
1469 ## TODO: use common prefix of args?
1471 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1472 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1473 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1474 depotDir
= re
.sub(r
"/$", "", depotDir
)
1475 return os
.path
.split(depotDir
)[1]
1477 def run(self
, args
):
1481 if self
.keepRepoPath
and not self
.cloneDestination
:
1482 sys
.stderr
.write("Must specify destination for --keep-path\n")
1487 if not self
.cloneDestination
and len(depotPaths
) > 1:
1488 self
.cloneDestination
= depotPaths
[-1]
1489 depotPaths
= depotPaths
[:-1]
1491 for p
in depotPaths
:
1492 if not p
.startswith("//"):
1495 if not self
.cloneDestination
:
1496 self
.cloneDestination
= self
.defaultDestination(args
)
1498 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1499 if not os
.path
.exists(self
.cloneDestination
):
1500 os
.makedirs(self
.cloneDestination
)
1501 os
.chdir(self
.cloneDestination
)
1503 self
.gitdir
= os
.getcwd() + "/.git"
1504 if not P4Sync
.run(self
, depotPaths
):
1506 if self
.branch
!= "master":
1507 if gitBranchExists("refs/remotes/p4/master"):
1508 system("git branch master refs/remotes/p4/master")
1509 system("git checkout -f")
1511 print "Could not detect main branch. No checkout/master branch created."
1515 class P4Branches(Command
):
1517 Command
.__init
__(self
)
1519 self
.description
= ("Shows the git branches that hold imports and their "
1520 + "corresponding perforce depot paths")
1521 self
.verbose
= False
1523 def run(self
, args
):
1524 if originP4BranchesExist():
1525 createOrUpdateBranchesFromOrigin()
1527 cmdline
= "git rev-parse --symbolic "
1528 cmdline
+= " --remotes"
1530 for line
in read_pipe_lines(cmdline
):
1533 if not line
.startswith('p4/') or line
== "p4/HEAD":
1537 log
= extractLogMessageFromGitCommit("refs/remotes/%s" % branch
)
1538 settings
= extractSettingsGitLog(log
)
1540 print "%s <= %s (%s)" % (branch
, ",".join(settings
["depot-paths"]), settings
["change"])
1543 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1545 optparse
.IndentedHelpFormatter
.__init
__(self
)
1547 def format_description(self
, description
):
1549 return description
+ "\n"
1553 def printUsage(commands
):
1554 print "usage: %s <command> [options]" % sys
.argv
[0]
1556 print "valid commands: %s" % ", ".join(commands
)
1558 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1563 "submit" : P4Submit
,
1565 "rebase" : P4Rebase
,
1567 "rollback" : P4RollBack
,
1568 "branches" : P4Branches
1573 if len(sys
.argv
[1:]) == 0:
1574 printUsage(commands
.keys())
1578 cmdName
= sys
.argv
[1]
1580 klass
= commands
[cmdName
]
1583 print "unknown command %s" % cmdName
1585 printUsage(commands
.keys())
1588 options
= cmd
.options
1589 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1593 if len(options
) > 0:
1594 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1596 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1598 description
= cmd
.description
,
1599 formatter
= HelpFormatter())
1601 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1603 verbose
= cmd
.verbose
1605 if cmd
.gitdir
== None:
1606 cmd
.gitdir
= os
.path
.abspath(".git")
1607 if not isValidGitDir(cmd
.gitdir
):
1608 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1609 if os
.path
.exists(cmd
.gitdir
):
1610 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1614 if not isValidGitDir(cmd
.gitdir
):
1615 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1616 cmd
.gitdir
+= "/.git"
1618 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1620 os
.environ
["GIT_DIR"] = cmd
.gitdir
1622 if not cmd
.run(args
):
1626 if __name__
== '__main__':