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
]
236 self
.usage
= "usage: %prog [options]"
239 class P4Debug(Command
):
241 Command
.__init
__(self
)
243 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
246 self
.description
= "A tool to debug the output of p4 -G."
247 self
.needsGit
= False
252 for output
in p4CmdList(" ".join(args
)):
253 print 'Element: %d' % j
258 class P4RollBack(Command
):
260 Command
.__init
__(self
)
262 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
263 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
265 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
267 self
.rollbackLocalBranches
= False
272 maxChange
= int(args
[0])
274 if "p4ExitCode" in p4Cmd("changes -m 1"):
275 die("Problems executing p4");
277 if self
.rollbackLocalBranches
:
278 refPrefix
= "refs/heads/"
279 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
281 refPrefix
= "refs/remotes/"
282 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
285 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
287 ref
= refPrefix
+ line
288 log
= extractLogMessageFromGitCommit(ref
)
289 settings
= extractSettingsGitLog(log
)
291 depotPaths
= settings
['depot-paths']
292 change
= settings
['change']
296 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
297 for p
in depotPaths
]))) == 0:
298 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
299 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
302 while change
and int(change
) > maxChange
:
305 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
306 system("git update-ref %s \"%s^\"" % (ref
, ref
))
307 log
= extractLogMessageFromGitCommit(ref
)
308 settings
= extractSettingsGitLog(log
)
311 depotPaths
= settings
['depot-paths']
312 change
= settings
['change']
315 print "%s rewound to %s" % (ref
, change
)
319 class P4Submit(Command
):
321 Command
.__init
__(self
)
323 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
324 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
325 optparse
.make_option("--origin", dest
="origin"),
326 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
327 optparse
.make_option("--log-substitutions", dest
="substFile"),
328 optparse
.make_option("--dry-run", action
="store_true"),
329 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
330 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
332 self
.description
= "Submit changes from git to the perforce depot."
333 self
.usage
+= " [name of git branch to submit into perforce depot]"
334 self
.firstTime
= True
336 self
.interactive
= True
339 self
.firstTime
= True
341 self
.directSubmit
= False
342 self
.trustMeLikeAFool
= False
344 self
.isWindows
= (platform
.system() == "Windows")
346 self
.logSubstitutions
= {}
347 self
.logSubstitutions
["<enter description here>"] = "%log%"
348 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
351 if len(p4CmdList("opened ...")) > 0:
352 die("You have files opened with perforce! Close them before starting the sync.")
355 if len(self
.config
) > 0 and not self
.reset
:
356 die("Cannot start sync. Previous sync config found at %s\n"
357 "If you want to start submitting again from scratch "
358 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
361 if self
.directSubmit
:
364 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
365 commits
.append(line
.strip())
368 self
.config
["commits"] = commits
370 def prepareLogMessage(self
, template
, message
):
373 for line
in template
.split("\n"):
374 if line
.startswith("#"):
375 result
+= line
+ "\n"
379 for key
in self
.logSubstitutions
.keys():
380 if line
.find(key
) != -1:
381 value
= self
.logSubstitutions
[key
]
382 value
= value
.replace("%log%", message
)
383 if value
!= "@remove@":
384 result
+= line
.replace(key
, value
) + "\n"
389 result
+= line
+ "\n"
393 def prepareSubmitTemplate(self
):
394 # remove lines in the Files section that show changes to files outside the depot path we're committing into
396 inFilesSection
= False
397 for line
in read_pipe_lines("p4 change -o"):
399 if line
.startswith("\t"):
400 # path starts and ends with a tab
402 lastTab
= path
.rfind("\t")
404 path
= path
[:lastTab
]
405 if not path
.startswith(self
.depotPath
):
408 inFilesSection
= False
410 if line
.startswith("Files:"):
411 inFilesSection
= True
417 def applyCommit(self
, id):
418 if self
.directSubmit
:
419 print "Applying local change in working directory/index"
420 diff
= self
.diffStatus
422 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
423 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
425 filesToDelete
= set()
429 path
= line
[1:].strip()
431 system("p4 edit \"%s\"" % path
)
432 editedFiles
.add(path
)
433 elif modifier
== "A":
435 if path
in filesToDelete
:
436 filesToDelete
.remove(path
)
437 elif modifier
== "D":
438 filesToDelete
.add(path
)
439 if path
in filesToAdd
:
440 filesToAdd
.remove(path
)
442 die("unknown modifier %s for %s" % (modifier
, path
))
444 if self
.directSubmit
:
445 diffcmd
= "cat \"%s\"" % self
.diffFile
447 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
448 patchcmd
= diffcmd
+ " | git apply "
449 tryPatchCmd
= patchcmd
+ "--check -"
450 applyPatchCmd
= patchcmd
+ "--check --apply -"
452 if os
.system(tryPatchCmd
) != 0:
453 print "Unfortunately applying the change failed!"
454 print "What do you want to do?"
456 while response
!= "s" and response
!= "a" and response
!= "w":
457 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
458 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
460 print "Skipping! Good luck with the next patches..."
462 elif response
== "a":
463 os
.system(applyPatchCmd
)
464 if len(filesToAdd
) > 0:
465 print "You may also want to call p4 add on the following files:"
466 print " ".join(filesToAdd
)
467 if len(filesToDelete
):
468 print "The following files should be scheduled for deletion with p4 delete:"
469 print " ".join(filesToDelete
)
470 die("Please resolve and submit the conflict manually and "
471 + "continue afterwards with git-p4 submit --continue")
472 elif response
== "w":
473 system(diffcmd
+ " > patch.txt")
474 print "Patch saved to patch.txt in %s !" % self
.clientPath
475 die("Please resolve and submit the conflict manually and "
476 "continue afterwards with git-p4 submit --continue")
478 system(applyPatchCmd
)
481 system("p4 add \"%s\"" % f
)
482 for f
in filesToDelete
:
483 system("p4 revert \"%s\"" % f
)
484 system("p4 delete \"%s\"" % f
)
487 if not self
.directSubmit
:
488 logMessage
= extractLogMessageFromGitCommit(id)
489 logMessage
= logMessage
.replace("\n", "\n\t")
491 logMessage
= logMessage
.replace("\n", "\r\n")
492 logMessage
= logMessage
.strip()
494 template
= self
.prepareSubmitTemplate()
497 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
498 diff
= read_pipe("p4 diff -du ...")
500 for newFile
in filesToAdd
:
501 diff
+= "==== new file ====\n"
502 diff
+= "--- /dev/null\n"
503 diff
+= "+++ %s\n" % newFile
504 f
= open(newFile
, "r")
505 for line
in f
.readlines():
509 separatorLine
= "######## everything below this line is just the diff #######"
510 if platform
.system() == "Windows":
511 separatorLine
+= "\r"
512 separatorLine
+= "\n"
515 if self
.trustMeLikeAFool
:
518 firstIteration
= True
519 while response
== "e":
520 if not firstIteration
:
521 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
522 firstIteration
= False
524 [handle
, fileName
] = tempfile
.mkstemp()
525 tmpFile
= os
.fdopen(handle
, "w+")
526 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
529 if platform
.system() == "Windows":
530 defaultEditor
= "notepad"
531 editor
= os
.environ
.get("EDITOR", defaultEditor
);
532 system(editor
+ " " + fileName
)
533 tmpFile
= open(fileName
, "rb")
534 message
= tmpFile
.read()
537 submitTemplate
= message
[:message
.index(separatorLine
)]
539 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
541 if response
== "y" or response
== "yes":
544 raw_input("Press return to continue...")
546 if self
.directSubmit
:
547 print "Submitting to git first"
548 os
.chdir(self
.oldWorkingDirectory
)
549 write_pipe("git commit -a -F -", submitTemplate
)
550 os
.chdir(self
.clientPath
)
552 write_pipe("p4 submit -i", submitTemplate
)
553 elif response
== "s":
554 for f
in editedFiles
:
555 system("p4 revert \"%s\"" % f
);
557 system("p4 revert \"%s\"" % f
);
559 for f
in filesToDelete
:
560 system("p4 delete \"%s\"" % f
);
563 print "Not submitting!"
564 self
.interactive
= False
566 fileName
= "submit.txt"
567 file = open(fileName
, "w+")
568 file.write(self
.prepareLogMessage(template
, logMessage
))
570 print ("Perforce submit template written as %s. "
571 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
572 % (fileName
, fileName
))
576 self
.master
= currentGitBranch()
577 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
578 die("Detecting current git branch failed!")
580 self
.master
= args
[0]
584 [upstream
, settings
] = findUpstreamBranchPoint()
585 self
.depotPath
= settings
['depot-paths'][0]
586 if len(self
.origin
) == 0:
587 self
.origin
= upstream
590 print "Origin branch is " + self
.origin
592 if len(self
.depotPath
) == 0:
593 print "Internal error: cannot locate perforce depot path from existing branches"
596 self
.clientPath
= p4Where(self
.depotPath
)
598 if len(self
.clientPath
) == 0:
599 print "Error: Cannot locate perforce checkout of %s in client view" % self
.depotPath
602 print "Perforce checkout for depot path %s located at %s" % (self
.depotPath
, self
.clientPath
)
603 self
.oldWorkingDirectory
= os
.getcwd()
605 if self
.directSubmit
:
606 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
607 if len(self
.diffStatus
) == 0:
608 print "No changes in working directory to submit."
610 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
611 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
612 f
= open(self
.diffFile
, "wb")
616 os
.chdir(self
.clientPath
)
617 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
618 if response
== "y" or response
== "yes":
619 system("p4 sync ...")
622 self
.firstTime
= True
624 if len(self
.substFile
) > 0:
625 for line
in open(self
.substFile
, "r").readlines():
626 tokens
= line
.strip().split("=")
627 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
630 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
631 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
636 commits
= self
.config
.get("commits", [])
638 while len(commits
) > 0:
639 self
.firstTime
= False
641 commits
= commits
[1:]
642 self
.config
["commits"] = commits
643 self
.applyCommit(commit
)
644 if not self
.interactive
:
649 if self
.directSubmit
:
650 os
.remove(self
.diffFile
)
652 if len(commits
) == 0:
654 print "No changes found to apply between %s and current HEAD" % self
.origin
656 print "All changes applied!"
657 os
.chdir(self
.oldWorkingDirectory
)
658 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
659 if response
== "y" or response
== "yes":
662 os
.remove(self
.configFile
)
666 class P4Sync(Command
):
668 Command
.__init
__(self
)
670 optparse
.make_option("--branch", dest
="branch"),
671 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
672 optparse
.make_option("--changesfile", dest
="changesFile"),
673 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
674 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
675 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
676 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
677 help="Import into refs/heads/ , not refs/remotes"),
678 optparse
.make_option("--max-changes", dest
="maxChanges"),
679 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
680 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
682 self
.description
= """Imports from Perforce into a git repository.\n
684 //depot/my/project/ -- to import the current head
685 //depot/my/project/@all -- to import everything
686 //depot/my/project/@1,6 -- to import only from revision 1 to 6
688 (a ... is not needed in the path p4 specification, it's added implicitly)"""
690 self
.usage
+= " //depot/path[@revRange]"
692 self
.createdBranches
= Set()
693 self
.committedChanges
= Set()
695 self
.detectBranches
= False
696 self
.detectLabels
= False
697 self
.changesFile
= ""
698 self
.syncWithOrigin
= True
700 self
.importIntoRemotes
= True
702 self
.isWindows
= (platform
.system() == "Windows")
703 self
.keepRepoPath
= False
704 self
.depotPaths
= None
705 self
.p4BranchesInGit
= []
707 if gitConfig("git-p4.syncFromOrigin") == "false":
708 self
.syncWithOrigin
= False
710 def extractFilesFromCommit(self
, commit
):
713 while commit
.has_key("depotFile%s" % fnum
):
714 path
= commit
["depotFile%s" % fnum
]
716 found
= [p
for p
in self
.depotPaths
717 if path
.startswith (p
)]
724 file["rev"] = commit
["rev%s" % fnum
]
725 file["action"] = commit
["action%s" % fnum
]
726 file["type"] = commit
["type%s" % fnum
]
731 def stripRepoPath(self
, path
, prefixes
):
732 if self
.keepRepoPath
:
733 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
736 if path
.startswith(p
):
741 def splitFilesIntoBranches(self
, commit
):
744 while commit
.has_key("depotFile%s" % fnum
):
745 path
= commit
["depotFile%s" % fnum
]
746 found
= [p
for p
in self
.depotPaths
747 if path
.startswith (p
)]
754 file["rev"] = commit
["rev%s" % fnum
]
755 file["action"] = commit
["action%s" % fnum
]
756 file["type"] = commit
["type%s" % fnum
]
759 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
761 for branch
in self
.knownBranches
.keys():
763 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
764 if relPath
.startswith(branch
+ "/"):
765 if branch
not in branches
:
766 branches
[branch
] = []
767 branches
[branch
].append(file)
772 ## Should move this out, doesn't use SELF.
773 def readP4Files(self
, files
):
774 files
= [f
for f
in files
775 if f
['action'] != 'delete']
780 filedata
= p4CmdList('-x - print',
781 stdin
='\n'.join(['%s#%s' % (f
['path'], f
['rev'])
784 if "p4ExitCode" in filedata
[0]:
785 die("Problems executing p4. Error: [%d]."
786 % (filedata
[0]['p4ExitCode']));
790 while j
< len(filedata
):
794 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
796 text
+= filedata
[j
]['data']
800 if not stat
.has_key('depotFile'):
801 sys
.stderr
.write("p4 print fails with: %s\n" % repr(stat
))
804 contents
[stat
['depotFile']] = text
807 assert not f
.has_key('data')
808 f
['data'] = contents
[f
['path']]
810 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
811 epoch
= details
["time"]
812 author
= details
["user"]
815 print "commit into %s" % branch
817 # start with reading files; if that fails, we should not
821 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
824 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
826 self
.readP4Files(files
)
831 self
.gitStream
.write("commit %s\n" % branch
)
832 # gitStream.write("mark :%s\n" % details["change"])
833 self
.committedChanges
.add(int(details
["change"]))
835 if author
not in self
.users
:
836 self
.getUserMapFromPerforceServer()
837 if author
in self
.users
:
838 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
840 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
842 self
.gitStream
.write("committer %s\n" % committer
)
844 self
.gitStream
.write("data <<EOT\n")
845 self
.gitStream
.write(details
["desc"])
846 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s"
847 % (','.join (branchPrefixes
), details
["change"]))
848 if len(details
['options']) > 0:
849 self
.gitStream
.write(": options = %s" % details
['options'])
850 self
.gitStream
.write("]\nEOT\n\n")
854 print "parent %s" % parent
855 self
.gitStream
.write("from %s\n" % parent
)
858 if file["type"] == "apple":
859 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
862 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
863 if file["action"] == "delete":
864 self
.gitStream
.write("D %s\n" % relPath
)
869 if file["type"].startswith("x"):
871 elif file["type"] == "symlink":
873 # p4 print on a symlink contains "target\n", so strip it off
876 if self
.isWindows
and file["type"].endswith("text"):
877 data
= data
.replace("\r\n", "\n")
879 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
880 self
.gitStream
.write("data %s\n" % len(data
))
881 self
.gitStream
.write(data
)
882 self
.gitStream
.write("\n")
884 self
.gitStream
.write("\n")
886 change
= int(details
["change"])
888 if self
.labels
.has_key(change
):
889 label
= self
.labels
[change
]
890 labelDetails
= label
[0]
891 labelRevisions
= label
[1]
893 print "Change %s is labelled %s" % (change
, labelDetails
)
895 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
896 for p
in branchPrefixes
]))
898 if len(files
) == len(labelRevisions
):
902 if info
["action"] == "delete":
904 cleanedFiles
[info
["depotFile"]] = info
["rev"]
906 if cleanedFiles
== labelRevisions
:
907 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
908 self
.gitStream
.write("from %s\n" % branch
)
910 owner
= labelDetails
["Owner"]
912 if author
in self
.users
:
913 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
915 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
916 self
.gitStream
.write("tagger %s\n" % tagger
)
917 self
.gitStream
.write("data <<EOT\n")
918 self
.gitStream
.write(labelDetails
["Description"])
919 self
.gitStream
.write("EOT\n\n")
923 print ("Tag %s does not match with change %s: files do not match."
924 % (labelDetails
["label"], change
))
928 print ("Tag %s does not match with change %s: file count is different."
929 % (labelDetails
["label"], change
))
931 def getUserCacheFilename(self
):
932 home
= os
.environ
.get("HOME", os
.environ
.get("USERPROFILE"))
933 return home
+ "/.gitp4-usercache.txt"
935 def getUserMapFromPerforceServer(self
):
936 if self
.userMapFromPerforceServer
:
940 for output
in p4CmdList("users"):
941 if not output
.has_key("User"):
943 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
947 for (key
, val
) in self
.users
.items():
948 s
+= "%s\t%s\n" % (key
, val
)
950 open(self
.getUserCacheFilename(), "wb").write(s
)
951 self
.userMapFromPerforceServer
= True
953 def loadUserMapFromCache(self
):
955 self
.userMapFromPerforceServer
= False
957 cache
= open(self
.getUserCacheFilename(), "rb")
958 lines
= cache
.readlines()
961 entry
= line
.strip().split("\t")
962 self
.users
[entry
[0]] = entry
[1]
964 self
.getUserMapFromPerforceServer()
969 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
970 if len(l
) > 0 and not self
.silent
:
971 print "Finding files belonging to labels in %s" % `self
.depotPath`
974 label
= output
["label"]
978 print "Querying files for label %s" % label
979 for file in p4CmdList("files "
980 + ' '.join (["%s...@%s" % (p
, label
)
981 for p
in self
.depotPaths
])):
982 revisions
[file["depotFile"]] = file["rev"]
983 change
= int(file["change"])
984 if change
> newestChange
:
985 newestChange
= change
987 self
.labels
[newestChange
] = [output
, revisions
]
990 print "Label changes: %s" % self
.labels
.keys()
992 def guessProjectName(self
):
993 for p
in self
.depotPaths
:
996 p
= p
[p
.strip().rfind("/") + 1:]
997 if not p
.endswith("/"):
1001 def getBranchMapping(self
):
1002 lostAndFoundBranches
= set()
1004 for info
in p4CmdList("branches"):
1005 details
= p4Cmd("branch -o %s" % info
["branch"])
1007 while details
.has_key("View%s" % viewIdx
):
1008 paths
= details
["View%s" % viewIdx
].split(" ")
1009 viewIdx
= viewIdx
+ 1
1010 # require standard //depot/foo/... //depot/bar/... mapping
1011 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
1014 destination
= paths
[1]
1016 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
1017 source
= source
[len(self
.depotPaths
[0]):-4]
1018 destination
= destination
[len(self
.depotPaths
[0]):-4]
1020 if destination
in self
.knownBranches
:
1022 print "p4 branch %s defines a mapping from %s to %s" % (info
["branch"], source
, destination
)
1023 print "but there exists another mapping from %s to %s already!" % (self
.knownBranches
[destination
], destination
)
1026 self
.knownBranches
[destination
] = source
1028 lostAndFoundBranches
.discard(destination
)
1030 if source
not in self
.knownBranches
:
1031 lostAndFoundBranches
.add(source
)
1034 for branch
in lostAndFoundBranches
:
1035 self
.knownBranches
[branch
] = branch
1037 def listExistingP4GitBranches(self
):
1038 # branches holds mapping from name to commit
1039 branches
= p4BranchesInGit(self
.importIntoRemotes
)
1040 self
.p4BranchesInGit
= branches
.keys()
1041 for branch
in branches
.keys():
1042 self
.initialParents
[self
.refPrefix
+ branch
] = branches
[branch
]
1044 def createOrUpdateBranchesFromOrigin(self
):
1046 print ("Creating/updating branch(es) in %s based on origin branch(es)"
1049 originPrefix
= "origin/p4/"
1051 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
1053 if (not line
.startswith(originPrefix
)) or line
.endswith("HEAD"):
1056 headName
= line
[len(originPrefix
):]
1057 remoteHead
= self
.refPrefix
+ headName
1060 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
1061 if (not original
.has_key('depot-paths')
1062 or not original
.has_key('change')):
1066 if not gitBranchExists(remoteHead
):
1068 print "creating %s" % remoteHead
1071 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
1072 if settings
.has_key('change') > 0:
1073 if settings
['depot-paths'] == original
['depot-paths']:
1074 originP4Change
= int(original
['change'])
1075 p4Change
= int(settings
['change'])
1076 if originP4Change
> p4Change
:
1077 print ("%s (%s) is newer than %s (%s). "
1078 "Updating p4 branch from origin."
1079 % (originHead
, originP4Change
,
1080 remoteHead
, p4Change
))
1083 print ("Ignoring: %s was imported from %s while "
1084 "%s was imported from %s"
1085 % (originHead
, ','.join(original
['depot-paths']),
1086 remoteHead
, ','.join(settings
['depot-paths'])))
1089 system("git update-ref %s %s" % (remoteHead
, originHead
))
1091 def updateOptionDict(self
, d
):
1093 if self
.keepRepoPath
:
1094 option_keys
['keepRepoPath'] = 1
1096 d
["options"] = ' '.join(sorted(option_keys
.keys()))
1098 def readOptions(self
, d
):
1099 self
.keepRepoPath
= (d
.has_key('options')
1100 and ('keepRepoPath' in d
['options']))
1102 def run(self
, args
):
1103 self
.depotPaths
= []
1104 self
.changeRange
= ""
1105 self
.initialParent
= ""
1106 self
.previousDepotPaths
= []
1108 # map from branch depot path to parent branch
1109 self
.knownBranches
= {}
1110 self
.initialParents
= {}
1111 self
.hasOrigin
= gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
1112 if not self
.syncWithOrigin
:
1113 self
.hasOrigin
= False
1115 if self
.importIntoRemotes
:
1116 self
.refPrefix
= "refs/remotes/p4/"
1118 self
.refPrefix
= "refs/heads/p4/"
1120 if self
.syncWithOrigin
and self
.hasOrigin
:
1122 print "Syncing with origin first by calling git fetch origin"
1123 system("git fetch origin")
1125 if len(self
.branch
) == 0:
1126 self
.branch
= self
.refPrefix
+ "master"
1127 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1128 system("git update-ref %s refs/heads/p4" % self
.branch
)
1129 system("git branch -D p4");
1130 # create it /after/ importing, when master exists
1131 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
1132 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1134 # TODO: should always look at previous commits,
1135 # merge with previous imports, if possible.
1138 self
.createOrUpdateBranchesFromOrigin()
1139 self
.listExistingP4GitBranches()
1141 if len(self
.p4BranchesInGit
) > 1:
1143 print "Importing from/into multiple branches"
1144 self
.detectBranches
= True
1147 print "branches: %s" % self
.p4BranchesInGit
1150 for branch
in self
.p4BranchesInGit
:
1151 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1153 settings
= extractSettingsGitLog(logMsg
)
1155 self
.readOptions(settings
)
1156 if (settings
.has_key('depot-paths')
1157 and settings
.has_key ('change')):
1158 change
= int(settings
['change']) + 1
1159 p4Change
= max(p4Change
, change
)
1161 depotPaths
= sorted(settings
['depot-paths'])
1162 if self
.previousDepotPaths
== []:
1163 self
.previousDepotPaths
= depotPaths
1166 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1167 for i
in range(0, min(len(cur
), len(prev
))):
1168 if cur
[i
] <> prev
[i
]:
1172 paths
.append (cur
[:i
+ 1])
1174 self
.previousDepotPaths
= paths
1177 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1178 self
.changeRange
= "@%s,#head" % p4Change
1179 if not self
.detectBranches
:
1180 self
.initialParent
= parseRevision(self
.branch
)
1181 if not self
.silent
and not self
.detectBranches
:
1182 print "Performing incremental import into %s git branch" % self
.branch
1184 if not self
.branch
.startswith("refs/"):
1185 self
.branch
= "refs/heads/" + self
.branch
1187 if len(args
) == 0 and self
.depotPaths
:
1189 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1191 if self
.depotPaths
and self
.depotPaths
!= args
:
1192 print ("previous import used depot path %s and now %s was specified. "
1193 "This doesn't work!" % (' '.join (self
.depotPaths
),
1197 self
.depotPaths
= sorted(args
)
1203 for p
in self
.depotPaths
:
1204 if p
.find("@") != -1:
1205 atIdx
= p
.index("@")
1206 self
.changeRange
= p
[atIdx
:]
1207 if self
.changeRange
== "@all":
1208 self
.changeRange
= ""
1209 elif ',' not in self
.changeRange
:
1210 self
.revision
= self
.changeRange
1211 self
.changeRange
= ""
1213 elif p
.find("#") != -1:
1214 hashIdx
= p
.index("#")
1215 self
.revision
= p
[hashIdx
:]
1217 elif self
.previousDepotPaths
== []:
1218 self
.revision
= "#head"
1220 p
= re
.sub ("\.\.\.$", "", p
)
1221 if not p
.endswith("/"):
1226 self
.depotPaths
= newPaths
1229 self
.loadUserMapFromCache()
1231 if self
.detectLabels
:
1234 if self
.detectBranches
:
1235 ## FIXME - what's a P4 projectName ?
1236 self
.projectName
= self
.guessProjectName()
1238 if not self
.hasOrigin
:
1239 self
.getBranchMapping();
1241 print "p4-git branches: %s" % self
.p4BranchesInGit
1242 print "initial parents: %s" % self
.initialParents
1243 for b
in self
.p4BranchesInGit
:
1247 b
= b
[len(self
.projectName
):]
1248 self
.createdBranches
.add(b
)
1250 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1252 importProcess
= subprocess
.Popen(["git", "fast-import"],
1253 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1254 stderr
=subprocess
.PIPE
);
1255 self
.gitOutput
= importProcess
.stdout
1256 self
.gitStream
= importProcess
.stdin
1257 self
.gitError
= importProcess
.stderr
1260 print "Doing initial import of %s from revision %s into %s" % (' '.join(self
.depotPaths
), self
.revision
, self
.branch
)
1262 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1263 details
["desc"] = ("Initial import of %s from the state at revision %s"
1264 % (' '.join(self
.depotPaths
), self
.revision
))
1265 details
["change"] = self
.revision
1269 for info
in p4CmdList("files "
1270 + ' '.join(["%s...%s"
1271 % (p
, self
.revision
)
1272 for p
in self
.depotPaths
])):
1274 if info
['code'] == 'error':
1275 sys
.stderr
.write("p4 returned an error: %s\n"
1280 change
= int(info
["change"])
1281 if change
> newestRevision
:
1282 newestRevision
= change
1284 if info
["action"] == "delete":
1285 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1286 #fileCnt = fileCnt + 1
1289 for prop
in ["depotFile", "rev", "action", "type" ]:
1290 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1292 fileCnt
= fileCnt
+ 1
1294 details
["change"] = newestRevision
1295 self
.updateOptionDict(details
)
1297 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1299 print "IO error with git fast-import. Is your git version recent enough?"
1300 print self
.gitError
.read()
1305 if len(self
.changesFile
) > 0:
1306 output
= open(self
.changesFile
).readlines()
1309 changeSet
.add(int(line
))
1311 for change
in changeSet
:
1312 changes
.append(change
)
1317 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1319 assert self
.depotPaths
1320 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1321 for p
in self
.depotPaths
]))
1324 changeNum
= line
.split(" ")[1]
1325 changes
.append(changeNum
)
1329 if len(self
.maxChanges
) > 0:
1330 changes
= changes
[:min(int(self
.maxChanges
), len(changes
))]
1332 if len(changes
) == 0:
1334 print "No changes to import!"
1337 if not self
.silent
and not self
.detectBranches
:
1338 print "Import destination: %s" % self
.branch
1340 self
.updatedBranches
= set()
1343 for change
in changes
:
1344 description
= p4Cmd("describe %s" % change
)
1345 self
.updateOptionDict(description
)
1348 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1353 if self
.detectBranches
:
1354 branches
= self
.splitFilesIntoBranches(description
)
1355 for branch
in branches
.keys():
1357 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1361 filesForCommit
= branches
[branch
]
1364 print "branch is %s" % branch
1366 self
.updatedBranches
.add(branch
)
1368 if branch
not in self
.createdBranches
:
1369 self
.createdBranches
.add(branch
)
1370 parent
= self
.knownBranches
[branch
]
1371 if parent
== branch
:
1374 print "parent determined through known branches: %s" % parent
1376 # main branch? use master
1377 if branch
== "main":
1382 branch
= self
.projectName
+ branch
1384 if parent
== "main":
1386 elif len(parent
) > 0:
1388 parent
= self
.projectName
+ parent
1390 branch
= self
.refPrefix
+ branch
1392 parent
= self
.refPrefix
+ parent
1395 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1397 if len(parent
) == 0 and branch
in self
.initialParents
:
1398 parent
= self
.initialParents
[branch
]
1399 del self
.initialParents
[branch
]
1401 self
.commit(description
, filesForCommit
, branch
, [branchPrefix
], parent
)
1403 files
= self
.extractFilesFromCommit(description
)
1404 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1406 self
.initialParent
= ""
1408 print self
.gitError
.read()
1413 if len(self
.updatedBranches
) > 0:
1414 sys
.stdout
.write("Updated branches: ")
1415 for b
in self
.updatedBranches
:
1416 sys
.stdout
.write("%s " % b
)
1417 sys
.stdout
.write("\n")
1420 self
.gitStream
.close()
1421 if importProcess
.wait() != 0:
1422 die("fast-import failed: %s" % self
.gitError
.read())
1423 self
.gitOutput
.close()
1424 self
.gitError
.close()
1428 class P4Rebase(Command
):
1430 Command
.__init
__(self
)
1432 self
.description
= ("Fetches the latest revision from perforce and "
1433 + "rebases the current work (branch) against it")
1434 self
.verbose
= False
1436 def run(self
, args
):
1440 [upstream
, settings
] = findUpstreamBranchPoint()
1441 if len(upstream
) == 0:
1442 die("Cannot find upstream branchpoint for rebase")
1444 # the branchpoint may be p4/foo~3, so strip off the parent
1445 upstream
= re
.sub("~[0-9]+$", "", upstream
)
1447 print "Rebasing the current branch onto %s" % upstream
1448 oldHead
= read_pipe("git rev-parse HEAD").strip()
1449 system("git rebase %s" % upstream
)
1450 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1453 class P4Clone(P4Sync
):
1455 P4Sync
.__init
__(self
)
1456 self
.description
= "Creates a new git repository and imports from Perforce into it"
1457 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1458 self
.options
.append(
1459 optparse
.make_option("--destination", dest
="cloneDestination",
1460 action
='store', default
=None,
1461 help="where to leave result of the clone"))
1462 self
.cloneDestination
= None
1463 self
.needsGit
= False
1465 def defaultDestination(self
, args
):
1466 ## TODO: use common prefix of args?
1468 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1469 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1470 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1471 depotDir
= re
.sub(r
"/$", "", depotDir
)
1472 return os
.path
.split(depotDir
)[1]
1474 def run(self
, args
):
1478 if self
.keepRepoPath
and not self
.cloneDestination
:
1479 sys
.stderr
.write("Must specify destination for --keep-path\n")
1484 if not self
.cloneDestination
and len(depotPaths
) > 1:
1485 self
.cloneDestination
= depotPaths
[-1]
1486 depotPaths
= depotPaths
[:-1]
1488 for p
in depotPaths
:
1489 if not p
.startswith("//"):
1492 if not self
.cloneDestination
:
1493 self
.cloneDestination
= self
.defaultDestination(args
)
1495 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1496 if not os
.path
.exists(self
.cloneDestination
):
1497 os
.makedirs(self
.cloneDestination
)
1498 os
.chdir(self
.cloneDestination
)
1500 self
.gitdir
= os
.getcwd() + "/.git"
1501 if not P4Sync
.run(self
, depotPaths
):
1503 if self
.branch
!= "master":
1504 if gitBranchExists("refs/remotes/p4/master"):
1505 system("git branch master refs/remotes/p4/master")
1506 system("git checkout -f")
1508 print "Could not detect main branch. No checkout/master branch created."
1512 class P4Branches(Command
):
1514 Command
.__init
__(self
)
1516 self
.description
= ("Shows the git branches that hold imports and their "
1517 + "corresponding perforce depot paths")
1518 self
.verbose
= False
1520 def run(self
, args
):
1521 cmdline
= "git rev-parse --symbolic "
1522 cmdline
+= " --remotes"
1524 for line
in read_pipe_lines(cmdline
):
1527 if not line
.startswith('p4/') or line
== "p4/HEAD":
1531 log
= extractLogMessageFromGitCommit("refs/remotes/%s" % branch
)
1532 settings
= extractSettingsGitLog(log
)
1534 print "%s <= %s (%s)" % (branch
, ",".join(settings
["depot-paths"]), settings
["change"])
1537 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1539 optparse
.IndentedHelpFormatter
.__init
__(self
)
1541 def format_description(self
, description
):
1543 return description
+ "\n"
1547 def printUsage(commands
):
1548 print "usage: %s <command> [options]" % sys
.argv
[0]
1550 print "valid commands: %s" % ", ".join(commands
)
1552 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1557 "submit" : P4Submit
,
1559 "rebase" : P4Rebase
,
1561 "rollback" : P4RollBack
,
1562 "branches" : P4Branches
1567 if len(sys
.argv
[1:]) == 0:
1568 printUsage(commands
.keys())
1572 cmdName
= sys
.argv
[1]
1574 klass
= commands
[cmdName
]
1577 print "unknown command %s" % cmdName
1579 printUsage(commands
.keys())
1582 options
= cmd
.options
1583 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1587 if len(options
) > 0:
1588 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1590 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1592 description
= cmd
.description
,
1593 formatter
= HelpFormatter())
1595 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1597 verbose
= cmd
.verbose
1599 if cmd
.gitdir
== None:
1600 cmd
.gitdir
= os
.path
.abspath(".git")
1601 if not isValidGitDir(cmd
.gitdir
):
1602 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1603 if os
.path
.exists(cmd
.gitdir
):
1604 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1608 if not isValidGitDir(cmd
.gitdir
):
1609 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1610 cmd
.gitdir
+= "/.git"
1612 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1614 os
.environ
["GIT_DIR"] = cmd
.gitdir
1616 if not cmd
.run(args
):
1620 if __name__
== '__main__':