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()
171 def findUpstreamBranchPoint():
175 while parent
< 65535:
176 commit
= "HEAD~%s" % parent
177 log
= extractLogMessageFromGitCommit(commit
)
178 settings
= extractSettingsGitLog(log
)
179 if not settings
.has_key("depot-paths"):
183 names
= read_pipe_lines("git name-rev \"--refs=refs/remotes/p4/*\" \"%s\"" % commit
)
187 # strip away the beginning of 'HEAD~42 refs/remotes/p4/foo'
188 branchPoint
= names
[0].strip()[len(commit
) + 1:]
191 return [branchPoint
, settings
]
195 self
.usage
= "usage: %prog [options]"
198 class P4Debug(Command
):
200 Command
.__init
__(self
)
202 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
205 self
.description
= "A tool to debug the output of p4 -G."
206 self
.needsGit
= False
211 for output
in p4CmdList(" ".join(args
)):
212 print 'Element: %d' % j
217 class P4RollBack(Command
):
219 Command
.__init
__(self
)
221 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
222 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
224 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
226 self
.rollbackLocalBranches
= False
231 maxChange
= int(args
[0])
233 if "p4ExitCode" in p4Cmd("changes -m 1"):
234 die("Problems executing p4");
236 if self
.rollbackLocalBranches
:
237 refPrefix
= "refs/heads/"
238 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
240 refPrefix
= "refs/remotes/"
241 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
244 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
246 ref
= refPrefix
+ line
247 log
= extractLogMessageFromGitCommit(ref
)
248 settings
= extractSettingsGitLog(log
)
250 depotPaths
= settings
['depot-paths']
251 change
= settings
['change']
255 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
256 for p
in depotPaths
]))) == 0:
257 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
258 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
261 while change
and int(change
) > maxChange
:
264 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
265 system("git update-ref %s \"%s^\"" % (ref
, ref
))
266 log
= extractLogMessageFromGitCommit(ref
)
267 settings
= extractSettingsGitLog(log
)
270 depotPaths
= settings
['depot-paths']
271 change
= settings
['change']
274 print "%s rewound to %s" % (ref
, change
)
278 class P4Submit(Command
):
280 Command
.__init
__(self
)
282 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
283 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
284 optparse
.make_option("--origin", dest
="origin"),
285 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
286 optparse
.make_option("--log-substitutions", dest
="substFile"),
287 optparse
.make_option("--dry-run", action
="store_true"),
288 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
289 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
291 self
.description
= "Submit changes from git to the perforce depot."
292 self
.usage
+= " [name of git branch to submit into perforce depot]"
293 self
.firstTime
= True
295 self
.interactive
= True
298 self
.firstTime
= True
300 self
.directSubmit
= False
301 self
.trustMeLikeAFool
= False
303 self
.isWindows
= (platform
.system() == "Windows")
305 self
.logSubstitutions
= {}
306 self
.logSubstitutions
["<enter description here>"] = "%log%"
307 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
310 if len(p4CmdList("opened ...")) > 0:
311 die("You have files opened with perforce! Close them before starting the sync.")
314 if len(self
.config
) > 0 and not self
.reset
:
315 die("Cannot start sync. Previous sync config found at %s\n"
316 "If you want to start submitting again from scratch "
317 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
320 if self
.directSubmit
:
323 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
324 commits
.append(line
.strip())
327 self
.config
["commits"] = commits
329 def prepareLogMessage(self
, template
, message
):
332 for line
in template
.split("\n"):
333 if line
.startswith("#"):
334 result
+= line
+ "\n"
338 for key
in self
.logSubstitutions
.keys():
339 if line
.find(key
) != -1:
340 value
= self
.logSubstitutions
[key
]
341 value
= value
.replace("%log%", message
)
342 if value
!= "@remove@":
343 result
+= line
.replace(key
, value
) + "\n"
348 result
+= line
+ "\n"
352 def applyCommit(self
, id):
353 if self
.directSubmit
:
354 print "Applying local change in working directory/index"
355 diff
= self
.diffStatus
357 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
358 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
360 filesToDelete
= set()
364 path
= line
[1:].strip()
366 system("p4 edit \"%s\"" % path
)
367 editedFiles
.add(path
)
368 elif modifier
== "A":
370 if path
in filesToDelete
:
371 filesToDelete
.remove(path
)
372 elif modifier
== "D":
373 filesToDelete
.add(path
)
374 if path
in filesToAdd
:
375 filesToAdd
.remove(path
)
377 die("unknown modifier %s for %s" % (modifier
, path
))
379 if self
.directSubmit
:
380 diffcmd
= "cat \"%s\"" % self
.diffFile
382 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
383 patchcmd
= diffcmd
+ " | git apply "
384 tryPatchCmd
= patchcmd
+ "--check -"
385 applyPatchCmd
= patchcmd
+ "--check --apply -"
387 if os
.system(tryPatchCmd
) != 0:
388 print "Unfortunately applying the change failed!"
389 print "What do you want to do?"
391 while response
!= "s" and response
!= "a" and response
!= "w":
392 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
393 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
395 print "Skipping! Good luck with the next patches..."
397 elif response
== "a":
398 os
.system(applyPatchCmd
)
399 if len(filesToAdd
) > 0:
400 print "You may also want to call p4 add on the following files:"
401 print " ".join(filesToAdd
)
402 if len(filesToDelete
):
403 print "The following files should be scheduled for deletion with p4 delete:"
404 print " ".join(filesToDelete
)
405 die("Please resolve and submit the conflict manually and "
406 + "continue afterwards with git-p4 submit --continue")
407 elif response
== "w":
408 system(diffcmd
+ " > patch.txt")
409 print "Patch saved to patch.txt in %s !" % self
.clientPath
410 die("Please resolve and submit the conflict manually and "
411 "continue afterwards with git-p4 submit --continue")
413 system(applyPatchCmd
)
416 system("p4 add \"%s\"" % f
)
417 for f
in filesToDelete
:
418 system("p4 revert \"%s\"" % f
)
419 system("p4 delete \"%s\"" % f
)
422 if not self
.directSubmit
:
423 logMessage
= extractLogMessageFromGitCommit(id)
424 logMessage
= logMessage
.replace("\n", "\n\t")
426 logMessage
= logMessage
.replace("\n", "\r\n")
427 logMessage
= logMessage
.strip()
429 template
= read_pipe("p4 change -o")
432 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
433 diff
= read_pipe("p4 diff -du ...")
435 for newFile
in filesToAdd
:
436 diff
+= "==== new file ====\n"
437 diff
+= "--- /dev/null\n"
438 diff
+= "+++ %s\n" % newFile
439 f
= open(newFile
, "r")
440 for line
in f
.readlines():
444 separatorLine
= "######## everything below this line is just the diff #######"
445 if platform
.system() == "Windows":
446 separatorLine
+= "\r"
447 separatorLine
+= "\n"
450 if self
.trustMeLikeAFool
:
453 firstIteration
= True
454 while response
== "e":
455 if not firstIteration
:
456 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
457 firstIteration
= False
459 [handle
, fileName
] = tempfile
.mkstemp()
460 tmpFile
= os
.fdopen(handle
, "w+")
461 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
464 if platform
.system() == "Windows":
465 defaultEditor
= "notepad"
466 editor
= os
.environ
.get("EDITOR", defaultEditor
);
467 system(editor
+ " " + fileName
)
468 tmpFile
= open(fileName
, "rb")
469 message
= tmpFile
.read()
472 submitTemplate
= message
[:message
.index(separatorLine
)]
474 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
476 if response
== "y" or response
== "yes":
479 raw_input("Press return to continue...")
481 if self
.directSubmit
:
482 print "Submitting to git first"
483 os
.chdir(self
.oldWorkingDirectory
)
484 write_pipe("git commit -a -F -", submitTemplate
)
485 os
.chdir(self
.clientPath
)
487 write_pipe("p4 submit -i", submitTemplate
)
488 elif response
== "s":
489 for f
in editedFiles
:
490 system("p4 revert \"%s\"" % f
);
492 system("p4 revert \"%s\"" % f
);
494 for f
in filesToDelete
:
495 system("p4 delete \"%s\"" % f
);
498 print "Not submitting!"
499 self
.interactive
= False
501 fileName
= "submit.txt"
502 file = open(fileName
, "w+")
503 file.write(self
.prepareLogMessage(template
, logMessage
))
505 print ("Perforce submit template written as %s. "
506 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
507 % (fileName
, fileName
))
511 self
.master
= currentGitBranch()
512 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
513 die("Detecting current git branch failed!")
515 self
.master
= args
[0]
519 [upstream
, settings
] = findUpstreamBranchPoint()
520 depotPath
= settings
['depot-paths'][0]
521 if len(self
.origin
) == 0:
522 self
.origin
= upstream
525 print "Origin branch is " + self
.origin
527 if len(depotPath
) == 0:
528 print "Internal error: cannot locate perforce depot path from existing branches"
531 self
.clientPath
= p4Where(depotPath
)
533 if len(self
.clientPath
) == 0:
534 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
537 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
538 self
.oldWorkingDirectory
= os
.getcwd()
540 if self
.directSubmit
:
541 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
542 if len(self
.diffStatus
) == 0:
543 print "No changes in working directory to submit."
545 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
546 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
547 f
= open(self
.diffFile
, "wb")
551 os
.chdir(self
.clientPath
)
552 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
553 if response
== "y" or response
== "yes":
554 system("p4 sync ...")
557 self
.firstTime
= True
559 if len(self
.substFile
) > 0:
560 for line
in open(self
.substFile
, "r").readlines():
561 tokens
= line
.strip().split("=")
562 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
565 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
566 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
571 commits
= self
.config
.get("commits", [])
573 while len(commits
) > 0:
574 self
.firstTime
= False
576 commits
= commits
[1:]
577 self
.config
["commits"] = commits
578 self
.applyCommit(commit
)
579 if not self
.interactive
:
584 if self
.directSubmit
:
585 os
.remove(self
.diffFile
)
587 if len(commits
) == 0:
589 print "No changes found to apply between %s and current HEAD" % self
.origin
591 print "All changes applied!"
592 os
.chdir(self
.oldWorkingDirectory
)
593 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
594 if response
== "y" or response
== "yes":
597 os
.remove(self
.configFile
)
601 class P4Sync(Command
):
603 Command
.__init
__(self
)
605 optparse
.make_option("--branch", dest
="branch"),
606 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
607 optparse
.make_option("--changesfile", dest
="changesFile"),
608 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
609 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
610 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
611 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
612 help="Import into refs/heads/ , not refs/remotes"),
613 optparse
.make_option("--max-changes", dest
="maxChanges"),
614 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
615 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
617 self
.description
= """Imports from Perforce into a git repository.\n
619 //depot/my/project/ -- to import the current head
620 //depot/my/project/@all -- to import everything
621 //depot/my/project/@1,6 -- to import only from revision 1 to 6
623 (a ... is not needed in the path p4 specification, it's added implicitly)"""
625 self
.usage
+= " //depot/path[@revRange]"
627 self
.createdBranches
= Set()
628 self
.committedChanges
= Set()
630 self
.detectBranches
= False
631 self
.detectLabels
= False
632 self
.changesFile
= ""
633 self
.syncWithOrigin
= True
635 self
.importIntoRemotes
= True
637 self
.isWindows
= (platform
.system() == "Windows")
638 self
.keepRepoPath
= False
639 self
.depotPaths
= None
641 if gitConfig("git-p4.syncFromOrigin") == "false":
642 self
.syncWithOrigin
= False
644 def extractFilesFromCommit(self
, commit
):
647 while commit
.has_key("depotFile%s" % fnum
):
648 path
= commit
["depotFile%s" % fnum
]
650 found
= [p
for p
in self
.depotPaths
651 if path
.startswith (p
)]
658 file["rev"] = commit
["rev%s" % fnum
]
659 file["action"] = commit
["action%s" % fnum
]
660 file["type"] = commit
["type%s" % fnum
]
665 def stripRepoPath(self
, path
, prefixes
):
666 if self
.keepRepoPath
:
667 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
670 if path
.startswith(p
):
675 def splitFilesIntoBranches(self
, commit
):
678 while commit
.has_key("depotFile%s" % fnum
):
679 path
= commit
["depotFile%s" % fnum
]
680 found
= [p
for p
in self
.depotPaths
681 if path
.startswith (p
)]
688 file["rev"] = commit
["rev%s" % fnum
]
689 file["action"] = commit
["action%s" % fnum
]
690 file["type"] = commit
["type%s" % fnum
]
693 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
695 for branch
in self
.knownBranches
.keys():
697 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
698 if relPath
.startswith(branch
+ "/"):
699 if branch
not in branches
:
700 branches
[branch
] = []
701 branches
[branch
].append(file)
705 ## Should move this out, doesn't use SELF.
706 def readP4Files(self
, files
):
707 files
= [f
for f
in files
708 if f
['action'] != 'delete']
713 filedata
= p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f
['path'],
719 while j
< len(filedata
):
723 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
725 text
+= filedata
[j
]['data']
729 if not stat
.has_key('depotFile'):
730 sys
.stderr
.write("p4 print fails with: %s\n" % repr(stat
))
733 contents
[stat
['depotFile']] = text
736 assert not f
.has_key('data')
737 f
['data'] = contents
[f
['path']]
739 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
740 epoch
= details
["time"]
741 author
= details
["user"]
744 print "commit into %s" % branch
746 # start with reading files; if that fails, we should not
750 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
753 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
755 self
.readP4Files(files
)
760 self
.gitStream
.write("commit %s\n" % branch
)
761 # gitStream.write("mark :%s\n" % details["change"])
762 self
.committedChanges
.add(int(details
["change"]))
764 if author
not in self
.users
:
765 self
.getUserMapFromPerforceServer()
766 if author
in self
.users
:
767 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
769 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
771 self
.gitStream
.write("committer %s\n" % committer
)
773 self
.gitStream
.write("data <<EOT\n")
774 self
.gitStream
.write(details
["desc"])
775 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s"
776 % (','.join (branchPrefixes
), details
["change"]))
777 if len(details
['options']) > 0:
778 self
.gitStream
.write(": options = %s" % details
['options'])
779 self
.gitStream
.write("]\nEOT\n\n")
783 print "parent %s" % parent
784 self
.gitStream
.write("from %s\n" % parent
)
787 if file["type"] == "apple":
788 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
791 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
792 if file["action"] == "delete":
793 self
.gitStream
.write("D %s\n" % relPath
)
796 if file["type"].startswith("x"):
801 if self
.isWindows
and file["type"].endswith("text"):
802 data
= data
.replace("\r\n", "\n")
804 self
.gitStream
.write("M %d inline %s\n" % (mode
, relPath
))
805 self
.gitStream
.write("data %s\n" % len(data
))
806 self
.gitStream
.write(data
)
807 self
.gitStream
.write("\n")
809 self
.gitStream
.write("\n")
811 change
= int(details
["change"])
813 if self
.labels
.has_key(change
):
814 label
= self
.labels
[change
]
815 labelDetails
= label
[0]
816 labelRevisions
= label
[1]
818 print "Change %s is labelled %s" % (change
, labelDetails
)
820 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
821 for p
in branchPrefixes
]))
823 if len(files
) == len(labelRevisions
):
827 if info
["action"] == "delete":
829 cleanedFiles
[info
["depotFile"]] = info
["rev"]
831 if cleanedFiles
== labelRevisions
:
832 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
833 self
.gitStream
.write("from %s\n" % branch
)
835 owner
= labelDetails
["Owner"]
837 if author
in self
.users
:
838 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
840 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
841 self
.gitStream
.write("tagger %s\n" % tagger
)
842 self
.gitStream
.write("data <<EOT\n")
843 self
.gitStream
.write(labelDetails
["Description"])
844 self
.gitStream
.write("EOT\n\n")
848 print ("Tag %s does not match with change %s: files do not match."
849 % (labelDetails
["label"], change
))
853 print ("Tag %s does not match with change %s: file count is different."
854 % (labelDetails
["label"], change
))
856 def getUserCacheFilename(self
):
857 return os
.environ
["HOME"] + "/.gitp4-usercache.txt"
859 def getUserMapFromPerforceServer(self
):
860 if self
.userMapFromPerforceServer
:
864 for output
in p4CmdList("users"):
865 if not output
.has_key("User"):
867 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
871 for (key
, val
) in self
.users
.items():
872 s
+= "%s\t%s\n" % (key
, val
)
874 open(self
.getUserCacheFilename(), "wb").write(s
)
875 self
.userMapFromPerforceServer
= True
877 def loadUserMapFromCache(self
):
879 self
.userMapFromPerforceServer
= False
881 cache
= open(self
.getUserCacheFilename(), "rb")
882 lines
= cache
.readlines()
885 entry
= line
.strip().split("\t")
886 self
.users
[entry
[0]] = entry
[1]
888 self
.getUserMapFromPerforceServer()
893 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
894 if len(l
) > 0 and not self
.silent
:
895 print "Finding files belonging to labels in %s" % `self
.depotPath`
898 label
= output
["label"]
902 print "Querying files for label %s" % label
903 for file in p4CmdList("files "
904 + ' '.join (["%s...@%s" % (p
, label
)
905 for p
in self
.depotPaths
])):
906 revisions
[file["depotFile"]] = file["rev"]
907 change
= int(file["change"])
908 if change
> newestChange
:
909 newestChange
= change
911 self
.labels
[newestChange
] = [output
, revisions
]
914 print "Label changes: %s" % self
.labels
.keys()
916 def guessProjectName(self
):
917 for p
in self
.depotPaths
:
920 p
= p
[p
.strip().rfind("/") + 1:]
921 if not p
.endswith("/"):
925 def getBranchMapping(self
):
926 for info
in p4CmdList("branches"):
927 details
= p4Cmd("branch -o %s" % info
["branch"])
929 while details
.has_key("View%s" % viewIdx
):
930 paths
= details
["View%s" % viewIdx
].split(" ")
931 viewIdx
= viewIdx
+ 1
932 # require standard //depot/foo/... //depot/bar/... mapping
933 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
936 destination
= paths
[1]
938 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
939 source
= source
[len(self
.depotPaths
[0]):-4]
940 destination
= destination
[len(self
.depotPaths
[0]):-4]
941 if destination
not in self
.knownBranches
:
942 self
.knownBranches
[destination
] = source
943 if source
not in self
.knownBranches
:
944 self
.knownBranches
[source
] = source
946 def listExistingP4GitBranches(self
):
947 self
.p4BranchesInGit
= []
949 cmdline
= "git rev-parse --symbolic "
950 if self
.importIntoRemotes
:
951 cmdline
+= " --remotes"
953 cmdline
+= " --branches"
955 for line
in read_pipe_lines(cmdline
):
958 ## only import to p4/
959 if not line
.startswith('p4/') or line
== "p4/HEAD":
964 branch
= re
.sub ("^p4/", "", line
)
966 self
.p4BranchesInGit
.append(branch
)
967 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
969 def createOrUpdateBranchesFromOrigin(self
):
971 print ("Creating/updating branch(es) in %s based on origin branch(es)"
974 originPrefix
= "origin/p4/"
976 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
978 if (not line
.startswith(originPrefix
)) or line
.endswith("HEAD"):
981 headName
= line
[len(originPrefix
):]
982 remoteHead
= self
.refPrefix
+ headName
985 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
986 if (not original
.has_key('depot-paths')
987 or not original
.has_key('change')):
991 if not gitBranchExists(remoteHead
):
993 print "creating %s" % remoteHead
996 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
997 if settings
.has_key('change') > 0:
998 if settings
['depot-paths'] == original
['depot-paths']:
999 originP4Change
= int(original
['change'])
1000 p4Change
= int(settings
['change'])
1001 if originP4Change
> p4Change
:
1002 print ("%s (%s) is newer than %s (%s). "
1003 "Updating p4 branch from origin."
1004 % (originHead
, originP4Change
,
1005 remoteHead
, p4Change
))
1008 print ("Ignoring: %s was imported from %s while "
1009 "%s was imported from %s"
1010 % (originHead
, ','.join(original
['depot-paths']),
1011 remoteHead
, ','.join(settings
['depot-paths'])))
1014 system("git update-ref %s %s" % (remoteHead
, originHead
))
1016 def updateOptionDict(self
, d
):
1018 if self
.keepRepoPath
:
1019 option_keys
['keepRepoPath'] = 1
1021 d
["options"] = ' '.join(sorted(option_keys
.keys()))
1023 def readOptions(self
, d
):
1024 self
.keepRepoPath
= (d
.has_key('options')
1025 and ('keepRepoPath' in d
['options']))
1027 def run(self
, args
):
1028 self
.depotPaths
= []
1029 self
.changeRange
= ""
1030 self
.initialParent
= ""
1031 self
.previousDepotPaths
= []
1033 # map from branch depot path to parent branch
1034 self
.knownBranches
= {}
1035 self
.initialParents
= {}
1036 self
.hasOrigin
= gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
1037 if not self
.syncWithOrigin
:
1038 self
.hasOrigin
= False
1040 if self
.importIntoRemotes
:
1041 self
.refPrefix
= "refs/remotes/p4/"
1043 self
.refPrefix
= "refs/heads/p4/"
1045 if self
.syncWithOrigin
and self
.hasOrigin
:
1047 print "Syncing with origin first by calling git fetch origin"
1048 system("git fetch origin")
1050 if len(self
.branch
) == 0:
1051 self
.branch
= self
.refPrefix
+ "master"
1052 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1053 system("git update-ref %s refs/heads/p4" % self
.branch
)
1054 system("git branch -D p4");
1055 # create it /after/ importing, when master exists
1056 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
1057 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1059 # TODO: should always look at previous commits,
1060 # merge with previous imports, if possible.
1063 self
.createOrUpdateBranchesFromOrigin()
1064 self
.listExistingP4GitBranches()
1066 if len(self
.p4BranchesInGit
) > 1:
1068 print "Importing from/into multiple branches"
1069 self
.detectBranches
= True
1072 print "branches: %s" % self
.p4BranchesInGit
1075 for branch
in self
.p4BranchesInGit
:
1076 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1078 settings
= extractSettingsGitLog(logMsg
)
1080 self
.readOptions(settings
)
1081 if (settings
.has_key('depot-paths')
1082 and settings
.has_key ('change')):
1083 change
= int(settings
['change']) + 1
1084 p4Change
= max(p4Change
, change
)
1086 depotPaths
= sorted(settings
['depot-paths'])
1087 if self
.previousDepotPaths
== []:
1088 self
.previousDepotPaths
= depotPaths
1091 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1092 for i
in range(0, min(len(cur
), len(prev
))):
1093 if cur
[i
] <> prev
[i
]:
1097 paths
.append (cur
[:i
+ 1])
1099 self
.previousDepotPaths
= paths
1102 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1103 self
.changeRange
= "@%s,#head" % p4Change
1104 if not self
.detectBranches
:
1105 self
.initialParent
= parseRevision(self
.branch
)
1106 if not self
.silent
and not self
.detectBranches
:
1107 print "Performing incremental import into %s git branch" % self
.branch
1109 if not self
.branch
.startswith("refs/"):
1110 self
.branch
= "refs/heads/" + self
.branch
1112 if len(args
) == 0 and self
.depotPaths
:
1114 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1116 if self
.depotPaths
and self
.depotPaths
!= args
:
1117 print ("previous import used depot path %s and now %s was specified. "
1118 "This doesn't work!" % (' '.join (self
.depotPaths
),
1122 self
.depotPaths
= sorted(args
)
1128 for p
in self
.depotPaths
:
1129 if p
.find("@") != -1:
1130 atIdx
= p
.index("@")
1131 self
.changeRange
= p
[atIdx
:]
1132 if self
.changeRange
== "@all":
1133 self
.changeRange
= ""
1134 elif ',' not in self
.changeRange
:
1135 self
.revision
= self
.changeRange
1136 self
.changeRange
= ""
1138 elif p
.find("#") != -1:
1139 hashIdx
= p
.index("#")
1140 self
.revision
= p
[hashIdx
:]
1142 elif self
.previousDepotPaths
== []:
1143 self
.revision
= "#head"
1145 p
= re
.sub ("\.\.\.$", "", p
)
1146 if not p
.endswith("/"):
1151 self
.depotPaths
= newPaths
1154 self
.loadUserMapFromCache()
1156 if self
.detectLabels
:
1159 if self
.detectBranches
:
1160 ## FIXME - what's a P4 projectName ?
1161 self
.projectName
= self
.guessProjectName()
1163 if not self
.hasOrigin
:
1164 self
.getBranchMapping();
1166 print "p4-git branches: %s" % self
.p4BranchesInGit
1167 print "initial parents: %s" % self
.initialParents
1168 for b
in self
.p4BranchesInGit
:
1172 b
= b
[len(self
.projectName
):]
1173 self
.createdBranches
.add(b
)
1175 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1177 importProcess
= subprocess
.Popen(["git", "fast-import"],
1178 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1179 stderr
=subprocess
.PIPE
);
1180 self
.gitOutput
= importProcess
.stdout
1181 self
.gitStream
= importProcess
.stdin
1182 self
.gitError
= importProcess
.stderr
1185 print "Doing initial import of %s from revision %s into %s" % (' '.join(self
.depotPaths
), self
.revision
, self
.branch
)
1187 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1188 details
["desc"] = ("Initial import of %s from the state at revision %s"
1189 % (' '.join(self
.depotPaths
), self
.revision
))
1190 details
["change"] = self
.revision
1194 for info
in p4CmdList("files "
1195 + ' '.join(["%s...%s"
1196 % (p
, self
.revision
)
1197 for p
in self
.depotPaths
])):
1199 if info
['code'] == 'error':
1200 sys
.stderr
.write("p4 returned an error: %s\n"
1205 change
= int(info
["change"])
1206 if change
> newestRevision
:
1207 newestRevision
= change
1209 if info
["action"] == "delete":
1210 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1211 #fileCnt = fileCnt + 1
1214 for prop
in ["depotFile", "rev", "action", "type" ]:
1215 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1217 fileCnt
= fileCnt
+ 1
1219 details
["change"] = newestRevision
1220 self
.updateOptionDict(details
)
1222 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1224 print "IO error with git fast-import. Is your git version recent enough?"
1225 print self
.gitError
.read()
1230 if len(self
.changesFile
) > 0:
1231 output
= open(self
.changesFile
).readlines()
1234 changeSet
.add(int(line
))
1236 for change
in changeSet
:
1237 changes
.append(change
)
1242 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1244 assert self
.depotPaths
1245 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1246 for p
in self
.depotPaths
]))
1249 changeNum
= line
.split(" ")[1]
1250 changes
.append(changeNum
)
1254 if len(self
.maxChanges
) > 0:
1255 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1257 if len(changes
) == 0:
1259 print "No changes to import!"
1262 if not self
.silent
and not self
.detectBranches
:
1263 print "Import destination: %s" % self
.branch
1265 self
.updatedBranches
= set()
1268 for change
in changes
:
1269 description
= p4Cmd("describe %s" % change
)
1270 self
.updateOptionDict(description
)
1273 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1278 if self
.detectBranches
:
1279 branches
= self
.splitFilesIntoBranches(description
)
1280 for branch
in branches
.keys():
1282 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1286 filesForCommit
= branches
[branch
]
1289 print "branch is %s" % branch
1291 self
.updatedBranches
.add(branch
)
1293 if branch
not in self
.createdBranches
:
1294 self
.createdBranches
.add(branch
)
1295 parent
= self
.knownBranches
[branch
]
1296 if parent
== branch
:
1299 print "parent determined through known branches: %s" % parent
1301 # main branch? use master
1302 if branch
== "main":
1307 branch
= self
.projectName
+ branch
1309 if parent
== "main":
1311 elif len(parent
) > 0:
1313 parent
= self
.projectName
+ parent
1315 branch
= self
.refPrefix
+ branch
1317 parent
= self
.refPrefix
+ parent
1320 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1322 if len(parent
) == 0 and branch
in self
.initialParents
:
1323 parent
= self
.initialParents
[branch
]
1324 del self
.initialParents
[branch
]
1326 self
.commit(description
, filesForCommit
, branch
, [branchPrefix
], parent
)
1328 files
= self
.extractFilesFromCommit(description
)
1329 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1331 self
.initialParent
= ""
1333 print self
.gitError
.read()
1338 if len(self
.updatedBranches
) > 0:
1339 sys
.stdout
.write("Updated branches: ")
1340 for b
in self
.updatedBranches
:
1341 sys
.stdout
.write("%s " % b
)
1342 sys
.stdout
.write("\n")
1345 self
.gitStream
.close()
1346 if importProcess
.wait() != 0:
1347 die("fast-import failed: %s" % self
.gitError
.read())
1348 self
.gitOutput
.close()
1349 self
.gitError
.close()
1353 class P4Rebase(Command
):
1355 Command
.__init
__(self
)
1357 self
.description
= ("Fetches the latest revision from perforce and "
1358 + "rebases the current work (branch) against it")
1359 self
.verbose
= False
1361 def run(self
, args
):
1365 [upstream
, settings
] = findUpstreamBranchPoint()
1366 if len(upstream
) == 0:
1367 die("Cannot find upstream branchpoint for rebase")
1369 # the branchpoint may be p4/foo~3, so strip off the parent
1370 upstream
= re
.sub("~[0-9]+$", "", upstream
)
1372 print "Rebasing the current branch onto %s" % upstream
1373 oldHead
= read_pipe("git rev-parse HEAD").strip()
1374 system("git rebase %s" % upstream
)
1375 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1378 class P4Clone(P4Sync
):
1380 P4Sync
.__init
__(self
)
1381 self
.description
= "Creates a new git repository and imports from Perforce into it"
1382 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1383 self
.options
.append(
1384 optparse
.make_option("--destination", dest
="cloneDestination",
1385 action
='store', default
=None,
1386 help="where to leave result of the clone"))
1387 self
.cloneDestination
= None
1388 self
.needsGit
= False
1390 def defaultDestination(self
, args
):
1391 ## TODO: use common prefix of args?
1393 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1394 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1395 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1396 depotDir
= re
.sub(r
"/$", "", depotDir
)
1397 return os
.path
.split(depotDir
)[1]
1399 def run(self
, args
):
1403 if self
.keepRepoPath
and not self
.cloneDestination
:
1404 sys
.stderr
.write("Must specify destination for --keep-path\n")
1409 if not self
.cloneDestination
and len(depotPaths
) > 1:
1410 self
.cloneDestination
= depotPaths
[-1]
1411 depotPaths
= depotPaths
[:-1]
1413 for p
in depotPaths
:
1414 if not p
.startswith("//"):
1417 if not self
.cloneDestination
:
1418 self
.cloneDestination
= self
.defaultDestination(args
)
1420 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1421 if not os
.path
.exists(self
.cloneDestination
):
1422 os
.makedirs(self
.cloneDestination
)
1423 os
.chdir(self
.cloneDestination
)
1425 self
.gitdir
= os
.getcwd() + "/.git"
1426 if not P4Sync
.run(self
, depotPaths
):
1428 if self
.branch
!= "master":
1429 if gitBranchExists("refs/remotes/p4/master"):
1430 system("git branch master refs/remotes/p4/master")
1431 system("git checkout -f")
1433 print "Could not detect main branch. No checkout/master branch created."
1437 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1439 optparse
.IndentedHelpFormatter
.__init
__(self
)
1441 def format_description(self
, description
):
1443 return description
+ "\n"
1447 def printUsage(commands
):
1448 print "usage: %s <command> [options]" % sys
.argv
[0]
1450 print "valid commands: %s" % ", ".join(commands
)
1452 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1457 "submit" : P4Submit
,
1459 "rebase" : P4Rebase
,
1461 "rollback" : P4RollBack
1466 if len(sys
.argv
[1:]) == 0:
1467 printUsage(commands
.keys())
1471 cmdName
= sys
.argv
[1]
1473 klass
= commands
[cmdName
]
1476 print "unknown command %s" % cmdName
1478 printUsage(commands
.keys())
1481 options
= cmd
.options
1482 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1486 if len(options
) > 0:
1487 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1489 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1491 description
= cmd
.description
,
1492 formatter
= HelpFormatter())
1494 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1496 verbose
= cmd
.verbose
1498 if cmd
.gitdir
== None:
1499 cmd
.gitdir
= os
.path
.abspath(".git")
1500 if not isValidGitDir(cmd
.gitdir
):
1501 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1502 if os
.path
.exists(cmd
.gitdir
):
1503 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1507 if not isValidGitDir(cmd
.gitdir
):
1508 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1509 cmd
.gitdir
+= "/.git"
1511 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1513 os
.environ
["GIT_DIR"] = cmd
.gitdir
1515 if not cmd
.run(args
):
1519 if __name__
== '__main__':