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 values
['depot-paths'] = values
.get("depot-paths").split(',')
159 def gitBranchExists(branch
):
160 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
161 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
162 return proc
.wait() == 0;
165 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
169 self
.usage
= "usage: %prog [options]"
172 class P4Debug(Command
):
174 Command
.__init
__(self
)
176 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
179 self
.description
= "A tool to debug the output of p4 -G."
180 self
.needsGit
= False
185 for output
in p4CmdList(" ".join(args
)):
186 print 'Element: %d' % j
191 class P4RollBack(Command
):
193 Command
.__init
__(self
)
195 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
196 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
198 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
200 self
.rollbackLocalBranches
= False
205 maxChange
= int(args
[0])
207 if "p4ExitCode" in p4Cmd("changes -m 1"):
208 die("Problems executing p4");
210 if self
.rollbackLocalBranches
:
211 refPrefix
= "refs/heads/"
212 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
214 refPrefix
= "refs/remotes/"
215 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
218 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
220 ref
= refPrefix
+ line
221 log
= extractLogMessageFromGitCommit(ref
)
222 settings
= extractSettingsGitLog(log
)
224 depotPaths
= settings
['depot-paths']
225 change
= settings
['change']
229 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
230 for p
in depotPaths
]))) == 0:
231 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
232 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
235 while change
and int(change
) > maxChange
:
238 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
239 system("git update-ref %s \"%s^\"" % (ref
, ref
))
240 log
= extractLogMessageFromGitCommit(ref
)
241 settings
= extractSettingsGitLog(log
)
244 depotPaths
= settings
['depot-paths']
245 change
= settings
['change']
248 print "%s rewound to %s" % (ref
, change
)
252 class P4Submit(Command
):
254 Command
.__init
__(self
)
256 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
257 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
258 optparse
.make_option("--origin", dest
="origin"),
259 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
260 optparse
.make_option("--log-substitutions", dest
="substFile"),
261 optparse
.make_option("--dry-run", action
="store_true"),
262 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
263 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
265 self
.description
= "Submit changes from git to the perforce depot."
266 self
.usage
+= " [name of git branch to submit into perforce depot]"
267 self
.firstTime
= True
269 self
.interactive
= True
272 self
.firstTime
= True
274 self
.directSubmit
= False
275 self
.trustMeLikeAFool
= False
277 self
.logSubstitutions
= {}
278 self
.logSubstitutions
["<enter description here>"] = "%log%"
279 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
282 if len(p4CmdList("opened ...")) > 0:
283 die("You have files opened with perforce! Close them before starting the sync.")
286 if len(self
.config
) > 0 and not self
.reset
:
287 die("Cannot start sync. Previous sync config found at %s\n"
288 "If you want to start submitting again from scratch "
289 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
292 if self
.directSubmit
:
295 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
296 commits
.append(line
.strip())
299 self
.config
["commits"] = commits
301 def prepareLogMessage(self
, template
, message
):
304 for line
in template
.split("\n"):
305 if line
.startswith("#"):
306 result
+= line
+ "\n"
310 for key
in self
.logSubstitutions
.keys():
311 if line
.find(key
) != -1:
312 value
= self
.logSubstitutions
[key
]
313 value
= value
.replace("%log%", message
)
314 if value
!= "@remove@":
315 result
+= line
.replace(key
, value
) + "\n"
320 result
+= line
+ "\n"
324 def applyCommit(self
, id):
325 if self
.directSubmit
:
326 print "Applying local change in working directory/index"
327 diff
= self
.diffStatus
329 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
330 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
332 filesToDelete
= set()
336 path
= line
[1:].strip()
338 system("p4 edit \"%s\"" % path
)
339 editedFiles
.add(path
)
340 elif modifier
== "A":
342 if path
in filesToDelete
:
343 filesToDelete
.remove(path
)
344 elif modifier
== "D":
345 filesToDelete
.add(path
)
346 if path
in filesToAdd
:
347 filesToAdd
.remove(path
)
349 die("unknown modifier %s for %s" % (modifier
, path
))
351 if self
.directSubmit
:
352 diffcmd
= "cat \"%s\"" % self
.diffFile
354 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
355 patchcmd
= diffcmd
+ " | git apply "
356 tryPatchCmd
= patchcmd
+ "--check -"
357 applyPatchCmd
= patchcmd
+ "--check --apply -"
359 if os
.system(tryPatchCmd
) != 0:
360 print "Unfortunately applying the change failed!"
361 print "What do you want to do?"
363 while response
!= "s" and response
!= "a" and response
!= "w":
364 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
365 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
367 print "Skipping! Good luck with the next patches..."
369 elif response
== "a":
370 os
.system(applyPatchCmd
)
371 if len(filesToAdd
) > 0:
372 print "You may also want to call p4 add on the following files:"
373 print " ".join(filesToAdd
)
374 if len(filesToDelete
):
375 print "The following files should be scheduled for deletion with p4 delete:"
376 print " ".join(filesToDelete
)
377 die("Please resolve and submit the conflict manually and "
378 + "continue afterwards with git-p4 submit --continue")
379 elif response
== "w":
380 system(diffcmd
+ " > patch.txt")
381 print "Patch saved to patch.txt in %s !" % self
.clientPath
382 die("Please resolve and submit the conflict manually and "
383 "continue afterwards with git-p4 submit --continue")
385 system(applyPatchCmd
)
388 system("p4 add %s" % f
)
389 for f
in filesToDelete
:
390 system("p4 revert %s" % f
)
391 system("p4 delete %s" % f
)
394 if not self
.directSubmit
:
395 logMessage
= extractLogMessageFromGitCommit(id)
396 logMessage
= logMessage
.replace("\n", "\n\t")
397 logMessage
= logMessage
.strip()
399 template
= read_pipe("p4 change -o")
402 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
403 diff
= read_pipe("p4 diff -du ...")
405 for newFile
in filesToAdd
:
406 diff
+= "==== new file ====\n"
407 diff
+= "--- /dev/null\n"
408 diff
+= "+++ %s\n" % newFile
409 f
= open(newFile
, "r")
410 for line
in f
.readlines():
414 separatorLine
= "######## everything below this line is just the diff #######"
415 if platform
.system() == "Windows":
416 separatorLine
+= "\r"
417 separatorLine
+= "\n"
420 if self
.trustMeLikeAFool
:
423 firstIteration
= True
424 while response
== "e":
425 if not firstIteration
:
426 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
427 firstIteration
= False
429 [handle
, fileName
] = tempfile
.mkstemp()
430 tmpFile
= os
.fdopen(handle
, "w+")
431 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
434 if platform
.system() == "Windows":
435 defaultEditor
= "notepad"
436 editor
= os
.environ
.get("EDITOR", defaultEditor
);
437 system(editor
+ " " + fileName
)
438 tmpFile
= open(fileName
, "rb")
439 message
= tmpFile
.read()
442 submitTemplate
= message
[:message
.index(separatorLine
)]
444 if response
== "y" or response
== "yes":
447 raw_input("Press return to continue...")
449 if self
.directSubmit
:
450 print "Submitting to git first"
451 os
.chdir(self
.oldWorkingDirectory
)
452 write_pipe("git commit -a -F -", submitTemplate
)
453 os
.chdir(self
.clientPath
)
455 write_pipe("p4 submit -i", submitTemplate
)
456 elif response
== "s":
457 for f
in editedFiles
:
458 system("p4 revert \"%s\"" % f
);
460 system("p4 revert \"%s\"" % f
);
462 for f
in filesToDelete
:
463 system("p4 delete \"%s\"" % f
);
466 print "Not submitting!"
467 self
.interactive
= False
469 fileName
= "submit.txt"
470 file = open(fileName
, "w+")
471 file.write(self
.prepareLogMessage(template
, logMessage
))
473 print ("Perforce submit template written as %s. "
474 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
475 % (fileName
, fileName
))
478 # make gitdir absolute so we can cd out into the perforce checkout
479 os
.environ
["GIT_DIR"] = gitdir
482 self
.master
= currentGitBranch()
483 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
484 die("Detecting current git branch failed!")
486 self
.master
= args
[0]
492 if gitBranchExists("p4"):
493 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
494 if len(depotPath
) == 0 and gitBranchExists("origin"):
495 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
496 depotPaths
= settings
['depot-paths']
498 if len(depotPath
) == 0:
499 print "Internal error: cannot locate perforce depot path from existing branches"
502 self
.clientPath
= p4Where(depotPath
)
504 if len(self
.clientPath
) == 0:
505 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
508 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
509 self
.oldWorkingDirectory
= os
.getcwd()
511 if self
.directSubmit
:
512 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
513 if len(self
.diffStatus
) == 0:
514 print "No changes in working directory to submit."
516 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
517 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
518 f
= open(self
.diffFile
, "wb")
522 os
.chdir(self
.clientPath
)
523 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
524 if response
== "y" or response
== "yes":
525 system("p4 sync ...")
527 if len(self
.origin
) == 0:
528 if gitBranchExists("p4"):
531 self
.origin
= "origin"
534 self
.firstTime
= True
536 if len(self
.substFile
) > 0:
537 for line
in open(self
.substFile
, "r").readlines():
538 tokens
= line
.strip().split("=")
539 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
542 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
543 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
548 commits
= self
.config
.get("commits", [])
550 while len(commits
) > 0:
551 self
.firstTime
= False
553 commits
= commits
[1:]
554 self
.config
["commits"] = commits
555 self
.applyCommit(commit
)
556 if not self
.interactive
:
561 if self
.directSubmit
:
562 os
.remove(self
.diffFile
)
564 if len(commits
) == 0:
566 print "No changes found to apply between %s and current HEAD" % self
.origin
568 print "All changes applied!"
569 os
.chdir(self
.oldWorkingDirectory
)
570 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
571 if response
== "y" or response
== "yes":
574 os
.remove(self
.configFile
)
578 class P4Sync(Command
):
580 Command
.__init
__(self
)
582 optparse
.make_option("--branch", dest
="branch"),
583 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
584 optparse
.make_option("--changesfile", dest
="changesFile"),
585 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
586 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
587 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
588 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
589 help="Import into refs/heads/ , not refs/remotes"),
590 optparse
.make_option("--max-changes", dest
="maxChanges"),
591 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
592 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
594 self
.description
= """Imports from Perforce into a git repository.\n
596 //depot/my/project/ -- to import the current head
597 //depot/my/project/@all -- to import everything
598 //depot/my/project/@1,6 -- to import only from revision 1 to 6
600 (a ... is not needed in the path p4 specification, it's added implicitly)"""
602 self
.usage
+= " //depot/path[@revRange]"
604 self
.createdBranches
= Set()
605 self
.committedChanges
= Set()
607 self
.detectBranches
= False
608 self
.detectLabels
= False
609 self
.changesFile
= ""
610 self
.syncWithOrigin
= True
612 self
.importIntoRemotes
= True
614 self
.isWindows
= (platform
.system() == "Windows")
615 self
.keepRepoPath
= False
616 self
.depotPaths
= None
618 if gitConfig("git-p4.syncFromOrigin") == "false":
619 self
.syncWithOrigin
= False
621 def extractFilesFromCommit(self
, commit
):
624 while commit
.has_key("depotFile%s" % fnum
):
625 path
= commit
["depotFile%s" % fnum
]
627 found
= [p
for p
in self
.depotPaths
628 if path
.startswith (p
)]
635 file["rev"] = commit
["rev%s" % fnum
]
636 file["action"] = commit
["action%s" % fnum
]
637 file["type"] = commit
["type%s" % fnum
]
642 def stripRepoPath(self
, path
, prefixes
):
643 if self
.keepRepoPath
:
644 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
647 if path
.startswith(p
):
652 def splitFilesIntoBranches(self
, commit
):
655 while commit
.has_key("depotFile%s" % fnum
):
656 path
= commit
["depotFile%s" % fnum
]
657 found
= [p
for p
in self
.depotPaths
658 if path
.startswith (p
)]
665 file["rev"] = commit
["rev%s" % fnum
]
666 file["action"] = commit
["action%s" % fnum
]
667 file["type"] = commit
["type%s" % fnum
]
670 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
672 for branch
in self
.knownBranches
.keys():
674 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
675 if relPath
.startswith(branch
+ "/"):
676 if branch
not in branches
:
677 branches
[branch
] = []
678 branches
[branch
].append(file)
682 ## Should move this out, doesn't use SELF.
683 def readP4Files(self
, files
):
684 files
= [f
for f
in files
685 if f
['action'] != 'delete']
690 filedata
= p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f
['path'],
696 while j
< len(filedata
):
700 while j
< len(filedata
) and filedata
[j
]['code'] == 'text':
701 text
+= filedata
[j
]['data']
704 contents
[stat
['depotFile']] = text
707 assert not f
.has_key('data')
708 f
['data'] = contents
[f
['path']]
710 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
711 epoch
= details
["time"]
712 author
= details
["user"]
715 print "commit into %s" % branch
717 # start with reading files; if that fails, we should not
721 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
724 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
726 self
.readP4Files(files
)
731 self
.gitStream
.write("commit %s\n" % branch
)
732 # gitStream.write("mark :%s\n" % details["change"])
733 self
.committedChanges
.add(int(details
["change"]))
735 if author
not in self
.users
:
736 self
.getUserMapFromPerforceServer()
737 if author
in self
.users
:
738 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
740 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
742 self
.gitStream
.write("committer %s\n" % committer
)
744 self
.gitStream
.write("data <<EOT\n")
745 self
.gitStream
.write(details
["desc"])
746 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
748 % (','.join (branchPrefixes
), details
["change"],
751 self
.gitStream
.write("EOT\n\n")
755 print "parent %s" % parent
756 self
.gitStream
.write("from %s\n" % parent
)
759 if file["type"] == "apple":
760 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
763 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
764 if file["action"] == "delete":
765 self
.gitStream
.write("D %s\n" % relPath
)
768 if file["type"].startswith("x"):
773 if self
.isWindows
and file["type"].endswith("text"):
774 data
= data
.replace("\r\n", "\n")
776 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
777 self
.gitStream
.write("data %s\n" % len(data
))
778 self
.gitStream
.write(data
)
779 self
.gitStream
.write("\n")
781 self
.gitStream
.write("\n")
783 change
= int(details
["change"])
785 if self
.labels
.has_key(change
):
786 label
= self
.labels
[change
]
787 labelDetails
= label
[0]
788 labelRevisions
= label
[1]
790 print "Change %s is labelled %s" % (change
, labelDetails
)
792 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
793 for p
in branchPrefixes
]))
795 if len(files
) == len(labelRevisions
):
799 if info
["action"] == "delete":
801 cleanedFiles
[info
["depotFile"]] = info
["rev"]
803 if cleanedFiles
== labelRevisions
:
804 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
805 self
.gitStream
.write("from %s\n" % branch
)
807 owner
= labelDetails
["Owner"]
809 if author
in self
.users
:
810 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
812 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
813 self
.gitStream
.write("tagger %s\n" % tagger
)
814 self
.gitStream
.write("data <<EOT\n")
815 self
.gitStream
.write(labelDetails
["Description"])
816 self
.gitStream
.write("EOT\n\n")
820 print ("Tag %s does not match with change %s: files do not match."
821 % (labelDetails
["label"], change
))
825 print ("Tag %s does not match with change %s: file count is different."
826 % (labelDetails
["label"], change
))
828 def getUserCacheFilename(self
):
829 return os
.environ
["HOME"] + "/.gitp4-usercache.txt"
831 def getUserMapFromPerforceServer(self
):
832 if self
.userMapFromPerforceServer
:
836 for output
in p4CmdList("users"):
837 if not output
.has_key("User"):
839 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
843 for (key
, val
) in self
.users
.items():
844 s
+= "%s\t%s\n" % (key
, val
)
846 open(self
.getUserCacheFilename(), "wb").write(s
)
847 self
.userMapFromPerforceServer
= True
849 def loadUserMapFromCache(self
):
851 self
.userMapFromPerforceServer
= False
853 cache
= open(self
.getUserCacheFilename(), "rb")
854 lines
= cache
.readlines()
857 entry
= line
.strip().split("\t")
858 self
.users
[entry
[0]] = entry
[1]
860 self
.getUserMapFromPerforceServer()
865 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
866 if len(l
) > 0 and not self
.silent
:
867 print "Finding files belonging to labels in %s" % `self
.depotPath`
870 label
= output
["label"]
874 print "Querying files for label %s" % label
875 for file in p4CmdList("files "
876 + ' '.join (["%s...@%s" % (p
, label
)
877 for p
in self
.depotPaths
])):
878 revisions
[file["depotFile"]] = file["rev"]
879 change
= int(file["change"])
880 if change
> newestChange
:
881 newestChange
= change
883 self
.labels
[newestChange
] = [output
, revisions
]
886 print "Label changes: %s" % self
.labels
.keys()
888 def guessProjectName(self
):
889 for p
in self
.depotPaths
:
890 return p
[p
.strip().rfind("/") + 1:]
892 def getBranchMapping(self
):
894 ## FIXME - what's a P4 projectName ?
895 self
.projectName
= self
.guessProjectName()
897 for info
in p4CmdList("branches"):
898 details
= p4Cmd("branch -o %s" % info
["branch"])
900 while details
.has_key("View%s" % viewIdx
):
901 paths
= details
["View%s" % viewIdx
].split(" ")
902 viewIdx
= viewIdx
+ 1
903 # require standard //depot/foo/... //depot/bar/... mapping
904 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
907 destination
= paths
[1]
908 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
909 source
= source
[len(self
.depotPath
):-4]
910 destination
= destination
[len(self
.depotPath
):-4]
911 if destination
not in self
.knownBranches
:
912 self
.knownBranches
[destination
] = source
913 if source
not in self
.knownBranches
:
914 self
.knownBranches
[source
] = source
916 def listExistingP4GitBranches(self
):
917 self
.p4BranchesInGit
= []
919 cmdline
= "git rev-parse --symbolic "
920 if self
.importIntoRemotes
:
921 cmdline
+= " --remotes"
923 cmdline
+= " --branches"
925 for line
in read_pipe_lines(cmdline
):
928 ## only import to p4/
929 if not line
.startswith('p4/'):
932 if self
.importIntoRemotes
:
934 branch
= re
.sub ("^p4/", "", line
)
936 self
.p4BranchesInGit
.append(branch
)
937 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
939 def createOrUpdateBranchesFromOrigin(self
):
941 print ("Creating/updating branch(es) in %s based on origin branch(es)"
944 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
946 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
949 headName
= line
[len("origin/"):]
950 remoteHead
= self
.refPrefix
+ headName
951 originHead
= "origin/" + headName
953 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
954 if (not original
.has_key('depot-paths')
955 or not original
.has_key('change')):
959 if not gitBranchExists(remoteHead
):
961 print "creating %s" % remoteHead
964 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
965 if settings
.has_key('change') > 0:
966 if settings
['depot-paths'] == original
['depot-paths']:
967 originP4Change
= int(original
['change'])
968 p4Change
= int(settings
['change'])
969 if originP4Change
> p4Change
:
970 print ("%s (%s) is newer than %s (%s). "
971 "Updating p4 branch from origin."
972 % (originHead
, originP4Change
,
973 remoteHead
, p4Change
))
976 print ("Ignoring: %s was imported from %s while "
977 "%s was imported from %s"
978 % (originHead
, ','.join(original
['depot-paths']),
979 remoteHead
, ','.join(settings
['depot-paths'])))
982 system("git update-ref %s %s" % (remoteHead
, originHead
))
984 def updateOptionDict(self
, d
):
986 if self
.keepRepoPath
:
987 option_keys
['keepRepoPath'] = 1
989 d
["options"] = ' '.join(sorted(option_keys
.keys()))
991 def readOptions(self
, d
):
992 self
.keepRepoPath
= (d
.has_key('options')
993 and ('keepRepoPath' in d
['options']))
997 self
.changeRange
= ""
998 self
.initialParent
= ""
999 self
.previousDepotPaths
= []
1001 # map from branch depot path to parent branch
1002 self
.knownBranches
= {}
1003 self
.initialParents
= {}
1004 self
.hasOrigin
= gitBranchExists("origin")
1006 if self
.importIntoRemotes
:
1007 self
.refPrefix
= "refs/remotes/p4/"
1009 self
.refPrefix
= "refs/heads/"
1011 if self
.syncWithOrigin
and self
.hasOrigin
:
1013 print "Syncing with origin first by calling git fetch origin"
1014 system("git fetch origin")
1016 if len(self
.branch
) == 0:
1017 self
.branch
= self
.refPrefix
+ "p4/master"
1018 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1019 system("git update-ref %s refs/heads/p4" % self
.branch
)
1020 system("git branch -D p4");
1021 # create it /after/ importing, when master exists
1022 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
1023 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1025 # TODO: should always look at previous commits,
1026 # merge with previous imports, if possible.
1029 self
.createOrUpdateBranchesFromOrigin()
1030 self
.listExistingP4GitBranches()
1032 if len(self
.p4BranchesInGit
) > 1:
1034 print "Importing from/into multiple branches"
1035 self
.detectBranches
= True
1038 print "branches: %s" % self
.p4BranchesInGit
1041 for branch
in self
.p4BranchesInGit
:
1042 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1044 settings
= extractSettingsGitLog(logMsg
)
1046 self
.readOptions(settings
)
1047 if (settings
.has_key('depot-paths')
1048 and settings
.has_key ('change')):
1049 change
= int(settings
['change']) + 1
1050 p4Change
= max(p4Change
, change
)
1052 depotPaths
= sorted(settings
['depot-paths'])
1053 if self
.previousDepotPaths
== []:
1054 self
.previousDepotPaths
= depotPaths
1057 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1058 for i
in range(0, max(len(cur
), len(prev
))):
1059 if cur
[i
] <> prev
[i
]:
1062 paths
.append (cur
[:i
])
1064 self
.previousDepotPaths
= paths
1067 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1068 self
.changeRange
= "@%s,#head" % p4Change
1069 self
.initialParent
= parseRevision(self
.branch
)
1070 if not self
.silent
and not self
.detectBranches
:
1071 print "Performing incremental import into %s git branch" % self
.branch
1073 if not self
.branch
.startswith("refs/"):
1074 self
.branch
= "refs/heads/" + self
.branch
1076 if len(args
) == 0 and self
.depotPaths
:
1078 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1080 if self
.depotPaths
and self
.depotPaths
!= args
:
1081 print ("previous import used depot path %s and now %s was specified. "
1082 "This doesn't work!" % (' '.join (self
.depotPaths
),
1086 self
.depotPaths
= sorted(args
)
1092 for p
in self
.depotPaths
:
1093 if p
.find("@") != -1:
1094 atIdx
= p
.index("@")
1095 self
.changeRange
= p
[atIdx
:]
1096 if self
.changeRange
== "@all":
1097 self
.changeRange
= ""
1098 elif ',' not in self
.changeRange
:
1099 self
.revision
= self
.changeRange
1100 self
.changeRange
= ""
1102 elif p
.find("#") != -1:
1103 hashIdx
= p
.index("#")
1104 self
.revision
= p
[hashIdx
:]
1106 elif self
.previousDepotPaths
== []:
1107 self
.revision
= "#head"
1109 p
= re
.sub ("\.\.\.$", "", p
)
1110 if not p
.endswith("/"):
1115 self
.depotPaths
= newPaths
1118 self
.loadUserMapFromCache()
1120 if self
.detectLabels
:
1123 if self
.detectBranches
:
1124 self
.getBranchMapping();
1126 print "p4-git branches: %s" % self
.p4BranchesInGit
1127 print "initial parents: %s" % self
.initialParents
1128 for b
in self
.p4BranchesInGit
:
1132 b
= b
[len(self
.projectName
):]
1133 self
.createdBranches
.add(b
)
1135 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1137 importProcess
= subprocess
.Popen(["git", "fast-import"],
1138 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1139 stderr
=subprocess
.PIPE
);
1140 self
.gitOutput
= importProcess
.stdout
1141 self
.gitStream
= importProcess
.stdin
1142 self
.gitError
= importProcess
.stderr
1145 print "Doing initial import of %s from revision %s" % (' '.join(self
.depotPaths
), self
.revision
)
1147 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1148 details
["desc"] = ("Initial import of %s from the state at revision %s"
1149 % (' '.join(self
.depotPaths
), self
.revision
))
1150 details
["change"] = self
.revision
1154 for info
in p4CmdList("files "
1155 + ' '.join(["%s...%s"
1156 % (p
, self
.revision
)
1157 for p
in self
.depotPaths
])):
1159 if info
['code'] == 'error':
1160 sys
.stderr
.write("p4 returned an error: %s\n"
1165 change
= int(info
["change"])
1166 if change
> newestRevision
:
1167 newestRevision
= change
1169 if info
["action"] == "delete":
1170 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1171 #fileCnt = fileCnt + 1
1174 for prop
in ["depotFile", "rev", "action", "type" ]:
1175 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1177 fileCnt
= fileCnt
+ 1
1179 details
["change"] = newestRevision
1180 self
.updateOptionDict(details
)
1182 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1184 print "IO error with git fast-import. Is your git version recent enough?"
1185 print self
.gitError
.read()
1190 if len(self
.changesFile
) > 0:
1191 output
= open(self
.changesFile
).readlines()
1194 changeSet
.add(int(line
))
1196 for change
in changeSet
:
1197 changes
.append(change
)
1202 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1204 assert self
.depotPaths
1205 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1206 for p
in self
.depotPaths
]))
1209 changeNum
= line
.split(" ")[1]
1210 changes
.append(changeNum
)
1214 if len(self
.maxChanges
) > 0:
1215 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1217 if len(changes
) == 0:
1219 print "No changes to import!"
1222 self
.updatedBranches
= set()
1225 for change
in changes
:
1226 description
= p4Cmd("describe %s" % change
)
1227 self
.updateOptionDict(description
)
1230 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1235 if self
.detectBranches
:
1236 branches
= self
.splitFilesIntoBranches(description
)
1237 for branch
in branches
.keys():
1239 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1243 filesForCommit
= branches
[branch
]
1246 print "branch is %s" % branch
1248 self
.updatedBranches
.add(branch
)
1250 if branch
not in self
.createdBranches
:
1251 self
.createdBranches
.add(branch
)
1252 parent
= self
.knownBranches
[branch
]
1253 if parent
== branch
:
1256 print "parent determined through known branches: %s" % parent
1258 # main branch? use master
1259 if branch
== "main":
1264 branch
= self
.projectName
+ branch
1266 if parent
== "main":
1268 elif len(parent
) > 0:
1270 parent
= self
.projectName
+ parent
1272 branch
= self
.refPrefix
+ branch
1274 parent
= self
.refPrefix
+ parent
1277 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1279 if len(parent
) == 0 and branch
in self
.initialParents
:
1280 parent
= self
.initialParents
[branch
]
1281 del self
.initialParents
[branch
]
1283 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1285 files
= self
.extractFilesFromCommit(description
)
1286 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1288 self
.initialParent
= ""
1290 print self
.gitError
.read()
1295 if len(self
.updatedBranches
) > 0:
1296 sys
.stdout
.write("Updated branches: ")
1297 for b
in self
.updatedBranches
:
1298 sys
.stdout
.write("%s " % b
)
1299 sys
.stdout
.write("\n")
1302 self
.gitStream
.close()
1303 if importProcess
.wait() != 0:
1304 die("fast-import failed: %s" % self
.gitError
.read())
1305 self
.gitOutput
.close()
1306 self
.gitError
.close()
1310 class P4Rebase(Command
):
1312 Command
.__init
__(self
)
1314 self
.description
= ("Fetches the latest revision from perforce and "
1315 + "rebases the current work (branch) against it")
1317 def run(self
, args
):
1320 print "Rebasing the current branch"
1321 oldHead
= read_pipe("git rev-parse HEAD").strip()
1322 system("git rebase p4")
1323 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1326 class P4Clone(P4Sync
):
1328 P4Sync
.__init
__(self
)
1329 self
.description
= "Creates a new git repository and imports from Perforce into it"
1330 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1331 self
.options
.append(
1332 optparse
.make_option("--destination", dest
="cloneDestination",
1333 action
='store', default
=None,
1334 help="where to leave result of the clone"))
1335 self
.cloneDestination
= None
1336 self
.needsGit
= False
1338 def defaultDestination(self
, args
):
1339 ## TODO: use common prefix of args?
1341 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1342 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1343 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1344 depotDir
= re
.sub(r
"/$", "", depotDir
)
1345 return os
.path
.split(depotDir
)[1]
1347 def run(self
, args
):
1351 if self
.keepRepoPath
and not self
.cloneDestination
:
1352 sys
.stderr
.write("Must specify destination for --keep-path\n")
1356 for p
in depotPaths
:
1357 if not p
.startswith("//"):
1360 if not self
.cloneDestination
:
1361 self
.cloneDestination
= self
.defaultDestination()
1363 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1364 os
.makedirs(self
.cloneDestination
)
1365 os
.chdir(self
.cloneDestination
)
1367 self
.gitdir
= os
.getcwd() + "/.git"
1368 if not P4Sync
.run(self
, depotPaths
):
1370 if self
.branch
!= "master":
1371 if gitBranchExists("refs/remotes/p4/master"):
1372 system("git branch master refs/remotes/p4/master")
1373 system("git checkout -f")
1375 print "Could not detect main branch. No checkout/master branch created."
1379 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1381 optparse
.IndentedHelpFormatter
.__init
__(self
)
1383 def format_description(self
, description
):
1385 return description
+ "\n"
1389 def printUsage(commands
):
1390 print "usage: %s <command> [options]" % sys
.argv
[0]
1392 print "valid commands: %s" % ", ".join(commands
)
1394 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1399 "submit" : P4Submit
,
1401 "rebase" : P4Rebase
,
1403 "rollback" : P4RollBack
1408 if len(sys
.argv
[1:]) == 0:
1409 printUsage(commands
.keys())
1413 cmdName
= sys
.argv
[1]
1415 klass
= commands
[cmdName
]
1418 print "unknown command %s" % cmdName
1420 printUsage(commands
.keys())
1423 options
= cmd
.options
1424 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1428 if len(options
) > 0:
1429 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1431 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1433 description
= cmd
.description
,
1434 formatter
= HelpFormatter())
1436 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1438 verbose
= cmd
.verbose
1440 if cmd
.gitdir
== None:
1441 cmd
.gitdir
= os
.path
.abspath(".git")
1442 if not isValidGitDir(cmd
.gitdir
):
1443 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1444 if os
.path
.exists(cmd
.gitdir
):
1445 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1449 if not isValidGitDir(cmd
.gitdir
):
1450 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1451 cmd
.gitdir
+= "/.git"
1453 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1455 os
.environ
["GIT_DIR"] = cmd
.gitdir
1457 if not cmd
.run(args
):
1461 if __name__
== '__main__':