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
17 gitdir
= os
.environ
.get("GIT_DIR", "")
20 def write_pipe(c
, str):
22 sys
.stderr
.write('writing pipe: %s\n' % c
)
24 pipe
= os
.popen(c
, 'w')
27 sys
.stderr
.write('Command failed: %s' % c
)
32 def read_pipe(c
, ignore_error
=False):
34 sys
.stderr
.write('reading pipe: %s\n' % c
)
36 pipe
= os
.popen(c
, 'rb')
38 if pipe
.close() and not ignore_error
:
39 sys
.stderr
.write('Command failed: %s\n' % c
)
45 def read_pipe_lines(c
):
47 sys
.stderr
.write('reading pipe: %s\n' % c
)
48 ## todo: check return status
49 pipe
= os
.popen(c
, 'rb')
50 val
= pipe
.readlines()
52 sys
.stderr
.write('Command failed: %s\n' % c
)
59 sys
.stderr
.write("executing %s\n" % cmd
)
60 if os
.system(cmd
) != 0:
61 die("command failed: %s" % cmd
)
64 cmd
= "p4 -G %s" % cmd
65 pipe
= os
.popen(cmd
, "rb")
70 entry
= marshal
.load(pipe
)
74 exitCode
= pipe
.close()
77 entry
["p4ExitCode"] = exitCode
89 def p4Where(depotPath
):
90 if not depotPath
.endswith("/"):
92 output
= p4Cmd("where %s..." % depotPath
)
93 if output
["code"] == "error":
97 clientPath
= output
.get("path")
98 elif "data" in output
:
99 data
= output
.get("data")
100 lastSpace
= data
.rfind(" ")
101 clientPath
= data
[lastSpace
+ 1:]
103 if clientPath
.endswith("..."):
104 clientPath
= clientPath
[:-3]
108 sys
.stderr
.write(msg
+ "\n")
111 def currentGitBranch():
112 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
114 def isValidGitDir(path
):
115 if (os
.path
.exists(path
+ "/HEAD")
116 and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects")):
120 def parseRevision(ref
):
121 return read_pipe("git rev-parse %s" % ref
).strip()
123 def extractLogMessageFromGitCommit(commit
):
126 ## fixme: title is first line of commit, not 1st paragraph.
128 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
137 def extractSettingsGitLog(log
):
139 for line
in log
.split("\n"):
141 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
145 assignments
= m
.group(1).split (':')
146 for a
in assignments
:
148 key
= vals
[0].strip()
149 val
= ('='.join (vals
[1:])).strip()
150 if val
.endswith ('\"') and val
.startswith('"'):
155 values
['depot-paths'] = values
.get("depot-paths").split(',')
158 def gitBranchExists(branch
):
159 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
160 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
161 return proc
.wait() == 0;
164 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
168 self
.usage
= "usage: %prog [options]"
171 class P4Debug(Command
):
173 Command
.__init
__(self
)
175 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
177 self
.description
= "A tool to debug the output of p4 -G."
178 self
.needsGit
= False
181 for output
in p4CmdList(" ".join(args
)):
185 class P4RollBack(Command
):
187 Command
.__init
__(self
)
189 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
190 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
192 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
194 self
.rollbackLocalBranches
= False
199 maxChange
= int(args
[0])
201 if "p4ExitCode" in p4Cmd("changes -m 1"):
202 die("Problems executing p4");
204 if self
.rollbackLocalBranches
:
205 refPrefix
= "refs/heads/"
206 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
208 refPrefix
= "refs/remotes/"
209 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
212 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
214 ref
= refPrefix
+ line
215 log
= extractLogMessageFromGitCommit(ref
)
216 settings
= extractSettingsGitLog(log
)
218 depotPaths
= settings
['depot-paths']
219 change
= settings
['change']
223 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
224 for p
in depotPaths
]))) == 0:
225 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
226 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
229 while change
and int(change
) > maxChange
:
232 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
233 system("git update-ref %s \"%s^\"" % (ref
, ref
))
234 log
= extractLogMessageFromGitCommit(ref
)
235 settings
= extractSettingsGitLog(log
)
238 depotPaths
= settings
['depot-paths']
239 change
= settings
['change']
242 print "%s rewound to %s" % (ref
, change
)
246 class P4Submit(Command
):
248 Command
.__init
__(self
)
250 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
251 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
252 optparse
.make_option("--origin", dest
="origin"),
253 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
254 optparse
.make_option("--log-substitutions", dest
="substFile"),
255 optparse
.make_option("--dry-run", action
="store_true"),
256 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
257 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
259 self
.description
= "Submit changes from git to the perforce depot."
260 self
.usage
+= " [name of git branch to submit into perforce depot]"
261 self
.firstTime
= True
263 self
.interactive
= True
266 self
.firstTime
= True
268 self
.directSubmit
= False
269 self
.trustMeLikeAFool
= False
271 self
.logSubstitutions
= {}
272 self
.logSubstitutions
["<enter description here>"] = "%log%"
273 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
276 if len(p4CmdList("opened ...")) > 0:
277 die("You have files opened with perforce! Close them before starting the sync.")
280 if len(self
.config
) > 0 and not self
.reset
:
281 die("Cannot start sync. Previous sync config found at %s\n"
282 "If you want to start submitting again from scratch "
283 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
286 if self
.directSubmit
:
289 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
290 commits
.append(line
.strip())
293 self
.config
["commits"] = commits
295 def prepareLogMessage(self
, template
, message
):
298 for line
in template
.split("\n"):
299 if line
.startswith("#"):
300 result
+= line
+ "\n"
304 for key
in self
.logSubstitutions
.keys():
305 if line
.find(key
) != -1:
306 value
= self
.logSubstitutions
[key
]
307 value
= value
.replace("%log%", message
)
308 if value
!= "@remove@":
309 result
+= line
.replace(key
, value
) + "\n"
314 result
+= line
+ "\n"
318 def applyCommit(self
, id):
319 if self
.directSubmit
:
320 print "Applying local change in working directory/index"
321 diff
= self
.diffStatus
323 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
324 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
326 filesToDelete
= set()
330 path
= line
[1:].strip()
332 system("p4 edit \"%s\"" % path
)
333 editedFiles
.add(path
)
334 elif modifier
== "A":
336 if path
in filesToDelete
:
337 filesToDelete
.remove(path
)
338 elif modifier
== "D":
339 filesToDelete
.add(path
)
340 if path
in filesToAdd
:
341 filesToAdd
.remove(path
)
343 die("unknown modifier %s for %s" % (modifier
, path
))
345 if self
.directSubmit
:
346 diffcmd
= "cat \"%s\"" % self
.diffFile
348 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
349 patchcmd
= diffcmd
+ " | git apply "
350 tryPatchCmd
= patchcmd
+ "--check -"
351 applyPatchCmd
= patchcmd
+ "--check --apply -"
353 if os
.system(tryPatchCmd
) != 0:
354 print "Unfortunately applying the change failed!"
355 print "What do you want to do?"
357 while response
!= "s" and response
!= "a" and response
!= "w":
358 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
359 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
361 print "Skipping! Good luck with the next patches..."
363 elif response
== "a":
364 os
.system(applyPatchCmd
)
365 if len(filesToAdd
) > 0:
366 print "You may also want to call p4 add on the following files:"
367 print " ".join(filesToAdd
)
368 if len(filesToDelete
):
369 print "The following files should be scheduled for deletion with p4 delete:"
370 print " ".join(filesToDelete
)
371 die("Please resolve and submit the conflict manually and "
372 + "continue afterwards with git-p4 submit --continue")
373 elif response
== "w":
374 system(diffcmd
+ " > patch.txt")
375 print "Patch saved to patch.txt in %s !" % self
.clientPath
376 die("Please resolve and submit the conflict manually and "
377 "continue afterwards with git-p4 submit --continue")
379 system(applyPatchCmd
)
382 system("p4 add %s" % f
)
383 for f
in filesToDelete
:
384 system("p4 revert %s" % f
)
385 system("p4 delete %s" % f
)
388 if not self
.directSubmit
:
389 logMessage
= extractLogMessageFromGitCommit(id)
390 logMessage
= logMessage
.replace("\n", "\n\t")
391 logMessage
= logMessage
.strip()
393 template
= read_pipe("p4 change -o")
396 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
397 diff
= read_pipe("p4 diff -du ...")
399 for newFile
in filesToAdd
:
400 diff
+= "==== new file ====\n"
401 diff
+= "--- /dev/null\n"
402 diff
+= "+++ %s\n" % newFile
403 f
= open(newFile
, "r")
404 for line
in f
.readlines():
408 separatorLine
= "######## everything below this line is just the diff #######"
409 if platform
.system() == "Windows":
410 separatorLine
+= "\r"
411 separatorLine
+= "\n"
414 if self
.trustMeLikeAFool
:
417 firstIteration
= True
418 while response
== "e":
419 if not firstIteration
:
420 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
421 firstIteration
= False
423 [handle
, fileName
] = tempfile
.mkstemp()
424 tmpFile
= os
.fdopen(handle
, "w+")
425 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
428 if platform
.system() == "Windows":
429 defaultEditor
= "notepad"
430 editor
= os
.environ
.get("EDITOR", defaultEditor
);
431 system(editor
+ " " + fileName
)
432 tmpFile
= open(fileName
, "rb")
433 message
= tmpFile
.read()
436 submitTemplate
= message
[:message
.index(separatorLine
)]
438 if response
== "y" or response
== "yes":
441 raw_input("Press return to continue...")
443 if self
.directSubmit
:
444 print "Submitting to git first"
445 os
.chdir(self
.oldWorkingDirectory
)
446 write_pipe("git commit -a -F -", submitTemplate
)
447 os
.chdir(self
.clientPath
)
449 write_pipe("p4 submit -i", submitTemplate
)
450 elif response
== "s":
451 for f
in editedFiles
:
452 system("p4 revert \"%s\"" % f
);
454 system("p4 revert \"%s\"" % f
);
456 for f
in filesToDelete
:
457 system("p4 delete \"%s\"" % f
);
460 print "Not submitting!"
461 self
.interactive
= False
463 fileName
= "submit.txt"
464 file = open(fileName
, "w+")
465 file.write(self
.prepareLogMessage(template
, logMessage
))
467 print ("Perforce submit template written as %s. "
468 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
469 % (fileName
, fileName
))
473 # make gitdir absolute so we can cd out into the perforce checkout
474 gitdir
= os
.path
.abspath(gitdir
)
475 os
.environ
["GIT_DIR"] = gitdir
478 self
.master
= currentGitBranch()
479 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
480 die("Detecting current git branch failed!")
482 self
.master
= args
[0]
488 if gitBranchExists("p4"):
489 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
490 if len(depotPath
) == 0 and gitBranchExists("origin"):
491 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
492 depotPaths
= settings
['depot-paths']
494 if len(depotPath
) == 0:
495 print "Internal error: cannot locate perforce depot path from existing branches"
498 self
.clientPath
= p4Where(depotPath
)
500 if len(self
.clientPath
) == 0:
501 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
504 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
505 self
.oldWorkingDirectory
= os
.getcwd()
507 if self
.directSubmit
:
508 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
509 if len(self
.diffStatus
) == 0:
510 print "No changes in working directory to submit."
512 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
513 self
.diffFile
= gitdir
+ "/p4-git-diff"
514 f
= open(self
.diffFile
, "wb")
518 os
.chdir(self
.clientPath
)
519 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
520 if response
== "y" or response
== "yes":
521 system("p4 sync ...")
523 if len(self
.origin
) == 0:
524 if gitBranchExists("p4"):
527 self
.origin
= "origin"
530 self
.firstTime
= True
532 if len(self
.substFile
) > 0:
533 for line
in open(self
.substFile
, "r").readlines():
534 tokens
= line
.strip().split("=")
535 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
538 self
.configFile
= gitdir
+ "/p4-git-sync.cfg"
539 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
544 commits
= self
.config
.get("commits", [])
546 while len(commits
) > 0:
547 self
.firstTime
= False
549 commits
= commits
[1:]
550 self
.config
["commits"] = commits
551 self
.applyCommit(commit
)
552 if not self
.interactive
:
557 if self
.directSubmit
:
558 os
.remove(self
.diffFile
)
560 if len(commits
) == 0:
562 print "No changes found to apply between %s and current HEAD" % self
.origin
564 print "All changes applied!"
565 os
.chdir(self
.oldWorkingDirectory
)
566 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
567 if response
== "y" or response
== "yes":
570 os
.remove(self
.configFile
)
574 class P4Sync(Command
):
576 Command
.__init
__(self
)
578 optparse
.make_option("--branch", dest
="branch"),
579 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
580 optparse
.make_option("--changesfile", dest
="changesFile"),
581 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
582 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
583 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
584 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false"),
585 optparse
.make_option("--max-changes", dest
="maxChanges"),
586 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true')
588 self
.description
= """Imports from Perforce into a git repository.\n
590 //depot/my/project/ -- to import the current head
591 //depot/my/project/@all -- to import everything
592 //depot/my/project/@1,6 -- to import only from revision 1 to 6
594 (a ... is not needed in the path p4 specification, it's added implicitly)"""
596 self
.usage
+= " //depot/path[@revRange]"
598 self
.createdBranches
= Set()
599 self
.committedChanges
= Set()
601 self
.detectBranches
= False
602 self
.detectLabels
= False
603 self
.changesFile
= ""
604 self
.syncWithOrigin
= True
606 self
.importIntoRemotes
= True
608 self
.isWindows
= (platform
.system() == "Windows")
609 self
.keepRepoPath
= False
610 self
.depotPaths
= None
612 if gitConfig("git-p4.syncFromOrigin") == "false":
613 self
.syncWithOrigin
= False
615 def p4File(self
, depotPath
):
616 return read_pipe("p4 print -q \"%s\"" % depotPath
)
618 def extractFilesFromCommit(self
, commit
):
621 while commit
.has_key("depotFile%s" % fnum
):
622 path
= commit
["depotFile%s" % fnum
]
624 found
= [p
for p
in self
.depotPaths
625 if path
.startswith (p
)]
632 file["rev"] = commit
["rev%s" % fnum
]
633 file["action"] = commit
["action%s" % fnum
]
634 file["type"] = commit
["type%s" % fnum
]
639 def stripRepoPath(self
, path
, prefixes
):
640 if self
.keepRepoPath
:
641 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
644 if path
.startswith(p
):
649 def splitFilesIntoBranches(self
, commit
):
652 while commit
.has_key("depotFile%s" % fnum
):
653 path
= commit
["depotFile%s" % fnum
]
654 found
= [p
for p
in self
.depotPaths
655 if path
.startswith (p
)]
662 file["rev"] = commit
["rev%s" % fnum
]
663 file["action"] = commit
["action%s" % fnum
]
664 file["type"] = commit
["type%s" % fnum
]
667 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
669 for branch
in self
.knownBranches
.keys():
671 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
672 if relPath
.startswith(branch
+ "/"):
673 if branch
not in branches
:
674 branches
[branch
] = []
675 branches
[branch
].append(file)
679 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
680 epoch
= details
["time"]
681 author
= details
["user"]
684 print "commit into %s" % branch
686 self
.gitStream
.write("commit %s\n" % branch
)
687 # gitStream.write("mark :%s\n" % details["change"])
688 self
.committedChanges
.add(int(details
["change"]))
690 if author
not in self
.users
:
691 self
.getUserMapFromPerforceServer()
692 if author
in self
.users
:
693 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
695 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
697 self
.gitStream
.write("committer %s\n" % committer
)
699 self
.gitStream
.write("data <<EOT\n")
700 self
.gitStream
.write(details
["desc"])
701 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
703 % (','.join (branchPrefixes
), details
["change"],
706 self
.gitStream
.write("EOT\n\n")
710 print "parent %s" % parent
711 self
.gitStream
.write("from %s\n" % parent
)
717 if not [p
for p
in branchPrefixes
if path
.startswith(p
)]:
720 depotPath
= path
+ "#" + rev
721 relPath
= self
.stripRepoPath(path
, branchPrefixes
)
722 action
= file["action"]
724 if file["type"] == "apple":
725 print "\nfile %s is a strange apple file that forks. Ignoring!" % path
728 if action
== "delete":
729 self
.gitStream
.write("D %s\n" % relPath
)
732 if file["type"].startswith("x"):
735 data
= self
.p4File(depotPath
)
737 if self
.isWindows
and file["type"].endswith("text"):
738 data
= data
.replace("\r\n", "\n")
740 self
.gitStream
.write("M %s inline %s\n" % (mode
, relPath
))
741 self
.gitStream
.write("data %s\n" % len(data
))
742 self
.gitStream
.write(data
)
743 self
.gitStream
.write("\n")
745 self
.gitStream
.write("\n")
747 change
= int(details
["change"])
749 if self
.labels
.has_key(change
):
750 label
= self
.labels
[change
]
751 labelDetails
= label
[0]
752 labelRevisions
= label
[1]
754 print "Change %s is labelled %s" % (change
, labelDetails
)
756 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
757 for p
in branchPrefixes
]))
759 if len(files
) == len(labelRevisions
):
763 if info
["action"] == "delete":
765 cleanedFiles
[info
["depotFile"]] = info
["rev"]
767 if cleanedFiles
== labelRevisions
:
768 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
769 self
.gitStream
.write("from %s\n" % branch
)
771 owner
= labelDetails
["Owner"]
773 if author
in self
.users
:
774 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
776 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
777 self
.gitStream
.write("tagger %s\n" % tagger
)
778 self
.gitStream
.write("data <<EOT\n")
779 self
.gitStream
.write(labelDetails
["Description"])
780 self
.gitStream
.write("EOT\n\n")
784 print ("Tag %s does not match with change %s: files do not match."
785 % (labelDetails
["label"], change
))
789 print ("Tag %s does not match with change %s: file count is different."
790 % (labelDetails
["label"], change
))
792 def getUserMapFromPerforceServer(self
):
793 if self
.userMapFromPerforceServer
:
797 for output
in p4CmdList("users"):
798 if not output
.has_key("User"):
800 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
802 cache
= open(gitdir
+ "/p4-usercache.txt", "wb")
803 for user
in self
.users
.keys():
804 cache
.write("%s\t%s\n" % (user
, self
.users
[user
]))
806 self
.userMapFromPerforceServer
= True
808 def loadUserMapFromCache(self
):
810 self
.userMapFromPerforceServer
= False
812 cache
= open(gitdir
+ "/p4-usercache.txt", "rb")
813 lines
= cache
.readlines()
816 entry
= line
.strip().split("\t")
817 self
.users
[entry
[0]] = entry
[1]
819 self
.getUserMapFromPerforceServer()
824 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
825 if len(l
) > 0 and not self
.silent
:
826 print "Finding files belonging to labels in %s" % `self
.depotPath`
829 label
= output
["label"]
833 print "Querying files for label %s" % label
834 for file in p4CmdList("files "
835 + ' '.join (["%s...@%s" % (p
, label
)
836 for p
in self
.depotPaths
])):
837 revisions
[file["depotFile"]] = file["rev"]
838 change
= int(file["change"])
839 if change
> newestChange
:
840 newestChange
= change
842 self
.labels
[newestChange
] = [output
, revisions
]
845 print "Label changes: %s" % self
.labels
.keys()
847 def getBranchMapping(self
):
849 ## FIXME - what's a P4 projectName ?
850 self
.projectName
= self
.depotPath
[self
.depotPath
.strip().rfind("/") + 1:]
852 for info
in p4CmdList("branches"):
853 details
= p4Cmd("branch -o %s" % info
["branch"])
855 while details
.has_key("View%s" % viewIdx
):
856 paths
= details
["View%s" % viewIdx
].split(" ")
857 viewIdx
= viewIdx
+ 1
858 # require standard //depot/foo/... //depot/bar/... mapping
859 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
862 destination
= paths
[1]
863 if source
.startswith(self
.depotPath
) and destination
.startswith(self
.depotPath
):
864 source
= source
[len(self
.depotPath
):-4]
865 destination
= destination
[len(self
.depotPath
):-4]
866 if destination
not in self
.knownBranches
:
867 self
.knownBranches
[destination
] = source
868 if source
not in self
.knownBranches
:
869 self
.knownBranches
[source
] = source
871 def listExistingP4GitBranches(self
):
872 self
.p4BranchesInGit
= []
874 cmdline
= "git rev-parse --symbolic "
875 if self
.importIntoRemotes
:
876 cmdline
+= " --remotes"
878 cmdline
+= " --branches"
880 for line
in read_pipe_lines(cmdline
):
882 if self
.importIntoRemotes
and ((not line
.startswith("p4/")) or line
== "p4/HEAD"):
885 if self
.importIntoRemotes
:
887 branch
= re
.sub ("^p4/", "", line
)
889 self
.p4BranchesInGit
.append(branch
)
890 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
892 def createOrUpdateBranchesFromOrigin(self
):
894 print "Creating/updating branch(es) in %s based on origin branch(es)" % self
.refPrefix
896 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
898 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
901 headName
= line
[len("origin/"):]
902 remoteHead
= self
.refPrefix
+ headName
903 originHead
= "origin/" + headName
905 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
906 if (not original
.has_key('depot-paths')
907 or not original
.has_key('change')):
911 if not gitBranchExists(remoteHead
):
913 print "creating %s" % remoteHead
916 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
917 if settings
.has_key('change') > 0:
918 if settings
['depot-paths'] == original
['depot-paths']:
919 originP4Change
= int(original
['change'])
920 p4Change
= int(settings
['change'])
921 if originP4Change
> p4Change
:
922 print ("%s (%s) is newer than %s (%s). "
923 "Updating p4 branch from origin."
924 % (originHead
, originP4Change
,
925 remoteHead
, p4Change
))
928 print ("Ignoring: %s was imported from %s while "
929 "%s was imported from %s"
930 % (originHead
, ','.join(original
['depot-paths']),
931 remoteHead
, ','.join(settings
['depot-paths'])))
934 system("git update-ref %s %s" % (remoteHead
, originHead
))
936 def updateOptionDict(self
, d
):
938 if self
.keepRepoPath
:
939 option_keys
['keepRepoPath'] = 1
941 d
["options"] = ' '.join(sorted(option_keys
.keys()))
943 def readOptions(self
, d
):
944 self
.keepRepoPath
= (d
.has_key('options')
945 and ('keepRepoPath' in d
['options']))
949 self
.changeRange
= ""
950 self
.initialParent
= ""
951 self
.previousDepotPaths
= []
953 # map from branch depot path to parent branch
954 self
.knownBranches
= {}
955 self
.initialParents
= {}
956 self
.hasOrigin
= gitBranchExists("origin")
958 if self
.importIntoRemotes
:
959 self
.refPrefix
= "refs/remotes/p4/"
961 self
.refPrefix
= "refs/heads/"
963 if self
.syncWithOrigin
and self
.hasOrigin
:
965 print "Syncing with origin first by calling git fetch origin"
966 system("git fetch origin")
968 if len(self
.branch
) == 0:
969 self
.branch
= self
.refPrefix
+ "master"
970 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
971 system("git update-ref %s refs/heads/p4" % self
.branch
)
972 system("git branch -D p4");
973 # create it /after/ importing, when master exists
974 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
975 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
980 self
.createOrUpdateBranchesFromOrigin()
981 self
.listExistingP4GitBranches()
983 if len(self
.p4BranchesInGit
) > 1:
985 print "Importing from/into multiple branches"
986 self
.detectBranches
= True
989 print "branches: %s" % self
.p4BranchesInGit
992 for branch
in self
.p4BranchesInGit
:
993 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
995 settings
= extractSettingsGitLog(logMsg
)
998 print "path %s change %s" % (','.join(depotPaths
), change
)
1000 self
.readOptions(settings
)
1001 if (settings
.has_key('depot-paths')
1002 and settings
.has_key ('change')):
1003 change
= int(settings
['change']) + 1
1004 p4Change
= max(p4Change
, change
)
1006 depotPaths
= sorted(settings
['depot-paths'])
1007 if self
.previousDepotPaths
== []:
1008 self
.previousDepotPaths
= depotPaths
1011 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1012 for i
in range(0, max(len(cur
), len(prev
))):
1013 if cur
[i
] <> prev
[i
]:
1016 paths
.append (cur
[:i
])
1018 self
.previousDepotPaths
= paths
1021 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1022 self
.changeRange
= "@%s,#head" % p4Change
1023 self
.initialParent
= parseRevision(self
.branch
)
1024 if not self
.silent
and not self
.detectBranches
:
1025 print "Performing incremental import into %s git branch" % self
.branch
1027 if not self
.branch
.startswith("refs/"):
1028 self
.branch
= "refs/heads/" + self
.branch
1030 if len(args
) == 0 and self
.depotPaths
:
1032 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1034 if self
.depotPaths
and self
.depotPaths
!= args
:
1035 print ("previous import used depot path %s and now %s was specified. "
1036 "This doesn't work!" % (' '.join (self
.depotPaths
),
1040 self
.depotPaths
= sorted(args
)
1046 for p
in self
.depotPaths
:
1047 if p
.find("@") != -1:
1048 atIdx
= p
.index("@")
1049 self
.changeRange
= p
[atIdx
:]
1050 if self
.changeRange
== "@all":
1051 self
.changeRange
= ""
1052 elif self
.changeRange
.find(",") == -1:
1053 self
.revision
= self
.changeRange
1054 self
.changeRange
= ""
1056 elif p
.find("#") != -1:
1057 hashIdx
= p
.index("#")
1058 self
.revision
= p
[hashIdx
:]
1060 elif self
.previousDepotPaths
== []:
1061 self
.revision
= "#head"
1063 p
= re
.sub ("\.\.\.$", "", p
)
1064 if not p
.endswith("/"):
1069 self
.depotPaths
= newPaths
1072 self
.loadUserMapFromCache()
1074 if self
.detectLabels
:
1077 if self
.detectBranches
:
1078 self
.getBranchMapping();
1080 print "p4-git branches: %s" % self
.p4BranchesInGit
1081 print "initial parents: %s" % self
.initialParents
1082 for b
in self
.p4BranchesInGit
:
1086 b
= b
[len(self
.projectName
):]
1087 self
.createdBranches
.add(b
)
1089 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1091 importProcess
= subprocess
.Popen(["git", "fast-import"],
1092 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1093 stderr
=subprocess
.PIPE
);
1094 self
.gitOutput
= importProcess
.stdout
1095 self
.gitStream
= importProcess
.stdin
1096 self
.gitError
= importProcess
.stderr
1098 if len(self
.revision
) > 0:
1099 print "Doing initial import of %s from revision %s" % (' '.join(self
.depotPaths
), self
.revision
)
1101 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1102 details
["desc"] = ("Initial import of %s from the state at revision %s"
1103 % (' '.join(self
.depotPaths
), self
.revision
))
1104 details
["change"] = self
.revision
1108 for info
in p4CmdList("files "
1109 + ' '.join(["%s...%s"
1110 % (p
, self
.revision
)
1111 for p
in self
.depotPaths
])):
1112 change
= int(info
["change"])
1113 if change
> newestRevision
:
1114 newestRevision
= change
1116 if info
["action"] == "delete":
1117 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1118 #fileCnt = fileCnt + 1
1121 for prop
in [ "depotFile", "rev", "action", "type" ]:
1122 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1124 fileCnt
= fileCnt
+ 1
1126 details
["change"] = newestRevision
1127 self
.updateOptionDict(details
)
1129 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1131 print "IO error with git fast-import. Is your git version recent enough?"
1132 print self
.gitError
.read()
1137 if len(self
.changesFile
) > 0:
1138 output
= open(self
.changesFile
).readlines()
1141 changeSet
.add(int(line
))
1143 for change
in changeSet
:
1144 changes
.append(change
)
1149 print "Getting p4 changes for %s...%s" % (`self
.depotPaths`
,
1151 assert self
.depotPaths
1152 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1153 for p
in self
.depotPaths
]))
1156 changeNum
= line
.split(" ")[1]
1157 changes
.append(changeNum
)
1161 if len(self
.maxChanges
) > 0:
1162 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1164 if len(changes
) == 0:
1166 print "No changes to import!"
1169 self
.updatedBranches
= set()
1172 for change
in changes
:
1173 description
= p4Cmd("describe %s" % change
)
1174 self
.updateOptionDict(description
)
1177 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1182 if self
.detectBranches
:
1183 branches
= self
.splitFilesIntoBranches(description
)
1184 for branch
in branches
.keys():
1186 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1190 filesForCommit
= branches
[branch
]
1193 print "branch is %s" % branch
1195 self
.updatedBranches
.add(branch
)
1197 if branch
not in self
.createdBranches
:
1198 self
.createdBranches
.add(branch
)
1199 parent
= self
.knownBranches
[branch
]
1200 if parent
== branch
:
1203 print "parent determined through known branches: %s" % parent
1205 # main branch? use master
1206 if branch
== "main":
1211 branch
= self
.projectName
+ branch
1213 if parent
== "main":
1215 elif len(parent
) > 0:
1217 parent
= self
.projectName
+ parent
1219 branch
= self
.refPrefix
+ branch
1221 parent
= self
.refPrefix
+ parent
1224 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1226 if len(parent
) == 0 and branch
in self
.initialParents
:
1227 parent
= self
.initialParents
[branch
]
1228 del self
.initialParents
[branch
]
1230 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1232 files
= self
.extractFilesFromCommit(description
)
1233 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1235 self
.initialParent
= ""
1237 print self
.gitError
.read()
1242 if len(self
.updatedBranches
) > 0:
1243 sys
.stdout
.write("Updated branches: ")
1244 for b
in self
.updatedBranches
:
1245 sys
.stdout
.write("%s " % b
)
1246 sys
.stdout
.write("\n")
1249 self
.gitStream
.close()
1250 if importProcess
.wait() != 0:
1251 die("fast-import failed: %s" % self
.gitError
.read())
1252 self
.gitOutput
.close()
1253 self
.gitError
.close()
1257 class P4Rebase(Command
):
1259 Command
.__init
__(self
)
1261 self
.description
= ("Fetches the latest revision from perforce and "
1262 + "rebases the current work (branch) against it")
1264 def run(self
, args
):
1267 print "Rebasing the current branch"
1268 oldHead
= read_pipe("git rev-parse HEAD").strip()
1269 system("git rebase p4")
1270 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1273 class P4Clone(P4Sync
):
1275 P4Sync
.__init
__(self
)
1276 self
.description
= "Creates a new git repository and imports from Perforce into it"
1277 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1278 self
.options
.append(
1279 optparse
.make_option("--destination", dest
="cloneDestination",
1280 action
='store', default
=None,
1281 help="where to leave result of the clone"))
1282 self
.cloneDestination
= None
1283 self
.needsGit
= False
1285 def run(self
, args
):
1291 if self
.keepRepoPath
and not self
.cloneDestination
:
1292 sys
.stderr
.write("Must specify destination for --keep-path\n")
1296 for p
in depotPaths
:
1297 if not p
.startswith("//"):
1300 if not self
.cloneDestination
:
1302 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1303 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1304 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1305 depotDir
= re
.sub(r
"/$", "", depotDir
)
1307 self
.cloneDestination
= os
.path
.split(depotDir
)[1]
1309 print "Importing from %s into %s" % (`depotPaths`
, self
.cloneDestination
)
1310 os
.makedirs(self
.cloneDestination
)
1311 os
.chdir(self
.cloneDestination
)
1313 gitdir
= os
.getcwd() + "/.git"
1314 if not P4Sync
.run(self
, depotPaths
):
1316 if self
.branch
!= "master":
1317 if gitBranchExists("refs/remotes/p4/master"):
1318 system("git branch master refs/remotes/p4/master")
1319 system("git checkout -f")
1321 print "Could not detect main branch. No checkout/master branch created."
1324 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1326 optparse
.IndentedHelpFormatter
.__init
__(self
)
1328 def format_description(self
, description
):
1330 return description
+ "\n"
1334 def printUsage(commands
):
1335 print "usage: %s <command> [options]" % sys
.argv
[0]
1337 print "valid commands: %s" % ", ".join(commands
)
1339 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1343 "debug" : P4Debug(),
1344 "submit" : P4Submit(),
1346 "rebase" : P4Rebase(),
1347 "clone" : P4Clone(),
1348 "rollback" : P4RollBack()
1353 if len(sys
.argv
[1:]) == 0:
1354 printUsage(commands
.keys())
1358 cmdName
= sys
.argv
[1]
1360 cmd
= commands
[cmdName
]
1362 print "unknown command %s" % cmdName
1364 printUsage(commands
.keys())
1367 options
= cmd
.options
1372 if len(options
) > 0:
1373 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1375 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1377 description
= cmd
.description
,
1378 formatter
= HelpFormatter())
1380 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1382 verbose
= cmd
.verbose
1385 if len(gitdir
) == 0:
1387 if not isValidGitDir(gitdir
):
1388 gitdir
= read_pipe("git rev-parse --git-dir").strip()
1389 if os
.path
.exists(gitdir
):
1390 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1394 if not isValidGitDir(gitdir
):
1395 if isValidGitDir(gitdir
+ "/.git"):
1398 die("fatal: cannot locate git repository at %s" % gitdir
)
1400 os
.environ
["GIT_DIR"] = gitdir
1402 if not cmd
.run(args
):
1406 if __name__
== '__main__':