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 cmd
= "p4 -G %s" % cmd
69 sys
.stderr
.write("Opening pipe: %s\n" % cmd
)
70 pipe
= os
.popen(cmd
, "rb")
75 entry
= marshal
.load(pipe
)
79 exitCode
= pipe
.close()
82 entry
["p4ExitCode"] = exitCode
94 def p4Where(depotPath
):
95 if not depotPath
.endswith("/"):
97 output
= p4Cmd("where %s..." % depotPath
)
98 if output
["code"] == "error":
102 clientPath
= output
.get("path")
103 elif "data" in output
:
104 data
= output
.get("data")
105 lastSpace
= data
.rfind(" ")
106 clientPath
= data
[lastSpace
+ 1:]
108 if clientPath
.endswith("..."):
109 clientPath
= clientPath
[:-3]
112 def currentGitBranch():
113 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
115 def isValidGitDir(path
):
116 if (os
.path
.exists(path
+ "/HEAD")
117 and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects")):
121 def parseRevision(ref
):
122 return read_pipe("git rev-parse %s" % ref
).strip()
124 def extractLogMessageFromGitCommit(commit
):
127 ## fixme: title is first line of commit, not 1st paragraph.
129 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
138 def extractSettingsGitLog(log
):
140 for line
in log
.split("\n"):
142 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
146 assignments
= m
.group(1).split (':')
147 for a
in assignments
:
149 key
= vals
[0].strip()
150 val
= ('='.join (vals
[1:])).strip()
151 if val
.endswith ('\"') and val
.startswith('"'):
156 paths
= values
.get("depot-paths")
158 paths
= values
.get("depot-path")
160 values
['depot-paths'] = paths
.split(',')
163 def gitBranchExists(branch
):
164 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
165 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
166 return proc
.wait() == 0;
169 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
173 self
.usage
= "usage: %prog [options]"
176 class P4Debug(Command
):
178 Command
.__init
__(self
)
180 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
183 self
.description
= "A tool to debug the output of p4 -G."
184 self
.needsGit
= False
189 for output
in p4CmdList(" ".join(args
)):
190 print 'Element: %d' % j
195 class P4RollBack(Command
):
197 Command
.__init
__(self
)
199 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
200 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
202 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
204 self
.rollbackLocalBranches
= False
209 maxChange
= int(args
[0])
211 if "p4ExitCode" in p4Cmd("changes -m 1"):
212 die("Problems executing p4");
214 if self
.rollbackLocalBranches
:
215 refPrefix
= "refs/heads/"
216 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
218 refPrefix
= "refs/remotes/"
219 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
222 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
224 ref
= refPrefix
+ line
225 log
= extractLogMessageFromGitCommit(ref
)
226 settings
= extractSettingsGitLog(log
)
228 depotPaths
= settings
['depot-paths']
229 change
= settings
['change']
233 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
234 for p
in depotPaths
]))) == 0:
235 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
236 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
239 while change
and int(change
) > maxChange
:
242 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
243 system("git update-ref %s \"%s^\"" % (ref
, ref
))
244 log
= extractLogMessageFromGitCommit(ref
)
245 settings
= extractSettingsGitLog(log
)
248 depotPaths
= settings
['depot-paths']
249 change
= settings
['change']
252 print "%s rewound to %s" % (ref
, change
)
256 class P4Submit(Command
):
258 Command
.__init
__(self
)
260 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
261 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
262 optparse
.make_option("--origin", dest
="origin"),
263 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
264 optparse
.make_option("--log-substitutions", dest
="substFile"),
265 optparse
.make_option("--dry-run", action
="store_true"),
266 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
267 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
269 self
.description
= "Submit changes from git to the perforce depot."
270 self
.usage
+= " [name of git branch to submit into perforce depot]"
271 self
.firstTime
= True
273 self
.interactive
= True
276 self
.firstTime
= True
278 self
.directSubmit
= False
279 self
.trustMeLikeAFool
= False
281 self
.isWindows
= (platform
.system() == "Windows")
283 self
.logSubstitutions
= {}
284 self
.logSubstitutions
["<enter description here>"] = "%log%"
285 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
288 if len(p4CmdList("opened ...")) > 0:
289 die("You have files opened with perforce! Close them before starting the sync.")
292 if len(self
.config
) > 0 and not self
.reset
:
293 die("Cannot start sync. Previous sync config found at %s\n"
294 "If you want to start submitting again from scratch "
295 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
298 if self
.directSubmit
:
301 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
302 commits
.append(line
.strip())
305 self
.config
["commits"] = commits
307 def prepareLogMessage(self
, template
, message
):
310 for line
in template
.split("\n"):
311 if line
.startswith("#"):
312 result
+= line
+ "\n"
316 for key
in self
.logSubstitutions
.keys():
317 if line
.find(key
) != -1:
318 value
= self
.logSubstitutions
[key
]
319 value
= value
.replace("%log%", message
)
320 if value
!= "@remove@":
321 result
+= line
.replace(key
, value
) + "\n"
326 result
+= line
+ "\n"
330 def applyCommit(self
, id):
331 if self
.directSubmit
:
332 print "Applying local change in working directory/index"
333 diff
= self
.diffStatus
335 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
336 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
338 filesToDelete
= set()
342 path
= line
[1:].strip()
344 system("p4 edit \"%s\"" % path
)
345 editedFiles
.add(path
)
346 elif modifier
== "A":
348 if path
in filesToDelete
:
349 filesToDelete
.remove(path
)
350 elif modifier
== "D":
351 filesToDelete
.add(path
)
352 if path
in filesToAdd
:
353 filesToAdd
.remove(path
)
355 die("unknown modifier %s for %s" % (modifier
, path
))
357 if self
.directSubmit
:
358 diffcmd
= "cat \"%s\"" % self
.diffFile
360 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
361 patchcmd
= diffcmd
+ " | git apply "
362 tryPatchCmd
= patchcmd
+ "--check -"
363 applyPatchCmd
= patchcmd
+ "--check --apply -"
365 if os
.system(tryPatchCmd
) != 0:
366 print "Unfortunately applying the change failed!"
367 print "What do you want to do?"
369 while response
!= "s" and response
!= "a" and response
!= "w":
370 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
371 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
373 print "Skipping! Good luck with the next patches..."
375 elif response
== "a":
376 os
.system(applyPatchCmd
)
377 if len(filesToAdd
) > 0:
378 print "You may also want to call p4 add on the following files:"
379 print " ".join(filesToAdd
)
380 if len(filesToDelete
):
381 print "The following files should be scheduled for deletion with p4 delete:"
382 print " ".join(filesToDelete
)
383 die("Please resolve and submit the conflict manually and "
384 + "continue afterwards with git-p4 submit --continue")
385 elif response
== "w":
386 system(diffcmd
+ " > patch.txt")
387 print "Patch saved to patch.txt in %s !" % self
.clientPath
388 die("Please resolve and submit the conflict manually and "
389 "continue afterwards with git-p4 submit --continue")
391 system(applyPatchCmd
)
394 system("p4 add %s" % f
)
395 for f
in filesToDelete
:
396 system("p4 revert %s" % f
)
397 system("p4 delete %s" % f
)
400 if not self
.directSubmit
:
401 logMessage
= extractLogMessageFromGitCommit(id)
402 logMessage
= logMessage
.replace("\n", "\n\t")
404 logMessage
= logMessage
.replace("\n", "\r\n")
405 logMessage
= logMessage
.strip()
407 template
= read_pipe("p4 change -o")
410 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
411 diff
= read_pipe("p4 diff -du ...")
413 for newFile
in filesToAdd
:
414 diff
+= "==== new file ====\n"
415 diff
+= "--- /dev/null\n"
416 diff
+= "+++ %s\n" % newFile
417 f
= open(newFile
, "r")
418 for line
in f
.readlines():
422 separatorLine
= "######## everything below this line is just the diff #######"
423 if platform
.system() == "Windows":
424 separatorLine
+= "\r"
425 separatorLine
+= "\n"
428 if self
.trustMeLikeAFool
:
431 firstIteration
= True
432 while response
== "e":
433 if not firstIteration
:
434 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
435 firstIteration
= False
437 [handle
, fileName
] = tempfile
.mkstemp()
438 tmpFile
= os
.fdopen(handle
, "w+")
439 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
442 if platform
.system() == "Windows":
443 defaultEditor
= "notepad"
444 editor
= os
.environ
.get("EDITOR", defaultEditor
);
445 system(editor
+ " " + fileName
)
446 tmpFile
= open(fileName
, "rb")
447 message
= tmpFile
.read()
450 submitTemplate
= message
[:message
.index(separatorLine
)]
452 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
454 if response
== "y" or response
== "yes":
457 raw_input("Press return to continue...")
459 if self
.directSubmit
:
460 print "Submitting to git first"
461 os
.chdir(self
.oldWorkingDirectory
)
462 write_pipe("git commit -a -F -", submitTemplate
)
463 os
.chdir(self
.clientPath
)
465 write_pipe("p4 submit -i", submitTemplate
)
466 elif response
== "s":
467 for f
in editedFiles
:
468 system("p4 revert \"%s\"" % f
);
470 system("p4 revert \"%s\"" % f
);
472 for f
in filesToDelete
:
473 system("p4 delete \"%s\"" % f
);
476 print "Not submitting!"
477 self
.interactive
= False
479 fileName
= "submit.txt"
480 file = open(fileName
, "w+")
481 file.write(self
.prepareLogMessage(template
, logMessage
))
483 print ("Perforce submit template written as %s. "
484 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
485 % (fileName
, fileName
))
489 self
.master
= currentGitBranch()
490 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
491 die("Detecting current git branch failed!")
493 self
.master
= args
[0]
499 while parent
< 65535:
500 commit
= "HEAD~%s" % parent
501 log
= extractLogMessageFromGitCommit(commit
)
502 settings
= extractSettingsGitLog(log
)
503 if not settings
.has_key("depot-paths"):
507 depotPath
= settings
['depot-paths'][0]
509 if len(self
.origin
) == 0:
510 names
= read_pipe_lines("git name-rev '--refs=refs/remotes/p4/*' '%s'" % commit
)
512 # strip away the beginning of 'HEAD~42 refs/remotes/p4/foo'
513 self
.origin
= names
[0].strip()[len(commit
) + 1:]
518 print "Origin branch is " + self
.origin
520 if len(depotPath
) == 0:
521 print "Internal error: cannot locate perforce depot path from existing branches"
524 self
.clientPath
= p4Where(depotPath
)
526 if len(self
.clientPath
) == 0:
527 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
530 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
531 self
.oldWorkingDirectory
= os
.getcwd()
533 if self
.directSubmit
:
534 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
535 if len(self
.diffStatus
) == 0:
536 print "No changes in working directory to submit."
538 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
539 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
540 f
= open(self
.diffFile
, "wb")
544 os
.chdir(self
.clientPath
)
545 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
546 if response
== "y" or response
== "yes":
547 system("p4 sync ...")
550 self
.firstTime
= True
552 if len(self
.substFile
) > 0:
553 for line
in open(self
.substFile
, "r").readlines():
554 tokens
= line
.strip().split("=")
555 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
558 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
559 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
564 commits
= self
.config
.get("commits", [])
566 while len(commits
) > 0:
567 self
.firstTime
= False
569 commits
= commits
[1:]
570 self
.config
["commits"] = commits
571 self
.applyCommit(commit
)
572 if not self
.interactive
:
577 if self
.directSubmit
:
578 os
.remove(self
.diffFile
)
580 if len(commits
) == 0:
582 print "No changes found to apply between %s and current HEAD" % self
.origin
584 print "All changes applied!"
585 os
.chdir(self
.oldWorkingDirectory
)
586 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
587 if response
== "y" or response
== "yes":
590 os
.remove(self
.configFile
)
594 class P4Sync(Command
):
596 Command
.__init
__(self
)
598 optparse
.make_option("--branch", dest
="branch"),
599 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
600 optparse
.make_option("--changesfile", dest
="changesFile"),
601 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
602 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
603 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
604 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
605 help="Import into refs/heads/ , not refs/remotes"),
606 optparse
.make_option("--max-changes", dest
="maxChanges"),
607 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
608 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
610 self
.description
= """Imports from Perforce into a git repository.\n
612 //depot/my/project/ -- to import the current head
613 //depot/my/project/@all -- to import everything
614 //depot/my/project/@1,6 -- to import only from revision 1 to 6
616 (a ... is not needed in the path p4 specification, it's added implicitly)"""
618 self
.usage
+= " //depot/path[@revRange]"
620 self
.createdBranches
= Set()
621 self
.committedChanges
= Set()
623 self
.detectBranches
= False
624 self
.detectLabels
= False
625 self
.changesFile
= ""
626 self
.syncWithOrigin
= True
628 self
.importIntoRemotes
= True
630 self
.isWindows
= (platform
.system() == "Windows")
631 self
.keepRepoPath
= False
632 self
.depotPaths
= None
634 if gitConfig("git-p4.syncFromOrigin") == "false":
635 self
.syncWithOrigin
= False
637 def extractFilesFromCommit(self
, commit
):
640 while commit
.has_key("depotFile%s" % fnum
):
641 path
= commit
["depotFile%s" % fnum
]
643 found
= [p
for p
in self
.depotPaths
644 if path
.startswith (p
)]
651 file["rev"] = commit
["rev%s" % fnum
]
652 file["action"] = commit
["action%s" % fnum
]
653 file["type"] = commit
["type%s" % fnum
]
658 def stripRepoPath(self
, path
, prefixes
):
659 if self
.keepRepoPath
:
660 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
663 if path
.startswith(p
):
668 def splitFilesIntoBranches(self
, commit
):
671 while commit
.has_key("depotFile%s" % fnum
):
672 path
= commit
["depotFile%s" % fnum
]
673 found
= [p
for p
in self
.depotPaths
674 if path
.startswith (p
)]
681 file["rev"] = commit
["rev%s" % fnum
]
682 file["action"] = commit
["action%s" % fnum
]
683 file["type"] = commit
["type%s" % fnum
]
686 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
688 for branch
in self
.knownBranches
.keys():
690 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
691 if relPath
.startswith(branch
+ "/"):
692 if branch
not in branches
:
693 branches
[branch
] = []
694 branches
[branch
].append(file)
698 ## Should move this out, doesn't use SELF.
699 def readP4Files(self
, files
):
700 files
= [f
for f
in files
701 if f
['action'] != 'delete']
706 filedata
= p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f
['path'],
712 while j
< len(filedata
):
716 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
718 text
+= filedata
[j
]['data']
722 if not stat
.has_key('depotFile'):
723 sys
.stderr
.write("p4 print fails with: %s\n" % repr(stat
))
726 contents
[stat
['depotFile']] = text
729 assert not f
.has_key('data')
730 f
['data'] = contents
[f
['path']]
732 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
733 epoch
= details
["time"]
734 author
= details
["user"]
737 print "commit into %s" % branch
739 # start with reading files; if that fails, we should not
743 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
746 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
748 self
.readP4Files(files
)
753 self
.gitStream
.write("commit %s\n" % branch
)
754 # gitStream.write("mark :%s\n" % details["change"])
755 self
.committedChanges
.add(int(details
["change"]))
757 if author
not in self
.users
:
758 self
.getUserMapFromPerforceServer()
759 if author
in self
.users
:
760 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
762 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
764 self
.gitStream
.write("committer %s\n" % committer
)
766 self
.gitStream
.write("data <<EOT\n")
767 self
.gitStream
.write(details
["desc"])
768 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
770 % (','.join (branchPrefixes
), details
["change"],
773 self
.gitStream
.write("EOT\n\n")
777 print "parent %s" % parent
778 self
.gitStream
.write("from %s\n" % parent
)
781 if file["type"] == "apple":
782 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
785 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
786 if file["action"] == "delete":
787 self
.gitStream
.write("D %s\n" % relPath
)
790 if file["type"].startswith("x"):
795 if self
.isWindows
and file["type"].endswith("text"):
796 data
= data
.replace("\r\n", "\n")
798 self
.gitStream
.write("M %d inline %s\n" % (mode
, relPath
))
799 self
.gitStream
.write("data %s\n" % len(data
))
800 self
.gitStream
.write(data
)
801 self
.gitStream
.write("\n")
803 self
.gitStream
.write("\n")
805 change
= int(details
["change"])
807 if self
.labels
.has_key(change
):
808 label
= self
.labels
[change
]
809 labelDetails
= label
[0]
810 labelRevisions
= label
[1]
812 print "Change %s is labelled %s" % (change
, labelDetails
)
814 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
815 for p
in branchPrefixes
]))
817 if len(files
) == len(labelRevisions
):
821 if info
["action"] == "delete":
823 cleanedFiles
[info
["depotFile"]] = info
["rev"]
825 if cleanedFiles
== labelRevisions
:
826 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
827 self
.gitStream
.write("from %s\n" % branch
)
829 owner
= labelDetails
["Owner"]
831 if author
in self
.users
:
832 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
834 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
835 self
.gitStream
.write("tagger %s\n" % tagger
)
836 self
.gitStream
.write("data <<EOT\n")
837 self
.gitStream
.write(labelDetails
["Description"])
838 self
.gitStream
.write("EOT\n\n")
842 print ("Tag %s does not match with change %s: files do not match."
843 % (labelDetails
["label"], change
))
847 print ("Tag %s does not match with change %s: file count is different."
848 % (labelDetails
["label"], change
))
850 def getUserCacheFilename(self
):
851 return os
.environ
["HOME"] + "/.gitp4-usercache.txt"
853 def getUserMapFromPerforceServer(self
):
854 if self
.userMapFromPerforceServer
:
858 for output
in p4CmdList("users"):
859 if not output
.has_key("User"):
861 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
865 for (key
, val
) in self
.users
.items():
866 s
+= "%s\t%s\n" % (key
, val
)
868 open(self
.getUserCacheFilename(), "wb").write(s
)
869 self
.userMapFromPerforceServer
= True
871 def loadUserMapFromCache(self
):
873 self
.userMapFromPerforceServer
= False
875 cache
= open(self
.getUserCacheFilename(), "rb")
876 lines
= cache
.readlines()
879 entry
= line
.strip().split("\t")
880 self
.users
[entry
[0]] = entry
[1]
882 self
.getUserMapFromPerforceServer()
887 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
888 if len(l
) > 0 and not self
.silent
:
889 print "Finding files belonging to labels in %s" % `self
.depotPath`
892 label
= output
["label"]
896 print "Querying files for label %s" % label
897 for file in p4CmdList("files "
898 + ' '.join (["%s...@%s" % (p
, label
)
899 for p
in self
.depotPaths
])):
900 revisions
[file["depotFile"]] = file["rev"]
901 change
= int(file["change"])
902 if change
> newestChange
:
903 newestChange
= change
905 self
.labels
[newestChange
] = [output
, revisions
]
908 print "Label changes: %s" % self
.labels
.keys()
910 def guessProjectName(self
):
911 for p
in self
.depotPaths
:
912 return p
[p
.strip().rfind("/") + 1:]
914 def getBranchMapping(self
):
915 for info
in p4CmdList("branches"):
916 details
= p4Cmd("branch -o %s" % info
["branch"])
918 while details
.has_key("View%s" % viewIdx
):
919 paths
= details
["View%s" % viewIdx
].split(" ")
920 viewIdx
= viewIdx
+ 1
921 # require standard //depot/foo/... //depot/bar/... mapping
922 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
925 destination
= paths
[1]
927 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
928 source
= source
[len(self
.depotPaths
[0]):-4]
929 destination
= destination
[len(self
.depotPaths
[0]):-4]
930 if destination
not in self
.knownBranches
:
931 self
.knownBranches
[destination
] = source
932 if source
not in self
.knownBranches
:
933 self
.knownBranches
[source
] = source
935 def listExistingP4GitBranches(self
):
936 self
.p4BranchesInGit
= []
938 cmdline
= "git rev-parse --symbolic "
939 if self
.importIntoRemotes
:
940 cmdline
+= " --remotes"
942 cmdline
+= " --branches"
944 for line
in read_pipe_lines(cmdline
):
947 ## only import to p4/
948 if not line
.startswith('p4/') or line
== "p4/HEAD":
953 branch
= re
.sub ("^p4/", "", line
)
955 self
.p4BranchesInGit
.append(branch
)
956 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
958 def createOrUpdateBranchesFromOrigin(self
):
960 print ("Creating/updating branch(es) in %s based on origin branch(es)"
963 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
965 if (not line
.startswith("origin/")) or line
.endswith("HEAD"):
968 headName
= line
[len("origin/"):]
969 remoteHead
= self
.refPrefix
+ headName
970 originHead
= "origin/" + headName
972 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
973 if (not original
.has_key('depot-paths')
974 or not original
.has_key('change')):
978 if not gitBranchExists(remoteHead
):
980 print "creating %s" % remoteHead
983 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
984 if settings
.has_key('change') > 0:
985 if settings
['depot-paths'] == original
['depot-paths']:
986 originP4Change
= int(original
['change'])
987 p4Change
= int(settings
['change'])
988 if originP4Change
> p4Change
:
989 print ("%s (%s) is newer than %s (%s). "
990 "Updating p4 branch from origin."
991 % (originHead
, originP4Change
,
992 remoteHead
, p4Change
))
995 print ("Ignoring: %s was imported from %s while "
996 "%s was imported from %s"
997 % (originHead
, ','.join(original
['depot-paths']),
998 remoteHead
, ','.join(settings
['depot-paths'])))
1001 system("git update-ref %s %s" % (remoteHead
, originHead
))
1003 def updateOptionDict(self
, d
):
1005 if self
.keepRepoPath
:
1006 option_keys
['keepRepoPath'] = 1
1008 d
["options"] = ' '.join(sorted(option_keys
.keys()))
1010 def readOptions(self
, d
):
1011 self
.keepRepoPath
= (d
.has_key('options')
1012 and ('keepRepoPath' in d
['options']))
1014 def run(self
, args
):
1015 self
.depotPaths
= []
1016 self
.changeRange
= ""
1017 self
.initialParent
= ""
1018 self
.previousDepotPaths
= []
1020 # map from branch depot path to parent branch
1021 self
.knownBranches
= {}
1022 self
.initialParents
= {}
1023 self
.hasOrigin
= gitBranchExists("origin")
1025 if self
.importIntoRemotes
:
1026 self
.refPrefix
= "refs/remotes/p4/"
1028 self
.refPrefix
= "refs/heads/p4/"
1030 if self
.syncWithOrigin
and self
.hasOrigin
:
1032 print "Syncing with origin first by calling git fetch origin"
1033 system("git fetch origin")
1035 if len(self
.branch
) == 0:
1036 self
.branch
= self
.refPrefix
+ "master"
1037 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1038 system("git update-ref %s refs/heads/p4" % self
.branch
)
1039 system("git branch -D p4");
1040 # create it /after/ importing, when master exists
1041 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
1042 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1044 # TODO: should always look at previous commits,
1045 # merge with previous imports, if possible.
1048 self
.createOrUpdateBranchesFromOrigin()
1049 self
.listExistingP4GitBranches()
1051 if len(self
.p4BranchesInGit
) > 1:
1053 print "Importing from/into multiple branches"
1054 self
.detectBranches
= True
1057 print "branches: %s" % self
.p4BranchesInGit
1060 for branch
in self
.p4BranchesInGit
:
1061 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1063 settings
= extractSettingsGitLog(logMsg
)
1065 self
.readOptions(settings
)
1066 if (settings
.has_key('depot-paths')
1067 and settings
.has_key ('change')):
1068 change
= int(settings
['change']) + 1
1069 p4Change
= max(p4Change
, change
)
1071 depotPaths
= sorted(settings
['depot-paths'])
1072 if self
.previousDepotPaths
== []:
1073 self
.previousDepotPaths
= depotPaths
1076 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1077 for i
in range(0, min(len(cur
), len(prev
))):
1078 if cur
[i
] <> prev
[i
]:
1082 paths
.append (cur
[:i
+ 1])
1084 self
.previousDepotPaths
= paths
1087 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1088 self
.changeRange
= "@%s,#head" % p4Change
1089 if not self
.detectBranches
:
1090 self
.initialParent
= parseRevision(self
.branch
)
1091 if not self
.silent
and not self
.detectBranches
:
1092 print "Performing incremental import into %s git branch" % self
.branch
1094 if not self
.branch
.startswith("refs/"):
1095 self
.branch
= "refs/heads/" + self
.branch
1097 if len(args
) == 0 and self
.depotPaths
:
1099 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1101 if self
.depotPaths
and self
.depotPaths
!= args
:
1102 print ("previous import used depot path %s and now %s was specified. "
1103 "This doesn't work!" % (' '.join (self
.depotPaths
),
1107 self
.depotPaths
= sorted(args
)
1113 for p
in self
.depotPaths
:
1114 if p
.find("@") != -1:
1115 atIdx
= p
.index("@")
1116 self
.changeRange
= p
[atIdx
:]
1117 if self
.changeRange
== "@all":
1118 self
.changeRange
= ""
1119 elif ',' not in self
.changeRange
:
1120 self
.revision
= self
.changeRange
1121 self
.changeRange
= ""
1123 elif p
.find("#") != -1:
1124 hashIdx
= p
.index("#")
1125 self
.revision
= p
[hashIdx
:]
1127 elif self
.previousDepotPaths
== []:
1128 self
.revision
= "#head"
1130 p
= re
.sub ("\.\.\.$", "", p
)
1131 if not p
.endswith("/"):
1136 self
.depotPaths
= newPaths
1139 self
.loadUserMapFromCache()
1141 if self
.detectLabels
:
1144 if self
.detectBranches
:
1145 ## FIXME - what's a P4 projectName ?
1146 self
.projectName
= self
.guessProjectName()
1148 if not self
.hasOrigin
:
1149 self
.getBranchMapping();
1151 print "p4-git branches: %s" % self
.p4BranchesInGit
1152 print "initial parents: %s" % self
.initialParents
1153 for b
in self
.p4BranchesInGit
:
1157 b
= b
[len(self
.projectName
):]
1158 self
.createdBranches
.add(b
)
1160 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1162 importProcess
= subprocess
.Popen(["git", "fast-import"],
1163 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1164 stderr
=subprocess
.PIPE
);
1165 self
.gitOutput
= importProcess
.stdout
1166 self
.gitStream
= importProcess
.stdin
1167 self
.gitError
= importProcess
.stderr
1170 print "Doing initial import of %s from revision %s" % (' '.join(self
.depotPaths
), self
.revision
)
1172 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1173 details
["desc"] = ("Initial import of %s from the state at revision %s"
1174 % (' '.join(self
.depotPaths
), self
.revision
))
1175 details
["change"] = self
.revision
1179 for info
in p4CmdList("files "
1180 + ' '.join(["%s...%s"
1181 % (p
, self
.revision
)
1182 for p
in self
.depotPaths
])):
1184 if info
['code'] == 'error':
1185 sys
.stderr
.write("p4 returned an error: %s\n"
1190 change
= int(info
["change"])
1191 if change
> newestRevision
:
1192 newestRevision
= change
1194 if info
["action"] == "delete":
1195 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1196 #fileCnt = fileCnt + 1
1199 for prop
in ["depotFile", "rev", "action", "type" ]:
1200 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1202 fileCnt
= fileCnt
+ 1
1204 details
["change"] = newestRevision
1205 self
.updateOptionDict(details
)
1207 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1209 print "IO error with git fast-import. Is your git version recent enough?"
1210 print self
.gitError
.read()
1215 if len(self
.changesFile
) > 0:
1216 output
= open(self
.changesFile
).readlines()
1219 changeSet
.add(int(line
))
1221 for change
in changeSet
:
1222 changes
.append(change
)
1227 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1229 assert self
.depotPaths
1230 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1231 for p
in self
.depotPaths
]))
1234 changeNum
= line
.split(" ")[1]
1235 changes
.append(changeNum
)
1239 if len(self
.maxChanges
) > 0:
1240 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1242 if len(changes
) == 0:
1244 print "No changes to import!"
1247 self
.updatedBranches
= set()
1250 for change
in changes
:
1251 description
= p4Cmd("describe %s" % change
)
1252 self
.updateOptionDict(description
)
1255 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1260 if self
.detectBranches
:
1261 branches
= self
.splitFilesIntoBranches(description
)
1262 for branch
in branches
.keys():
1264 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1268 filesForCommit
= branches
[branch
]
1271 print "branch is %s" % branch
1273 self
.updatedBranches
.add(branch
)
1275 if branch
not in self
.createdBranches
:
1276 self
.createdBranches
.add(branch
)
1277 parent
= self
.knownBranches
[branch
]
1278 if parent
== branch
:
1281 print "parent determined through known branches: %s" % parent
1283 # main branch? use master
1284 if branch
== "main":
1289 branch
= self
.projectName
+ branch
1291 if parent
== "main":
1293 elif len(parent
) > 0:
1295 parent
= self
.projectName
+ parent
1297 branch
= self
.refPrefix
+ branch
1299 parent
= self
.refPrefix
+ parent
1302 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1304 if len(parent
) == 0 and branch
in self
.initialParents
:
1305 parent
= self
.initialParents
[branch
]
1306 del self
.initialParents
[branch
]
1308 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1310 files
= self
.extractFilesFromCommit(description
)
1311 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1313 self
.initialParent
= ""
1315 print self
.gitError
.read()
1320 if len(self
.updatedBranches
) > 0:
1321 sys
.stdout
.write("Updated branches: ")
1322 for b
in self
.updatedBranches
:
1323 sys
.stdout
.write("%s " % b
)
1324 sys
.stdout
.write("\n")
1327 self
.gitStream
.close()
1328 if importProcess
.wait() != 0:
1329 die("fast-import failed: %s" % self
.gitError
.read())
1330 self
.gitOutput
.close()
1331 self
.gitError
.close()
1335 class P4Rebase(Command
):
1337 Command
.__init
__(self
)
1339 self
.description
= ("Fetches the latest revision from perforce and "
1340 + "rebases the current work (branch) against it")
1341 self
.verbose
= False
1343 def run(self
, args
):
1346 print "Rebasing the current branch"
1347 oldHead
= read_pipe("git rev-parse HEAD").strip()
1348 system("git rebase p4")
1349 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1352 class P4Clone(P4Sync
):
1354 P4Sync
.__init
__(self
)
1355 self
.description
= "Creates a new git repository and imports from Perforce into it"
1356 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1357 self
.options
.append(
1358 optparse
.make_option("--destination", dest
="cloneDestination",
1359 action
='store', default
=None,
1360 help="where to leave result of the clone"))
1361 self
.cloneDestination
= None
1362 self
.needsGit
= False
1364 def defaultDestination(self
, args
):
1365 ## TODO: use common prefix of args?
1367 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1368 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1369 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1370 depotDir
= re
.sub(r
"/$", "", depotDir
)
1371 return os
.path
.split(depotDir
)[1]
1373 def run(self
, args
):
1377 if self
.keepRepoPath
and not self
.cloneDestination
:
1378 sys
.stderr
.write("Must specify destination for --keep-path\n")
1383 if not self
.cloneDestination
and len(depotPaths
) > 1:
1384 self
.cloneDestination
= depotPaths
[-1]
1385 depotPaths
= depotPaths
[:-1]
1387 for p
in depotPaths
:
1388 if not p
.startswith("//"):
1391 if not self
.cloneDestination
:
1392 self
.cloneDestination
= self
.defaultDestination(args
)
1394 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1395 os
.makedirs(self
.cloneDestination
)
1396 os
.chdir(self
.cloneDestination
)
1398 self
.gitdir
= os
.getcwd() + "/.git"
1399 if not P4Sync
.run(self
, depotPaths
):
1401 if self
.branch
!= "master":
1402 if gitBranchExists("refs/remotes/p4/master"):
1403 system("git branch master refs/remotes/p4/master")
1404 system("git checkout -f")
1406 print "Could not detect main branch. No checkout/master branch created."
1410 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1412 optparse
.IndentedHelpFormatter
.__init
__(self
)
1414 def format_description(self
, description
):
1416 return description
+ "\n"
1420 def printUsage(commands
):
1421 print "usage: %s <command> [options]" % sys
.argv
[0]
1423 print "valid commands: %s" % ", ".join(commands
)
1425 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1430 "submit" : P4Submit
,
1432 "rebase" : P4Rebase
,
1434 "rollback" : P4RollBack
1439 if len(sys
.argv
[1:]) == 0:
1440 printUsage(commands
.keys())
1444 cmdName
= sys
.argv
[1]
1446 klass
= commands
[cmdName
]
1449 print "unknown command %s" % cmdName
1451 printUsage(commands
.keys())
1454 options
= cmd
.options
1455 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1459 if len(options
) > 0:
1460 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1462 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1464 description
= cmd
.description
,
1465 formatter
= HelpFormatter())
1467 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1469 verbose
= cmd
.verbose
1471 if cmd
.gitdir
== None:
1472 cmd
.gitdir
= os
.path
.abspath(".git")
1473 if not isValidGitDir(cmd
.gitdir
):
1474 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1475 if os
.path
.exists(cmd
.gitdir
):
1476 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1480 if not isValidGitDir(cmd
.gitdir
):
1481 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1482 cmd
.gitdir
+= "/.git"
1484 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1486 os
.environ
["GIT_DIR"] = cmd
.gitdir
1488 if not cmd
.run(args
):
1492 if __name__
== '__main__':