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")
159 values
['depot-paths'] = paths
.split(',')
162 def gitBranchExists(branch
):
163 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
164 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
165 return proc
.wait() == 0;
168 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
172 self
.usage
= "usage: %prog [options]"
175 class P4Debug(Command
):
177 Command
.__init
__(self
)
179 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
182 self
.description
= "A tool to debug the output of p4 -G."
183 self
.needsGit
= False
188 for output
in p4CmdList(" ".join(args
)):
189 print 'Element: %d' % j
194 class P4RollBack(Command
):
196 Command
.__init
__(self
)
198 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
199 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
201 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
203 self
.rollbackLocalBranches
= False
208 maxChange
= int(args
[0])
210 if "p4ExitCode" in p4Cmd("changes -m 1"):
211 die("Problems executing p4");
213 if self
.rollbackLocalBranches
:
214 refPrefix
= "refs/heads/"
215 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
217 refPrefix
= "refs/remotes/"
218 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
221 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
223 ref
= refPrefix
+ line
224 log
= extractLogMessageFromGitCommit(ref
)
225 settings
= extractSettingsGitLog(log
)
227 depotPaths
= settings
['depot-paths']
228 change
= settings
['change']
232 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
233 for p
in depotPaths
]))) == 0:
234 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
235 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
238 while change
and int(change
) > maxChange
:
241 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
242 system("git update-ref %s \"%s^\"" % (ref
, ref
))
243 log
= extractLogMessageFromGitCommit(ref
)
244 settings
= extractSettingsGitLog(log
)
247 depotPaths
= settings
['depot-paths']
248 change
= settings
['change']
251 print "%s rewound to %s" % (ref
, change
)
255 class P4Submit(Command
):
257 Command
.__init
__(self
)
259 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
260 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
261 optparse
.make_option("--origin", dest
="origin"),
262 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
263 optparse
.make_option("--log-substitutions", dest
="substFile"),
264 optparse
.make_option("--dry-run", action
="store_true"),
265 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
266 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
268 self
.description
= "Submit changes from git to the perforce depot."
269 self
.usage
+= " [name of git branch to submit into perforce depot]"
270 self
.firstTime
= True
272 self
.interactive
= True
275 self
.firstTime
= True
277 self
.directSubmit
= False
278 self
.trustMeLikeAFool
= False
281 self
.logSubstitutions
= {}
282 self
.logSubstitutions
["<enter description here>"] = "%log%"
283 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
286 if len(p4CmdList("opened ...")) > 0:
287 die("You have files opened with perforce! Close them before starting the sync.")
290 if len(self
.config
) > 0 and not self
.reset
:
291 die("Cannot start sync. Previous sync config found at %s\n"
292 "If you want to start submitting again from scratch "
293 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
296 if self
.directSubmit
:
299 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
300 commits
.append(line
.strip())
303 self
.config
["commits"] = commits
305 def prepareLogMessage(self
, template
, message
):
308 for line
in template
.split("\n"):
309 if line
.startswith("#"):
310 result
+= line
+ "\n"
314 for key
in self
.logSubstitutions
.keys():
315 if line
.find(key
) != -1:
316 value
= self
.logSubstitutions
[key
]
317 value
= value
.replace("%log%", message
)
318 if value
!= "@remove@":
319 result
+= line
.replace(key
, value
) + "\n"
324 result
+= line
+ "\n"
328 def applyCommit(self
, id):
329 if self
.directSubmit
:
330 print "Applying local change in working directory/index"
331 diff
= self
.diffStatus
333 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
334 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
336 filesToDelete
= set()
340 path
= line
[1:].strip()
342 system("p4 edit \"%s\"" % path
)
343 editedFiles
.add(path
)
344 elif modifier
== "A":
346 if path
in filesToDelete
:
347 filesToDelete
.remove(path
)
348 elif modifier
== "D":
349 filesToDelete
.add(path
)
350 if path
in filesToAdd
:
351 filesToAdd
.remove(path
)
353 die("unknown modifier %s for %s" % (modifier
, path
))
355 if self
.directSubmit
:
356 diffcmd
= "cat \"%s\"" % self
.diffFile
358 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
359 patchcmd
= diffcmd
+ " | git apply "
360 tryPatchCmd
= patchcmd
+ "--check -"
361 applyPatchCmd
= patchcmd
+ "--check --apply -"
363 if os
.system(tryPatchCmd
) != 0:
364 print "Unfortunately applying the change failed!"
365 print "What do you want to do?"
367 while response
!= "s" and response
!= "a" and response
!= "w":
368 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
369 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
371 print "Skipping! Good luck with the next patches..."
373 elif response
== "a":
374 os
.system(applyPatchCmd
)
375 if len(filesToAdd
) > 0:
376 print "You may also want to call p4 add on the following files:"
377 print " ".join(filesToAdd
)
378 if len(filesToDelete
):
379 print "The following files should be scheduled for deletion with p4 delete:"
380 print " ".join(filesToDelete
)
381 die("Please resolve and submit the conflict manually and "
382 + "continue afterwards with git-p4 submit --continue")
383 elif response
== "w":
384 system(diffcmd
+ " > patch.txt")
385 print "Patch saved to patch.txt in %s !" % self
.clientPath
386 die("Please resolve and submit the conflict manually and "
387 "continue afterwards with git-p4 submit --continue")
389 system(applyPatchCmd
)
392 system("p4 add %s" % f
)
393 for f
in filesToDelete
:
394 system("p4 revert %s" % f
)
395 system("p4 delete %s" % f
)
398 if not self
.directSubmit
:
399 logMessage
= extractLogMessageFromGitCommit(id)
400 logMessage
= logMessage
.replace("\n", "\n\t")
401 logMessage
= logMessage
.strip()
403 template
= read_pipe("p4 change -o")
406 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
407 diff
= read_pipe("p4 diff -du ...")
409 for newFile
in filesToAdd
:
410 diff
+= "==== new file ====\n"
411 diff
+= "--- /dev/null\n"
412 diff
+= "+++ %s\n" % newFile
413 f
= open(newFile
, "r")
414 for line
in f
.readlines():
418 separatorLine
= "######## everything below this line is just the diff #######"
419 if platform
.system() == "Windows":
420 separatorLine
+= "\r"
421 separatorLine
+= "\n"
424 if self
.trustMeLikeAFool
:
427 firstIteration
= True
428 while response
== "e":
429 if not firstIteration
:
430 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
431 firstIteration
= False
433 [handle
, fileName
] = tempfile
.mkstemp()
434 tmpFile
= os
.fdopen(handle
, "w+")
435 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
438 if platform
.system() == "Windows":
439 defaultEditor
= "notepad"
440 editor
= os
.environ
.get("EDITOR", defaultEditor
);
441 system(editor
+ " " + fileName
)
442 tmpFile
= open(fileName
, "rb")
443 message
= tmpFile
.read()
446 submitTemplate
= message
[:message
.index(separatorLine
)]
448 if response
== "y" or response
== "yes":
451 raw_input("Press return to continue...")
453 if self
.directSubmit
:
454 print "Submitting to git first"
455 os
.chdir(self
.oldWorkingDirectory
)
456 write_pipe("git commit -a -F -", submitTemplate
)
457 os
.chdir(self
.clientPath
)
459 write_pipe("p4 submit -i", submitTemplate
)
460 elif response
== "s":
461 for f
in editedFiles
:
462 system("p4 revert \"%s\"" % f
);
464 system("p4 revert \"%s\"" % f
);
466 for f
in filesToDelete
:
467 system("p4 delete \"%s\"" % f
);
470 print "Not submitting!"
471 self
.interactive
= False
473 fileName
= "submit.txt"
474 file = open(fileName
, "w+")
475 file.write(self
.prepareLogMessage(template
, logMessage
))
477 print ("Perforce submit template written as %s. "
478 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
479 % (fileName
, fileName
))
483 self
.master
= currentGitBranch()
484 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
485 die("Detecting current git branch failed!")
487 self
.master
= args
[0]
493 if gitBranchExists("p4"):
494 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
495 if len(depotPath
) == 0 and gitBranchExists("origin"):
496 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
497 depotPath
= settings
['depot-paths'][0]
499 if len(depotPath
) == 0:
500 print "Internal error: cannot locate perforce depot path from existing branches"
503 self
.clientPath
= p4Where(depotPath
)
505 if len(self
.clientPath
) == 0:
506 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
509 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
510 self
.oldWorkingDirectory
= os
.getcwd()
512 if self
.directSubmit
:
513 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
514 if len(self
.diffStatus
) == 0:
515 print "No changes in working directory to submit."
517 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
518 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
519 f
= open(self
.diffFile
, "wb")
523 os
.chdir(self
.clientPath
)
524 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
525 if response
== "y" or response
== "yes":
526 system("p4 sync ...")
528 if len(self
.origin
) == 0:
529 if gitBranchExists("p4"):
532 self
.origin
= "origin"
535 self
.firstTime
= True
537 if len(self
.substFile
) > 0:
538 for line
in open(self
.substFile
, "r").readlines():
539 tokens
= line
.strip().split("=")
540 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
543 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
544 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
549 commits
= self
.config
.get("commits", [])
551 while len(commits
) > 0:
552 self
.firstTime
= False
554 commits
= commits
[1:]
555 self
.config
["commits"] = commits
556 self
.applyCommit(commit
)
557 if not self
.interactive
:
562 if self
.directSubmit
:
563 os
.remove(self
.diffFile
)
565 if len(commits
) == 0:
567 print "No changes found to apply between %s and current HEAD" % self
.origin
569 print "All changes applied!"
570 os
.chdir(self
.oldWorkingDirectory
)
571 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
572 if response
== "y" or response
== "yes":
575 os
.remove(self
.configFile
)
579 class P4Sync(Command
):
581 Command
.__init
__(self
)
583 optparse
.make_option("--branch", dest
="branch"),
584 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
585 optparse
.make_option("--changesfile", dest
="changesFile"),
586 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
587 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
588 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
589 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
590 help="Import into refs/heads/ , not refs/remotes"),
591 optparse
.make_option("--max-changes", dest
="maxChanges"),
592 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
593 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
595 self
.description
= """Imports from Perforce into a git repository.\n
597 //depot/my/project/ -- to import the current head
598 //depot/my/project/@all -- to import everything
599 //depot/my/project/@1,6 -- to import only from revision 1 to 6
601 (a ... is not needed in the path p4 specification, it's added implicitly)"""
603 self
.usage
+= " //depot/path[@revRange]"
605 self
.createdBranches
= Set()
606 self
.committedChanges
= Set()
608 self
.detectBranches
= False
609 self
.detectLabels
= False
610 self
.changesFile
= ""
611 self
.syncWithOrigin
= True
613 self
.importIntoRemotes
= True
615 self
.isWindows
= (platform
.system() == "Windows")
616 self
.keepRepoPath
= False
617 self
.depotPaths
= None
619 if gitConfig("git-p4.syncFromOrigin") == "false":
620 self
.syncWithOrigin
= False
622 def extractFilesFromCommit(self
, commit
):
625 while commit
.has_key("depotFile%s" % fnum
):
626 path
= commit
["depotFile%s" % fnum
]
628 found
= [p
for p
in self
.depotPaths
629 if path
.startswith (p
)]
636 file["rev"] = commit
["rev%s" % fnum
]
637 file["action"] = commit
["action%s" % fnum
]
638 file["type"] = commit
["type%s" % fnum
]
643 def stripRepoPath(self
, path
, prefixes
):
644 if self
.keepRepoPath
:
645 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
648 if path
.startswith(p
):
653 def splitFilesIntoBranches(self
, commit
):
656 while commit
.has_key("depotFile%s" % fnum
):
657 path
= commit
["depotFile%s" % fnum
]
658 found
= [p
for p
in self
.depotPaths
659 if path
.startswith (p
)]
666 file["rev"] = commit
["rev%s" % fnum
]
667 file["action"] = commit
["action%s" % fnum
]
668 file["type"] = commit
["type%s" % fnum
]
671 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
673 for branch
in self
.knownBranches
.keys():
675 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
676 if relPath
.startswith(branch
+ "/"):
677 if branch
not in branches
:
678 branches
[branch
] = []
679 branches
[branch
].append(file)
683 ## Should move this out, doesn't use SELF.
684 def readP4Files(self
, files
):
685 files
= [f
for f
in files
686 if f
['action'] != 'delete']
691 filedata
= p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f
['path'],
697 while j
< len(filedata
):
701 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
703 text
+= filedata
[j
]['data']
706 contents
[stat
['depotFile']] = text
709 assert not f
.has_key('data')
710 f
['data'] = contents
[f
['path']]
712 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
713 epoch
= details
["time"]
714 author
= details
["user"]
717 print "commit into %s" % branch
719 # start with reading files; if that fails, we should not
723 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
726 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
728 self
.readP4Files(files
)
733 self
.gitStream
.write("commit %s\n" % branch
)
734 # gitStream.write("mark :%s\n" % details["change"])
735 self
.committedChanges
.add(int(details
["change"]))
737 if author
not in self
.users
:
738 self
.getUserMapFromPerforceServer()
739 if author
in self
.users
:
740 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
742 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
744 self
.gitStream
.write("committer %s\n" % committer
)
746 self
.gitStream
.write("data <<EOT\n")
747 self
.gitStream
.write(details
["desc"])
748 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
750 % (','.join (branchPrefixes
), details
["change"],
753 self
.gitStream
.write("EOT\n\n")
757 print "parent %s" % parent
758 self
.gitStream
.write("from %s\n" % parent
)
761 if file["type"] == "apple":
762 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
765 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
766 if file["action"] == "delete":
767 self
.gitStream
.write("D %s\n" % relPath
)
770 if file["type"].startswith("x"):
775 if self
.isWindows
and file["type"].endswith("text"):
776 data
= data
.replace("\r\n", "\n")
778 self
.gitStream
.write("M %d inline %s\n" % (mode
, relPath
))
779 self
.gitStream
.write("data %s\n" % len(data
))
780 self
.gitStream
.write(data
)
781 self
.gitStream
.write("\n")
783 self
.gitStream
.write("\n")
785 change
= int(details
["change"])
787 if self
.labels
.has_key(change
):
788 label
= self
.labels
[change
]
789 labelDetails
= label
[0]
790 labelRevisions
= label
[1]
792 print "Change %s is labelled %s" % (change
, labelDetails
)
794 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
795 for p
in branchPrefixes
]))
797 if len(files
) == len(labelRevisions
):
801 if info
["action"] == "delete":
803 cleanedFiles
[info
["depotFile"]] = info
["rev"]
805 if cleanedFiles
== labelRevisions
:
806 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
807 self
.gitStream
.write("from %s\n" % branch
)
809 owner
= labelDetails
["Owner"]
811 if author
in self
.users
:
812 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
814 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
815 self
.gitStream
.write("tagger %s\n" % tagger
)
816 self
.gitStream
.write("data <<EOT\n")
817 self
.gitStream
.write(labelDetails
["Description"])
818 self
.gitStream
.write("EOT\n\n")
822 print ("Tag %s does not match with change %s: files do not match."
823 % (labelDetails
["label"], change
))
827 print ("Tag %s does not match with change %s: file count is different."
828 % (labelDetails
["label"], change
))
830 def getUserCacheFilename(self
):
831 return os
.environ
["HOME"] + "/.gitp4-usercache.txt"
833 def getUserMapFromPerforceServer(self
):
834 if self
.userMapFromPerforceServer
:
838 for output
in p4CmdList("users"):
839 if not output
.has_key("User"):
841 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
845 for (key
, val
) in self
.users
.items():
846 s
+= "%s\t%s\n" % (key
, val
)
848 open(self
.getUserCacheFilename(), "wb").write(s
)
849 self
.userMapFromPerforceServer
= True
851 def loadUserMapFromCache(self
):
853 self
.userMapFromPerforceServer
= False
855 cache
= open(self
.getUserCacheFilename(), "rb")
856 lines
= cache
.readlines()
859 entry
= line
.strip().split("\t")
860 self
.users
[entry
[0]] = entry
[1]
862 self
.getUserMapFromPerforceServer()
867 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
868 if len(l
) > 0 and not self
.silent
:
869 print "Finding files belonging to labels in %s" % `self
.depotPath`
872 label
= output
["label"]
876 print "Querying files for label %s" % label
877 for file in p4CmdList("files "
878 + ' '.join (["%s...@%s" % (p
, label
)
879 for p
in self
.depotPaths
])):
880 revisions
[file["depotFile"]] = file["rev"]
881 change
= int(file["change"])
882 if change
> newestChange
:
883 newestChange
= change
885 self
.labels
[newestChange
] = [output
, revisions
]
888 print "Label changes: %s" % self
.labels
.keys()
890 def guessProjectName(self
):
891 for p
in self
.depotPaths
:
892 return p
[p
.strip().rfind("/") + 1:]
894 def getBranchMapping(self
):
896 ## FIXME - what's a P4 projectName ?
897 self
.projectName
= self
.guessProjectName()
899 for info
in p4CmdList("branches"):
900 details
= p4Cmd("branch -o %s" % info
["branch"])
902 while details
.has_key("View%s" % viewIdx
):
903 paths
= details
["View%s" % viewIdx
].split(" ")
904 viewIdx
= viewIdx
+ 1
905 # require standard //depot/foo/... //depot/bar/... mapping
906 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
909 destination
= paths
[1]
911 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
912 source
= source
[len(self
.depotPaths
[0]):-4]
913 destination
= destination
[len(self
.depotPaths
[0]):-4]
914 if destination
not in self
.knownBranches
:
915 self
.knownBranches
[destination
] = source
916 if source
not in self
.knownBranches
:
917 self
.knownBranches
[source
] = source
919 def listExistingP4GitBranches(self
):
920 self
.p4BranchesInGit
= []
922 cmdline
= "git rev-parse --symbolic "
923 if self
.importIntoRemotes
:
924 cmdline
+= " --remotes"
926 cmdline
+= " --branches"
928 for line
in read_pipe_lines(cmdline
):
931 ## only import to p4/
932 if not line
.startswith('p4/'):
935 if self
.importIntoRemotes
:
937 branch
= re
.sub ("^p4/", "", line
)
939 self
.p4BranchesInGit
.append(branch
)
940 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
942 def createOrUpdateBranchesFromOrigin(self
):
944 print ("Creating/updating branch(es) in %s based on origin branch(es)"
947 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
949 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
952 headName
= line
[len("origin/"):]
953 remoteHead
= self
.refPrefix
+ headName
954 originHead
= "origin/" + headName
956 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
957 if (not original
.has_key('depot-paths')
958 or not original
.has_key('change')):
962 if not gitBranchExists(remoteHead
):
964 print "creating %s" % remoteHead
967 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
968 if settings
.has_key('change') > 0:
969 if settings
['depot-paths'] == original
['depot-paths']:
970 originP4Change
= int(original
['change'])
971 p4Change
= int(settings
['change'])
972 if originP4Change
> p4Change
:
973 print ("%s (%s) is newer than %s (%s). "
974 "Updating p4 branch from origin."
975 % (originHead
, originP4Change
,
976 remoteHead
, p4Change
))
979 print ("Ignoring: %s was imported from %s while "
980 "%s was imported from %s"
981 % (originHead
, ','.join(original
['depot-paths']),
982 remoteHead
, ','.join(settings
['depot-paths'])))
985 system("git update-ref %s %s" % (remoteHead
, originHead
))
987 def updateOptionDict(self
, d
):
989 if self
.keepRepoPath
:
990 option_keys
['keepRepoPath'] = 1
992 d
["options"] = ' '.join(sorted(option_keys
.keys()))
994 def readOptions(self
, d
):
995 self
.keepRepoPath
= (d
.has_key('options')
996 and ('keepRepoPath' in d
['options']))
1000 self
.changeRange
= ""
1001 self
.initialParent
= ""
1002 self
.previousDepotPaths
= []
1004 # map from branch depot path to parent branch
1005 self
.knownBranches
= {}
1006 self
.initialParents
= {}
1007 self
.hasOrigin
= gitBranchExists("origin")
1009 if self
.importIntoRemotes
:
1010 self
.refPrefix
= "refs/remotes/p4/"
1012 self
.refPrefix
= "refs/heads/"
1014 if self
.syncWithOrigin
and self
.hasOrigin
:
1016 print "Syncing with origin first by calling git fetch origin"
1017 system("git fetch origin")
1019 if len(self
.branch
) == 0:
1020 self
.branch
= self
.refPrefix
+ "p4/master"
1021 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1022 system("git update-ref %s refs/heads/p4" % self
.branch
)
1023 system("git branch -D p4");
1024 # create it /after/ importing, when master exists
1025 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
1026 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1028 # TODO: should always look at previous commits,
1029 # merge with previous imports, if possible.
1032 self
.createOrUpdateBranchesFromOrigin()
1033 self
.listExistingP4GitBranches()
1035 if len(self
.p4BranchesInGit
) > 1:
1037 print "Importing from/into multiple branches"
1038 self
.detectBranches
= True
1041 print "branches: %s" % self
.p4BranchesInGit
1044 for branch
in self
.p4BranchesInGit
:
1045 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1047 settings
= extractSettingsGitLog(logMsg
)
1049 self
.readOptions(settings
)
1050 if (settings
.has_key('depot-paths')
1051 and settings
.has_key ('change')):
1052 change
= int(settings
['change']) + 1
1053 p4Change
= max(p4Change
, change
)
1055 depotPaths
= sorted(settings
['depot-paths'])
1056 if self
.previousDepotPaths
== []:
1057 self
.previousDepotPaths
= depotPaths
1060 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1061 for i
in range(0, min(len(cur
), len(prev
))):
1062 if cur
[i
] <> prev
[i
]:
1066 paths
.append (cur
[:i
+ 1])
1068 self
.previousDepotPaths
= paths
1071 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1072 self
.changeRange
= "@%s,#head" % p4Change
1073 if not self
.detectBranches
:
1074 self
.initialParent
= parseRevision(self
.branch
)
1075 if not self
.silent
and not self
.detectBranches
:
1076 print "Performing incremental import into %s git branch" % self
.branch
1078 if not self
.branch
.startswith("refs/"):
1079 self
.branch
= "refs/heads/" + self
.branch
1081 if len(args
) == 0 and self
.depotPaths
:
1083 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1085 if self
.depotPaths
and self
.depotPaths
!= args
:
1086 print ("previous import used depot path %s and now %s was specified. "
1087 "This doesn't work!" % (' '.join (self
.depotPaths
),
1091 self
.depotPaths
= sorted(args
)
1097 for p
in self
.depotPaths
:
1098 if p
.find("@") != -1:
1099 atIdx
= p
.index("@")
1100 self
.changeRange
= p
[atIdx
:]
1101 if self
.changeRange
== "@all":
1102 self
.changeRange
= ""
1103 elif ',' not in self
.changeRange
:
1104 self
.revision
= self
.changeRange
1105 self
.changeRange
= ""
1107 elif p
.find("#") != -1:
1108 hashIdx
= p
.index("#")
1109 self
.revision
= p
[hashIdx
:]
1111 elif self
.previousDepotPaths
== []:
1112 self
.revision
= "#head"
1114 p
= re
.sub ("\.\.\.$", "", p
)
1115 if not p
.endswith("/"):
1120 self
.depotPaths
= newPaths
1123 self
.loadUserMapFromCache()
1125 if self
.detectLabels
:
1128 if self
.detectBranches
:
1129 self
.getBranchMapping();
1131 print "p4-git branches: %s" % self
.p4BranchesInGit
1132 print "initial parents: %s" % self
.initialParents
1133 for b
in self
.p4BranchesInGit
:
1137 b
= b
[len(self
.projectName
):]
1138 self
.createdBranches
.add(b
)
1140 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1142 importProcess
= subprocess
.Popen(["git", "fast-import"],
1143 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1144 stderr
=subprocess
.PIPE
);
1145 self
.gitOutput
= importProcess
.stdout
1146 self
.gitStream
= importProcess
.stdin
1147 self
.gitError
= importProcess
.stderr
1150 print "Doing initial import of %s from revision %s" % (' '.join(self
.depotPaths
), self
.revision
)
1152 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1153 details
["desc"] = ("Initial import of %s from the state at revision %s"
1154 % (' '.join(self
.depotPaths
), self
.revision
))
1155 details
["change"] = self
.revision
1159 for info
in p4CmdList("files "
1160 + ' '.join(["%s...%s"
1161 % (p
, self
.revision
)
1162 for p
in self
.depotPaths
])):
1164 if info
['code'] == 'error':
1165 sys
.stderr
.write("p4 returned an error: %s\n"
1170 change
= int(info
["change"])
1171 if change
> newestRevision
:
1172 newestRevision
= change
1174 if info
["action"] == "delete":
1175 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1176 #fileCnt = fileCnt + 1
1179 for prop
in ["depotFile", "rev", "action", "type" ]:
1180 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1182 fileCnt
= fileCnt
+ 1
1184 details
["change"] = newestRevision
1185 self
.updateOptionDict(details
)
1187 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1189 print "IO error with git fast-import. Is your git version recent enough?"
1190 print self
.gitError
.read()
1195 if len(self
.changesFile
) > 0:
1196 output
= open(self
.changesFile
).readlines()
1199 changeSet
.add(int(line
))
1201 for change
in changeSet
:
1202 changes
.append(change
)
1207 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1209 assert self
.depotPaths
1210 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1211 for p
in self
.depotPaths
]))
1214 changeNum
= line
.split(" ")[1]
1215 changes
.append(changeNum
)
1219 if len(self
.maxChanges
) > 0:
1220 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1222 if len(changes
) == 0:
1224 print "No changes to import!"
1227 self
.updatedBranches
= set()
1230 for change
in changes
:
1231 description
= p4Cmd("describe %s" % change
)
1232 self
.updateOptionDict(description
)
1235 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1240 if self
.detectBranches
:
1241 branches
= self
.splitFilesIntoBranches(description
)
1242 for branch
in branches
.keys():
1244 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1248 filesForCommit
= branches
[branch
]
1251 print "branch is %s" % branch
1253 self
.updatedBranches
.add(branch
)
1255 if branch
not in self
.createdBranches
:
1256 self
.createdBranches
.add(branch
)
1257 parent
= self
.knownBranches
[branch
]
1258 if parent
== branch
:
1261 print "parent determined through known branches: %s" % parent
1263 # main branch? use master
1264 if branch
== "main":
1269 branch
= self
.projectName
+ branch
1271 if parent
== "main":
1273 elif len(parent
) > 0:
1275 parent
= self
.projectName
+ parent
1277 branch
= self
.refPrefix
+ branch
1279 parent
= self
.refPrefix
+ parent
1282 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1284 if len(parent
) == 0 and branch
in self
.initialParents
:
1285 parent
= self
.initialParents
[branch
]
1286 del self
.initialParents
[branch
]
1288 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1290 files
= self
.extractFilesFromCommit(description
)
1291 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1293 self
.initialParent
= ""
1295 print self
.gitError
.read()
1300 if len(self
.updatedBranches
) > 0:
1301 sys
.stdout
.write("Updated branches: ")
1302 for b
in self
.updatedBranches
:
1303 sys
.stdout
.write("%s " % b
)
1304 sys
.stdout
.write("\n")
1307 self
.gitStream
.close()
1308 if importProcess
.wait() != 0:
1309 die("fast-import failed: %s" % self
.gitError
.read())
1310 self
.gitOutput
.close()
1311 self
.gitError
.close()
1315 class P4Rebase(Command
):
1317 Command
.__init
__(self
)
1319 self
.description
= ("Fetches the latest revision from perforce and "
1320 + "rebases the current work (branch) against it")
1321 self
.verbose
= False
1323 def run(self
, args
):
1326 print "Rebasing the current branch"
1327 oldHead
= read_pipe("git rev-parse HEAD").strip()
1328 system("git rebase p4")
1329 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1332 class P4Clone(P4Sync
):
1334 P4Sync
.__init
__(self
)
1335 self
.description
= "Creates a new git repository and imports from Perforce into it"
1336 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1337 self
.options
.append(
1338 optparse
.make_option("--destination", dest
="cloneDestination",
1339 action
='store', default
=None,
1340 help="where to leave result of the clone"))
1341 self
.cloneDestination
= None
1342 self
.needsGit
= False
1344 def defaultDestination(self
, args
):
1345 ## TODO: use common prefix of args?
1347 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1348 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1349 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1350 depotDir
= re
.sub(r
"/$", "", depotDir
)
1351 return os
.path
.split(depotDir
)[1]
1353 def run(self
, args
):
1357 if self
.keepRepoPath
and not self
.cloneDestination
:
1358 sys
.stderr
.write("Must specify destination for --keep-path\n")
1362 for p
in depotPaths
:
1363 if not p
.startswith("//"):
1366 if not self
.cloneDestination
:
1367 self
.cloneDestination
= self
.defaultDestination()
1369 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1370 os
.makedirs(self
.cloneDestination
)
1371 os
.chdir(self
.cloneDestination
)
1373 self
.gitdir
= os
.getcwd() + "/.git"
1374 if not P4Sync
.run(self
, depotPaths
):
1376 if self
.branch
!= "master":
1377 if gitBranchExists("refs/remotes/p4/master"):
1378 system("git branch master refs/remotes/p4/master")
1379 system("git checkout -f")
1381 print "Could not detect main branch. No checkout/master branch created."
1385 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1387 optparse
.IndentedHelpFormatter
.__init
__(self
)
1389 def format_description(self
, description
):
1391 return description
+ "\n"
1395 def printUsage(commands
):
1396 print "usage: %s <command> [options]" % sys
.argv
[0]
1398 print "valid commands: %s" % ", ".join(commands
)
1400 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1405 "submit" : P4Submit
,
1407 "rebase" : P4Rebase
,
1409 "rollback" : P4RollBack
1414 if len(sys
.argv
[1:]) == 0:
1415 printUsage(commands
.keys())
1419 cmdName
= sys
.argv
[1]
1421 klass
= commands
[cmdName
]
1424 print "unknown command %s" % cmdName
1426 printUsage(commands
.keys())
1429 options
= cmd
.options
1430 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1434 if len(options
) > 0:
1435 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1437 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1439 description
= cmd
.description
,
1440 formatter
= HelpFormatter())
1442 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1444 verbose
= cmd
.verbose
1446 if cmd
.gitdir
== None:
1447 cmd
.gitdir
= os
.path
.abspath(".git")
1448 if not isValidGitDir(cmd
.gitdir
):
1449 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1450 if os
.path
.exists(cmd
.gitdir
):
1451 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1455 if not isValidGitDir(cmd
.gitdir
):
1456 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1457 cmd
.gitdir
+= "/.git"
1459 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1461 os
.environ
["GIT_DIR"] = cmd
.gitdir
1463 if not cmd
.run(args
):
1467 if __name__
== '__main__':