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
19 def write_pipe(c
, str):
21 sys
.stderr
.write('writing pipe: %s\n' % c
)
23 pipe
= os
.popen(c
, 'w')
26 sys
.stderr
.write('Command failed: %s' % c
)
31 def read_pipe(c
, ignore_error
=False):
33 sys
.stderr
.write('reading pipe: %s\n' % c
)
35 pipe
= os
.popen(c
, 'rb')
37 if pipe
.close() and not ignore_error
:
38 sys
.stderr
.write('Command failed: %s\n' % c
)
44 def read_pipe_lines(c
):
46 sys
.stderr
.write('reading pipe: %s\n' % c
)
47 ## todo: check return status
48 pipe
= os
.popen(c
, 'rb')
49 val
= pipe
.readlines()
51 sys
.stderr
.write('Command failed: %s\n' % c
)
58 sys
.stderr
.write("executing %s\n" % cmd
)
59 if os
.system(cmd
) != 0:
60 die("command failed: %s" % cmd
)
63 cmd
= "p4 -G %s" % cmd
65 sys
.stderr
.write("Opening pipe: %s\n" % cmd
)
66 pipe
= os
.popen(cmd
, "rb")
71 entry
= marshal
.load(pipe
)
75 exitCode
= pipe
.close()
78 entry
["p4ExitCode"] = exitCode
90 def p4Where(depotPath
):
91 if not depotPath
.endswith("/"):
93 output
= p4Cmd("where %s..." % depotPath
)
94 if output
["code"] == "error":
98 clientPath
= output
.get("path")
99 elif "data" in output
:
100 data
= output
.get("data")
101 lastSpace
= data
.rfind(" ")
102 clientPath
= data
[lastSpace
+ 1:]
104 if clientPath
.endswith("..."):
105 clientPath
= clientPath
[:-3]
109 sys
.stderr
.write(msg
+ "\n")
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"),
178 self
.description
= "A tool to debug the output of p4 -G."
179 self
.needsGit
= False
182 for output
in p4CmdList(" ".join(args
)):
186 class P4RollBack(Command
):
188 Command
.__init
__(self
)
190 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
191 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
193 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
195 self
.rollbackLocalBranches
= False
200 maxChange
= int(args
[0])
202 if "p4ExitCode" in p4Cmd("changes -m 1"):
203 die("Problems executing p4");
205 if self
.rollbackLocalBranches
:
206 refPrefix
= "refs/heads/"
207 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
209 refPrefix
= "refs/remotes/"
210 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
213 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
215 ref
= refPrefix
+ line
216 log
= extractLogMessageFromGitCommit(ref
)
217 settings
= extractSettingsGitLog(log
)
219 depotPaths
= settings
['depot-paths']
220 change
= settings
['change']
224 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
225 for p
in depotPaths
]))) == 0:
226 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
227 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
230 while change
and int(change
) > maxChange
:
233 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
234 system("git update-ref %s \"%s^\"" % (ref
, ref
))
235 log
= extractLogMessageFromGitCommit(ref
)
236 settings
= extractSettingsGitLog(log
)
239 depotPaths
= settings
['depot-paths']
240 change
= settings
['change']
243 print "%s rewound to %s" % (ref
, change
)
247 class P4Submit(Command
):
249 Command
.__init
__(self
)
251 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
252 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
253 optparse
.make_option("--origin", dest
="origin"),
254 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
255 optparse
.make_option("--log-substitutions", dest
="substFile"),
256 optparse
.make_option("--dry-run", action
="store_true"),
257 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
258 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
260 self
.description
= "Submit changes from git to the perforce depot."
261 self
.usage
+= " [name of git branch to submit into perforce depot]"
262 self
.firstTime
= True
264 self
.interactive
= True
267 self
.firstTime
= True
269 self
.directSubmit
= False
270 self
.trustMeLikeAFool
= False
272 self
.logSubstitutions
= {}
273 self
.logSubstitutions
["<enter description here>"] = "%log%"
274 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
277 if len(p4CmdList("opened ...")) > 0:
278 die("You have files opened with perforce! Close them before starting the sync.")
281 if len(self
.config
) > 0 and not self
.reset
:
282 die("Cannot start sync. Previous sync config found at %s\n"
283 "If you want to start submitting again from scratch "
284 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
287 if self
.directSubmit
:
290 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
291 commits
.append(line
.strip())
294 self
.config
["commits"] = commits
296 def prepareLogMessage(self
, template
, message
):
299 for line
in template
.split("\n"):
300 if line
.startswith("#"):
301 result
+= line
+ "\n"
305 for key
in self
.logSubstitutions
.keys():
306 if line
.find(key
) != -1:
307 value
= self
.logSubstitutions
[key
]
308 value
= value
.replace("%log%", message
)
309 if value
!= "@remove@":
310 result
+= line
.replace(key
, value
) + "\n"
315 result
+= line
+ "\n"
319 def applyCommit(self
, id):
320 if self
.directSubmit
:
321 print "Applying local change in working directory/index"
322 diff
= self
.diffStatus
324 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
325 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
327 filesToDelete
= set()
331 path
= line
[1:].strip()
333 system("p4 edit \"%s\"" % path
)
334 editedFiles
.add(path
)
335 elif modifier
== "A":
337 if path
in filesToDelete
:
338 filesToDelete
.remove(path
)
339 elif modifier
== "D":
340 filesToDelete
.add(path
)
341 if path
in filesToAdd
:
342 filesToAdd
.remove(path
)
344 die("unknown modifier %s for %s" % (modifier
, path
))
346 if self
.directSubmit
:
347 diffcmd
= "cat \"%s\"" % self
.diffFile
349 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
350 patchcmd
= diffcmd
+ " | git apply "
351 tryPatchCmd
= patchcmd
+ "--check -"
352 applyPatchCmd
= patchcmd
+ "--check --apply -"
354 if os
.system(tryPatchCmd
) != 0:
355 print "Unfortunately applying the change failed!"
356 print "What do you want to do?"
358 while response
!= "s" and response
!= "a" and response
!= "w":
359 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
360 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
362 print "Skipping! Good luck with the next patches..."
364 elif response
== "a":
365 os
.system(applyPatchCmd
)
366 if len(filesToAdd
) > 0:
367 print "You may also want to call p4 add on the following files:"
368 print " ".join(filesToAdd
)
369 if len(filesToDelete
):
370 print "The following files should be scheduled for deletion with p4 delete:"
371 print " ".join(filesToDelete
)
372 die("Please resolve and submit the conflict manually and "
373 + "continue afterwards with git-p4 submit --continue")
374 elif response
== "w":
375 system(diffcmd
+ " > patch.txt")
376 print "Patch saved to patch.txt in %s !" % self
.clientPath
377 die("Please resolve and submit the conflict manually and "
378 "continue afterwards with git-p4 submit --continue")
380 system(applyPatchCmd
)
383 system("p4 add %s" % f
)
384 for f
in filesToDelete
:
385 system("p4 revert %s" % f
)
386 system("p4 delete %s" % f
)
389 if not self
.directSubmit
:
390 logMessage
= extractLogMessageFromGitCommit(id)
391 logMessage
= logMessage
.replace("\n", "\n\t")
392 logMessage
= logMessage
.strip()
394 template
= read_pipe("p4 change -o")
397 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
398 diff
= read_pipe("p4 diff -du ...")
400 for newFile
in filesToAdd
:
401 diff
+= "==== new file ====\n"
402 diff
+= "--- /dev/null\n"
403 diff
+= "+++ %s\n" % newFile
404 f
= open(newFile
, "r")
405 for line
in f
.readlines():
409 separatorLine
= "######## everything below this line is just the diff #######"
410 if platform
.system() == "Windows":
411 separatorLine
+= "\r"
412 separatorLine
+= "\n"
415 if self
.trustMeLikeAFool
:
418 firstIteration
= True
419 while response
== "e":
420 if not firstIteration
:
421 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
422 firstIteration
= False
424 [handle
, fileName
] = tempfile
.mkstemp()
425 tmpFile
= os
.fdopen(handle
, "w+")
426 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
429 if platform
.system() == "Windows":
430 defaultEditor
= "notepad"
431 editor
= os
.environ
.get("EDITOR", defaultEditor
);
432 system(editor
+ " " + fileName
)
433 tmpFile
= open(fileName
, "rb")
434 message
= tmpFile
.read()
437 submitTemplate
= message
[:message
.index(separatorLine
)]
439 if response
== "y" or response
== "yes":
442 raw_input("Press return to continue...")
444 if self
.directSubmit
:
445 print "Submitting to git first"
446 os
.chdir(self
.oldWorkingDirectory
)
447 write_pipe("git commit -a -F -", submitTemplate
)
448 os
.chdir(self
.clientPath
)
450 write_pipe("p4 submit -i", submitTemplate
)
451 elif response
== "s":
452 for f
in editedFiles
:
453 system("p4 revert \"%s\"" % f
);
455 system("p4 revert \"%s\"" % f
);
457 for f
in filesToDelete
:
458 system("p4 delete \"%s\"" % f
);
461 print "Not submitting!"
462 self
.interactive
= False
464 fileName
= "submit.txt"
465 file = open(fileName
, "w+")
466 file.write(self
.prepareLogMessage(template
, logMessage
))
468 print ("Perforce submit template written as %s. "
469 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
470 % (fileName
, fileName
))
473 # make gitdir absolute so we can cd out into the perforce checkout
474 os
.environ
["GIT_DIR"] = gitdir
477 self
.master
= currentGitBranch()
478 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
479 die("Detecting current git branch failed!")
481 self
.master
= args
[0]
487 if gitBranchExists("p4"):
488 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
489 if len(depotPath
) == 0 and gitBranchExists("origin"):
490 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
491 depotPaths
= settings
['depot-paths']
493 if len(depotPath
) == 0:
494 print "Internal error: cannot locate perforce depot path from existing branches"
497 self
.clientPath
= p4Where(depotPath
)
499 if len(self
.clientPath
) == 0:
500 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
503 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
504 self
.oldWorkingDirectory
= os
.getcwd()
506 if self
.directSubmit
:
507 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
508 if len(self
.diffStatus
) == 0:
509 print "No changes in working directory to submit."
511 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
512 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
513 f
= open(self
.diffFile
, "wb")
517 os
.chdir(self
.clientPath
)
518 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
519 if response
== "y" or response
== "yes":
520 system("p4 sync ...")
522 if len(self
.origin
) == 0:
523 if gitBranchExists("p4"):
526 self
.origin
= "origin"
529 self
.firstTime
= True
531 if len(self
.substFile
) > 0:
532 for line
in open(self
.substFile
, "r").readlines():
533 tokens
= line
.strip().split("=")
534 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
537 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
538 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
543 commits
= self
.config
.get("commits", [])
545 while len(commits
) > 0:
546 self
.firstTime
= False
548 commits
= commits
[1:]
549 self
.config
["commits"] = commits
550 self
.applyCommit(commit
)
551 if not self
.interactive
:
556 if self
.directSubmit
:
557 os
.remove(self
.diffFile
)
559 if len(commits
) == 0:
561 print "No changes found to apply between %s and current HEAD" % self
.origin
563 print "All changes applied!"
564 os
.chdir(self
.oldWorkingDirectory
)
565 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
566 if response
== "y" or response
== "yes":
569 os
.remove(self
.configFile
)
573 class P4Sync(Command
):
575 Command
.__init
__(self
)
577 optparse
.make_option("--branch", dest
="branch"),
578 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
579 optparse
.make_option("--changesfile", dest
="changesFile"),
580 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
581 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
582 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
583 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
584 optparse
.make_option("--max-changes", dest
="maxChanges"),
585 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true')
587 self
.description
= """Imports from Perforce into a git repository.\n
589 //depot/my/project/ -- to import the current head
590 //depot/my/project/@all -- to import everything
591 //depot/my/project/@1,6 -- to import only from revision 1 to 6
593 (a ... is not needed in the path p4 specification, it's added implicitly)"""
595 self
.usage
+= " //depot/path[@revRange]"
597 self
.createdBranches
= Set()
598 self
.committedChanges
= Set()
600 self
.detectBranches
= False
601 self
.detectLabels
= False
602 self
.changesFile
= ""
603 self
.syncWithOrigin
= True
605 self
.importIntoRemotes
= True
607 self
.isWindows
= (platform
.system() == "Windows")
608 self
.keepRepoPath
= False
609 self
.depotPaths
= None
611 if gitConfig("git-p4.syncFromOrigin") == "false":
612 self
.syncWithOrigin
= False
614 def extractFilesFromCommit(self
, commit
):
617 while commit
.has_key("depotFile%s" % fnum
):
618 path
= commit
["depotFile%s" % fnum
]
620 found
= [p
for p
in self
.depotPaths
621 if path
.startswith (p
)]
628 file["rev"] = commit
["rev%s" % fnum
]
629 file["action"] = commit
["action%s" % fnum
]
630 file["type"] = commit
["type%s" % fnum
]
635 def stripRepoPath(self
, path
, prefixes
):
636 if self
.keepRepoPath
:
637 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
640 if path
.startswith(p
):
645 def splitFilesIntoBranches(self
, commit
):
648 while commit
.has_key("depotFile%s" % fnum
):
649 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
]
663 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
665 for branch
in self
.knownBranches
.keys():
667 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
668 if relPath
.startswith(branch
+ "/"):
669 if branch
not in branches
:
670 branches
[branch
] = []
671 branches
[branch
].append(file)
675 ## Should move this out, doesn't use SELF.
676 def readP4Files(self
, files
):
677 specs
= [(f
['path'] + "#" + f
['rev'], f
) for f
in files
678 if f
['action'] != 'delete']
680 data
= read_pipe('p4 print %s' % ' '.join(['"%s"' % path
681 for (path
, info
) in specs
]))
684 for j
in range(0, len(specs
)):
685 (pathrev
, info
) = specs
[j
]
687 assert idx
< len(data
)
688 if data
[idx
:idx
+ len(pathrev
)] != pathrev
:
690 idx
= data
.find ('\n', idx
)
698 (next_pathrev
, next_info
) = specs
[j
+1]
699 end
= data
.find(next_pathrev
, start
)
703 print 'PATHREV', pathrev
, specs
[j
]
704 print 'nextpathrev', next_pathrev
, specs
[j
+1]
705 print 'start', start
, len(data
)
712 info
['data'] = data
[start
:end
]
714 assert idx
== len(data
)
716 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
717 epoch
= details
["time"]
718 author
= details
["user"]
721 print "commit into %s" % branch
723 # start with reading files; if that fails, we should not
727 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
730 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
732 self
.readP4Files(files
)
737 self
.gitStream
.write("commit %s\n" % branch
)
738 # gitStream.write("mark :%s\n" % details["change"])
739 self
.committedChanges
.add(int(details
["change"]))
741 if author
not in self
.users
:
742 self
.getUserMapFromPerforceServer()
743 if author
in self
.users
:
744 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
746 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
748 self
.gitStream
.write("committer %s\n" % committer
)
750 self
.gitStream
.write("data <<EOT\n")
751 self
.gitStream
.write(details
["desc"])
752 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
754 % (','.join (branchPrefixes
), details
["change"],
757 self
.gitStream
.write("EOT\n\n")
761 print "parent %s" % parent
762 self
.gitStream
.write("from %s\n" % parent
)
765 if file["type"] == "apple":
766 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
769 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
770 if file["action"] == "delete":
771 self
.gitStream
.write("D %s\n" % relPath
)
774 if file["type"].startswith("x"):
779 if self
.isWindows
and file["type"].endswith("text"):
780 data
= data
.replace("\r\n", "\n")
782 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
783 self
.gitStream
.write("data %s\n" % len(data
))
784 self
.gitStream
.write(data
)
785 self
.gitStream
.write("\n")
787 self
.gitStream
.write("\n")
789 change
= int(details
["change"])
791 if self
.labels
.has_key(change
):
792 label
= self
.labels
[change
]
793 labelDetails
= label
[0]
794 labelRevisions
= label
[1]
796 print "Change %s is labelled %s" % (change
, labelDetails
)
798 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
799 for p
in branchPrefixes
]))
801 if len(files
) == len(labelRevisions
):
805 if info
["action"] == "delete":
807 cleanedFiles
[info
["depotFile"]] = info
["rev"]
809 if cleanedFiles
== labelRevisions
:
810 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
811 self
.gitStream
.write("from %s\n" % branch
)
813 owner
= labelDetails
["Owner"]
815 if author
in self
.users
:
816 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
818 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
819 self
.gitStream
.write("tagger %s\n" % tagger
)
820 self
.gitStream
.write("data <<EOT\n")
821 self
.gitStream
.write(labelDetails
["Description"])
822 self
.gitStream
.write("EOT\n\n")
826 print ("Tag %s does not match with change %s: files do not match."
827 % (labelDetails
["label"], change
))
831 print ("Tag %s does not match with change %s: file count is different."
832 % (labelDetails
["label"], change
))
834 def getUserCacheFilename(self
):
835 return os
.environ
["HOME"] + "/.gitp4-usercache.txt"
837 def getUserMapFromPerforceServer(self
):
838 if self
.userMapFromPerforceServer
:
842 for output
in p4CmdList("users"):
843 if not output
.has_key("User"):
845 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
849 for (key
, val
) in self
.users
.items():
850 s
+= "%s\t%s\n" % (key
, val
)
852 open(self
.getUserCacheFilename(), "wb").write(s
)
853 self
.userMapFromPerforceServer
= True
855 def loadUserMapFromCache(self
):
857 self
.userMapFromPerforceServer
= False
859 cache
= open(self
.getUserCacheFilename(), "rb")
860 lines
= cache
.readlines()
863 entry
= line
.strip().split("\t")
864 self
.users
[entry
[0]] = entry
[1]
866 self
.getUserMapFromPerforceServer()
871 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
872 if len(l
) > 0 and not self
.silent
:
873 print "Finding files belonging to labels in %s" % `self
.depotPath`
876 label
= output
["label"]
880 print "Querying files for label %s" % label
881 for file in p4CmdList("files "
882 + ' '.join (["%s...@%s" % (p
, label
)
883 for p
in self
.depotPaths
])):
884 revisions
[file["depotFile"]] = file["rev"]
885 change
= int(file["change"])
886 if change
> newestChange
:
887 newestChange
= change
889 self
.labels
[newestChange
] = [output
, revisions
]
892 print "Label changes: %s" % self
.labels
.keys()
894 def getBranchMapping(self
):
896 ## FIXME - what's a P4 projectName ?
897 self
.projectName
= self
.depotPath
[self
.depotPath
.strip().rfind("/") + 1:]
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]
910 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
911 source
= source
[len(self
.depotPath
):-4]
912 destination
= destination
[len(self
.depotPath
):-4]
913 if destination
not in self
.knownBranches
:
914 self
.knownBranches
[destination
] = source
915 if source
not in self
.knownBranches
:
916 self
.knownBranches
[source
] = source
918 def listExistingP4GitBranches(self
):
919 self
.p4BranchesInGit
= []
921 cmdline
= "git rev-parse --symbolic "
922 if self
.importIntoRemotes
:
923 cmdline
+= " --remotes"
925 cmdline
+= " --branches"
927 for line
in read_pipe_lines(cmdline
):
929 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD"):
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)" % self
.refPrefix
943 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
945 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
948 headName
= line
[len("origin/"):]
949 remoteHead
= self
.refPrefix
+ headName
950 originHead
= "origin/" + headName
952 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
953 if (not original
.has_key('depot-paths')
954 or not original
.has_key('change')):
958 if not gitBranchExists(remoteHead
):
960 print "creating %s" % remoteHead
963 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
964 if settings
.has_key('change') > 0:
965 if settings
['depot-paths'] == original
['depot-paths']:
966 originP4Change
= int(original
['change'])
967 p4Change
= int(settings
['change'])
968 if originP4Change
> p4Change
:
969 print ("%s (%s) is newer than %s (%s). "
970 "Updating p4 branch from origin."
971 % (originHead
, originP4Change
,
972 remoteHead
, p4Change
))
975 print ("Ignoring: %s was imported from %s while "
976 "%s was imported from %s"
977 % (originHead
, ','.join(original
['depot-paths']),
978 remoteHead
, ','.join(settings
['depot-paths'])))
981 system("git update-ref %s %s" % (remoteHead
, originHead
))
983 def updateOptionDict(self
, d
):
985 if self
.keepRepoPath
:
986 option_keys
['keepRepoPath'] = 1
988 d
["options"] = ' '.join(sorted(option_keys
.keys()))
990 def readOptions(self
, d
):
991 self
.keepRepoPath
= (d
.has_key('options')
992 and ('keepRepoPath' in d
['options']))
996 self
.changeRange
= ""
997 self
.initialParent
= ""
998 self
.previousDepotPaths
= []
1000 # map from branch depot path to parent branch
1001 self
.knownBranches
= {}
1002 self
.initialParents
= {}
1003 self
.hasOrigin
= gitBranchExists("origin")
1005 if self
.importIntoRemotes
:
1006 self
.refPrefix
= "refs/remotes/p4/"
1008 self
.refPrefix
= "refs/heads/"
1010 if self
.syncWithOrigin
and self
.hasOrigin
:
1012 print "Syncing with origin first by calling git fetch origin"
1013 system("git fetch origin")
1015 if len(self
.branch
) == 0:
1016 self
.branch
= self
.refPrefix
+ "master"
1017 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1018 system("git update-ref %s refs/heads/p4" % self
.branch
)
1019 system("git branch -D p4");
1020 # create it /after/ importing, when master exists
1021 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
1022 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1024 # TODO: should always look at previous commits,
1025 # merge with previous imports, if possible.
1028 self
.createOrUpdateBranchesFromOrigin()
1029 self
.listExistingP4GitBranches()
1031 if len(self
.p4BranchesInGit
) > 1:
1033 print "Importing from/into multiple branches"
1034 self
.detectBranches
= True
1037 print "branches: %s" % self
.p4BranchesInGit
1040 for branch
in self
.p4BranchesInGit
:
1041 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1043 settings
= extractSettingsGitLog(logMsg
)
1045 self
.readOptions(settings
)
1046 if (settings
.has_key('depot-paths')
1047 and settings
.has_key ('change')):
1048 change
= int(settings
['change']) + 1
1049 p4Change
= max(p4Change
, change
)
1051 depotPaths
= sorted(settings
['depot-paths'])
1052 if self
.previousDepotPaths
== []:
1053 self
.previousDepotPaths
= depotPaths
1056 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1057 for i
in range(0, max(len(cur
), len(prev
))):
1058 if cur
[i
] <> prev
[i
]:
1061 paths
.append (cur
[:i
])
1063 self
.previousDepotPaths
= paths
1066 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1067 self
.changeRange
= "@%s,#head" % p4Change
1068 self
.initialParent
= parseRevision(self
.branch
)
1069 if not self
.silent
and not self
.detectBranches
:
1070 print "Performing incremental import into %s git branch" % self
.branch
1072 if not self
.branch
.startswith("refs/"):
1073 self
.branch
= "refs/heads/" + self
.branch
1075 if len(args
) == 0 and self
.depotPaths
:
1077 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1079 if self
.depotPaths
and self
.depotPaths
!= args
:
1080 print ("previous import used depot path %s and now %s was specified. "
1081 "This doesn't work!" % (' '.join (self
.depotPaths
),
1085 self
.depotPaths
= sorted(args
)
1091 for p
in self
.depotPaths
:
1092 if p
.find("@") != -1:
1093 atIdx
= p
.index("@")
1094 self
.changeRange
= p
[atIdx
:]
1095 if self
.changeRange
== "@all":
1096 self
.changeRange
= ""
1097 elif ',' not in self
.changeRange
:
1098 self
.revision
= self
.changeRange
1099 self
.changeRange
= ""
1101 elif p
.find("#") != -1:
1102 hashIdx
= p
.index("#")
1103 self
.revision
= p
[hashIdx
:]
1105 elif self
.previousDepotPaths
== []:
1106 self
.revision
= "#head"
1108 p
= re
.sub ("\.\.\.$", "", p
)
1109 if not p
.endswith("/"):
1114 self
.depotPaths
= newPaths
1117 self
.loadUserMapFromCache()
1119 if self
.detectLabels
:
1122 if self
.detectBranches
:
1123 self
.getBranchMapping();
1125 print "p4-git branches: %s" % self
.p4BranchesInGit
1126 print "initial parents: %s" % self
.initialParents
1127 for b
in self
.p4BranchesInGit
:
1131 b
= b
[len(self
.projectName
):]
1132 self
.createdBranches
.add(b
)
1134 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1136 importProcess
= subprocess
.Popen(["git", "fast-import"],
1137 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1138 stderr
=subprocess
.PIPE
);
1139 self
.gitOutput
= importProcess
.stdout
1140 self
.gitStream
= importProcess
.stdin
1141 self
.gitError
= importProcess
.stderr
1143 if len(self
.revision
) > 0:
1144 print "Doing initial import of %s from revision %s" % (' '.join(self
.depotPaths
), self
.revision
)
1146 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1147 details
["desc"] = ("Initial import of %s from the state at revision %s"
1148 % (' '.join(self
.depotPaths
), self
.revision
))
1149 details
["change"] = self
.revision
1153 for info
in p4CmdList("files "
1154 + ' '.join(["%s...%s"
1155 % (p
, self
.revision
)
1156 for p
in self
.depotPaths
])):
1158 if not info
.has_key("change"):
1160 change
= int(info
["change"])
1161 if change
> newestRevision
:
1162 newestRevision
= change
1164 if info
["action"] == "delete":
1165 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1166 #fileCnt = fileCnt + 1
1169 for prop
in ["depotFile", "rev", "action", "type" ]:
1170 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1172 fileCnt
= fileCnt
+ 1
1174 details
["change"] = newestRevision
1175 self
.updateOptionDict(details
)
1177 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1179 print "IO error with git fast-import. Is your git version recent enough?"
1180 print self
.gitError
.read()
1185 if len(self
.changesFile
) > 0:
1186 output
= open(self
.changesFile
).readlines()
1189 changeSet
.add(int(line
))
1191 for change
in changeSet
:
1192 changes
.append(change
)
1197 print "Getting p4 changes for %s...%s" % (`self
.depotPaths`
,
1199 assert self
.depotPaths
1200 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1201 for p
in self
.depotPaths
]))
1204 changeNum
= line
.split(" ")[1]
1205 changes
.append(changeNum
)
1209 if len(self
.maxChanges
) > 0:
1210 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1212 if len(changes
) == 0:
1214 print "No changes to import!"
1217 self
.updatedBranches
= set()
1220 for change
in changes
:
1221 description
= p4Cmd("describe %s" % change
)
1222 self
.updateOptionDict(description
)
1225 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1230 if self
.detectBranches
:
1231 branches
= self
.splitFilesIntoBranches(description
)
1232 for branch
in branches
.keys():
1234 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1238 filesForCommit
= branches
[branch
]
1241 print "branch is %s" % branch
1243 self
.updatedBranches
.add(branch
)
1245 if branch
not in self
.createdBranches
:
1246 self
.createdBranches
.add(branch
)
1247 parent
= self
.knownBranches
[branch
]
1248 if parent
== branch
:
1251 print "parent determined through known branches: %s" % parent
1253 # main branch? use master
1254 if branch
== "main":
1259 branch
= self
.projectName
+ branch
1261 if parent
== "main":
1263 elif len(parent
) > 0:
1265 parent
= self
.projectName
+ parent
1267 branch
= self
.refPrefix
+ branch
1269 parent
= self
.refPrefix
+ parent
1272 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1274 if len(parent
) == 0 and branch
in self
.initialParents
:
1275 parent
= self
.initialParents
[branch
]
1276 del self
.initialParents
[branch
]
1278 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1280 files
= self
.extractFilesFromCommit(description
)
1281 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1283 self
.initialParent
= ""
1285 print self
.gitError
.read()
1290 if len(self
.updatedBranches
) > 0:
1291 sys
.stdout
.write("Updated branches: ")
1292 for b
in self
.updatedBranches
:
1293 sys
.stdout
.write("%s " % b
)
1294 sys
.stdout
.write("\n")
1297 self
.gitStream
.close()
1298 if importProcess
.wait() != 0:
1299 die("fast-import failed: %s" % self
.gitError
.read())
1300 self
.gitOutput
.close()
1301 self
.gitError
.close()
1305 class P4Rebase(Command
):
1307 Command
.__init
__(self
)
1309 self
.description
= ("Fetches the latest revision from perforce and "
1310 + "rebases the current work (branch) against it")
1312 def run(self
, args
):
1315 print "Rebasing the current branch"
1316 oldHead
= read_pipe("git rev-parse HEAD").strip()
1317 system("git rebase p4")
1318 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1321 class P4Clone(P4Sync
):
1323 P4Sync
.__init
__(self
)
1324 self
.description
= "Creates a new git repository and imports from Perforce into it"
1325 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1326 self
.options
.append(
1327 optparse
.make_option("--destination", dest
="cloneDestination",
1328 action
='store', default
=None,
1329 help="where to leave result of the clone"))
1330 self
.cloneDestination
= None
1331 self
.needsGit
= False
1333 def defaultDestination(self
, args
):
1334 ## TODO: use common prefix of args?
1336 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1337 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1338 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1339 depotDir
= re
.sub(r
"/$", "", depotDir
)
1340 return os
.path
.split(depotDir
)[1]
1342 def run(self
, args
):
1346 if self
.keepRepoPath
and not self
.cloneDestination
:
1347 sys
.stderr
.write("Must specify destination for --keep-path\n")
1351 for p
in depotPaths
:
1352 if not p
.startswith("//"):
1355 if not self
.cloneDestination
:
1356 self
.cloneDestination
= self
.defaultDestination()
1358 print "Importing from %s into %s" % (`depotPaths`
, self
.cloneDestination
)
1359 os
.makedirs(self
.cloneDestination
)
1360 os
.chdir(self
.cloneDestination
)
1362 self
.gitdir
= os
.getcwd() + "/.git"
1363 if not P4Sync
.run(self
, depotPaths
):
1365 if self
.branch
!= "master":
1366 if gitBranchExists("refs/remotes/p4/master"):
1367 system("git branch master refs/remotes/p4/master")
1368 system("git checkout -f")
1370 print "Could not detect main branch. No checkout/master branch created."
1373 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1375 optparse
.IndentedHelpFormatter
.__init
__(self
)
1377 def format_description(self
, description
):
1379 return description
+ "\n"
1383 def printUsage(commands
):
1384 print "usage: %s <command> [options]" % sys
.argv
[0]
1386 print "valid commands: %s" % ", ".join(commands
)
1388 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1393 "submit" : P4Submit
,
1395 "rebase" : P4Rebase
,
1397 "rollback" : P4RollBack
1402 if len(sys
.argv
[1:]) == 0:
1403 printUsage(commands
.keys())
1407 cmdName
= sys
.argv
[1]
1409 klass
= commands
[cmdName
]
1412 print "unknown command %s" % cmdName
1414 printUsage(commands
.keys())
1417 options
= cmd
.options
1418 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1422 if len(options
) > 0:
1423 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1425 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1427 description
= cmd
.description
,
1428 formatter
= HelpFormatter())
1430 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1432 verbose
= cmd
.verbose
1434 if cmd
.gitdir
== None:
1435 cmd
.gitdir
= os
.path
.abspath(".git")
1436 if not isValidGitDir(cmd
.gitdir
):
1437 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1438 if os
.path
.exists(cmd
.gitdir
):
1439 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1443 if not isValidGitDir(cmd
.gitdir
):
1444 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1445 cmd
.gitdir
+= "/.git"
1447 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1449 os
.environ
["GIT_DIR"] = cmd
.gitdir
1451 if not cmd
.run(args
):
1455 if __name__
== '__main__':