3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 import optparse
, sys
, os
, marshal
, popen2
, subprocess
, shelve
12 import tempfile
, getopt
, sha
, os
.path
, time
, platform
23 sys
.stderr
.write(msg
+ "\n")
26 def write_pipe(c
, str):
28 sys
.stderr
.write('Writing pipe: %s\n' % c
)
30 pipe
= os
.popen(c
, 'w')
33 die('Command failed: %s' % c
)
37 def read_pipe(c
, ignore_error
=False):
39 sys
.stderr
.write('Reading pipe: %s\n' % c
)
41 pipe
= os
.popen(c
, 'rb')
43 if pipe
.close() and not ignore_error
:
44 die('Command failed: %s' % c
)
49 def read_pipe_lines(c
):
51 sys
.stderr
.write('Reading pipe: %s\n' % c
)
52 ## todo: check return status
53 pipe
= os
.popen(c
, 'rb')
54 val
= pipe
.readlines()
56 die('Command failed: %s' % c
)
62 sys
.stderr
.write("executing %s\n" % cmd
)
63 if os
.system(cmd
) != 0:
64 die("command failed: %s" % cmd
)
67 cmd
= "p4 -G %s" % cmd
69 sys
.stderr
.write("Opening pipe: %s\n" % cmd
)
70 pipe
= os
.popen(cmd
, "rb")
75 entry
= marshal
.load(pipe
)
79 exitCode
= pipe
.close()
82 entry
["p4ExitCode"] = exitCode
94 def p4Where(depotPath
):
95 if not depotPath
.endswith("/"):
97 output
= p4Cmd("where %s..." % depotPath
)
98 if output
["code"] == "error":
102 clientPath
= output
.get("path")
103 elif "data" in output
:
104 data
= output
.get("data")
105 lastSpace
= data
.rfind(" ")
106 clientPath
= data
[lastSpace
+ 1:]
108 if clientPath
.endswith("..."):
109 clientPath
= clientPath
[:-3]
112 def currentGitBranch():
113 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
115 def isValidGitDir(path
):
116 if (os
.path
.exists(path
+ "/HEAD")
117 and os
.path
.exists(path
+ "/refs") and os
.path
.exists(path
+ "/objects")):
121 def parseRevision(ref
):
122 return read_pipe("git rev-parse %s" % ref
).strip()
124 def extractLogMessageFromGitCommit(commit
):
127 ## fixme: title is first line of commit, not 1st paragraph.
129 for log
in read_pipe_lines("git cat-file commit %s" % commit
):
138 def extractSettingsGitLog(log
):
140 for line
in log
.split("\n"):
142 m
= re
.search (r
"^ *\[git-p4: (.*)\]$", line
)
146 assignments
= m
.group(1).split (':')
147 for a
in assignments
:
149 key
= vals
[0].strip()
150 val
= ('='.join (vals
[1:])).strip()
151 if val
.endswith ('\"') and val
.startswith('"'):
156 paths
= values
.get("depot-paths")
158 paths
= values
.get("depot-path")
159 values
['depot-paths'] = paths
.split(',')
162 def gitBranchExists(branch
):
163 proc
= subprocess
.Popen(["git", "rev-parse", branch
],
164 stderr
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
);
165 return proc
.wait() == 0;
168 return read_pipe("git config %s" % key
, ignore_error
=True).strip()
172 self
.usage
= "usage: %prog [options]"
175 class P4Debug(Command
):
177 Command
.__init
__(self
)
179 optparse
.make_option("--verbose", dest
="verbose", action
="store_true",
182 self
.description
= "A tool to debug the output of p4 -G."
183 self
.needsGit
= False
188 for output
in p4CmdList(" ".join(args
)):
189 print 'Element: %d' % j
194 class P4RollBack(Command
):
196 Command
.__init
__(self
)
198 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
199 optparse
.make_option("--local", dest
="rollbackLocalBranches", action
="store_true")
201 self
.description
= "A tool to debug the multi-branch import. Don't use :)"
203 self
.rollbackLocalBranches
= False
208 maxChange
= int(args
[0])
210 if "p4ExitCode" in p4Cmd("changes -m 1"):
211 die("Problems executing p4");
213 if self
.rollbackLocalBranches
:
214 refPrefix
= "refs/heads/"
215 lines
= read_pipe_lines("git rev-parse --symbolic --branches")
217 refPrefix
= "refs/remotes/"
218 lines
= read_pipe_lines("git rev-parse --symbolic --remotes")
221 if self
.rollbackLocalBranches
or (line
.startswith("p4/") and line
!= "p4/HEAD\n"):
223 ref
= refPrefix
+ line
224 log
= extractLogMessageFromGitCommit(ref
)
225 settings
= extractSettingsGitLog(log
)
227 depotPaths
= settings
['depot-paths']
228 change
= settings
['change']
232 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p
, maxChange
)
233 for p
in depotPaths
]))) == 0:
234 print "Branch %s did not exist at change %s, deleting." % (ref
, maxChange
)
235 system("git update-ref -d %s `git rev-parse %s`" % (ref
, ref
))
238 while change
and int(change
) > maxChange
:
241 print "%s is at %s ; rewinding towards %s" % (ref
, change
, maxChange
)
242 system("git update-ref %s \"%s^\"" % (ref
, ref
))
243 log
= extractLogMessageFromGitCommit(ref
)
244 settings
= extractSettingsGitLog(log
)
247 depotPaths
= settings
['depot-paths']
248 change
= settings
['change']
251 print "%s rewound to %s" % (ref
, change
)
255 class P4Submit(Command
):
257 Command
.__init
__(self
)
259 optparse
.make_option("--continue", action
="store_false", dest
="firstTime"),
260 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
261 optparse
.make_option("--origin", dest
="origin"),
262 optparse
.make_option("--reset", action
="store_true", dest
="reset"),
263 optparse
.make_option("--log-substitutions", dest
="substFile"),
264 optparse
.make_option("--dry-run", action
="store_true"),
265 optparse
.make_option("--direct", dest
="directSubmit", action
="store_true"),
266 optparse
.make_option("--trust-me-like-a-fool", dest
="trustMeLikeAFool", action
="store_true"),
268 self
.description
= "Submit changes from git to the perforce depot."
269 self
.usage
+= " [name of git branch to submit into perforce depot]"
270 self
.firstTime
= True
272 self
.interactive
= True
275 self
.firstTime
= True
277 self
.directSubmit
= False
278 self
.trustMeLikeAFool
= False
280 self
.isWindows
= (platform
.system() == "Windows")
282 self
.logSubstitutions
= {}
283 self
.logSubstitutions
["<enter description here>"] = "%log%"
284 self
.logSubstitutions
["\tDetails:"] = "\tDetails: %log%"
287 if len(p4CmdList("opened ...")) > 0:
288 die("You have files opened with perforce! Close them before starting the sync.")
291 if len(self
.config
) > 0 and not self
.reset
:
292 die("Cannot start sync. Previous sync config found at %s\n"
293 "If you want to start submitting again from scratch "
294 "maybe you want to call git-p4 submit --reset" % self
.configFile
)
297 if self
.directSubmit
:
300 for line
in read_pipe_lines("git rev-list --no-merges %s..%s" % (self
.origin
, self
.master
)):
301 commits
.append(line
.strip())
304 self
.config
["commits"] = commits
306 def prepareLogMessage(self
, template
, message
):
309 for line
in template
.split("\n"):
310 if line
.startswith("#"):
311 result
+= line
+ "\n"
315 for key
in self
.logSubstitutions
.keys():
316 if line
.find(key
) != -1:
317 value
= self
.logSubstitutions
[key
]
318 value
= value
.replace("%log%", message
)
319 if value
!= "@remove@":
320 result
+= line
.replace(key
, value
) + "\n"
325 result
+= line
+ "\n"
329 def applyCommit(self
, id):
330 if self
.directSubmit
:
331 print "Applying local change in working directory/index"
332 diff
= self
.diffStatus
334 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
335 diff
= read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
337 filesToDelete
= set()
341 path
= line
[1:].strip()
343 system("p4 edit \"%s\"" % path
)
344 editedFiles
.add(path
)
345 elif modifier
== "A":
347 if path
in filesToDelete
:
348 filesToDelete
.remove(path
)
349 elif modifier
== "D":
350 filesToDelete
.add(path
)
351 if path
in filesToAdd
:
352 filesToAdd
.remove(path
)
354 die("unknown modifier %s for %s" % (modifier
, path
))
356 if self
.directSubmit
:
357 diffcmd
= "cat \"%s\"" % self
.diffFile
359 diffcmd
= "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
360 patchcmd
= diffcmd
+ " | git apply "
361 tryPatchCmd
= patchcmd
+ "--check -"
362 applyPatchCmd
= patchcmd
+ "--check --apply -"
364 if os
.system(tryPatchCmd
) != 0:
365 print "Unfortunately applying the change failed!"
366 print "What do you want to do?"
368 while response
!= "s" and response
!= "a" and response
!= "w":
369 response
= raw_input("[s]kip this patch / [a]pply the patch forcibly "
370 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
372 print "Skipping! Good luck with the next patches..."
374 elif response
== "a":
375 os
.system(applyPatchCmd
)
376 if len(filesToAdd
) > 0:
377 print "You may also want to call p4 add on the following files:"
378 print " ".join(filesToAdd
)
379 if len(filesToDelete
):
380 print "The following files should be scheduled for deletion with p4 delete:"
381 print " ".join(filesToDelete
)
382 die("Please resolve and submit the conflict manually and "
383 + "continue afterwards with git-p4 submit --continue")
384 elif response
== "w":
385 system(diffcmd
+ " > patch.txt")
386 print "Patch saved to patch.txt in %s !" % self
.clientPath
387 die("Please resolve and submit the conflict manually and "
388 "continue afterwards with git-p4 submit --continue")
390 system(applyPatchCmd
)
393 system("p4 add %s" % f
)
394 for f
in filesToDelete
:
395 system("p4 revert %s" % f
)
396 system("p4 delete %s" % f
)
399 if not self
.directSubmit
:
400 logMessage
= extractLogMessageFromGitCommit(id)
401 logMessage
= logMessage
.replace("\n", "\n\t")
403 logMessage
= logMessage
.replace("\n", "\r\n")
404 logMessage
= logMessage
.strip()
406 template
= read_pipe("p4 change -o")
409 submitTemplate
= self
.prepareLogMessage(template
, logMessage
)
410 diff
= read_pipe("p4 diff -du ...")
412 for newFile
in filesToAdd
:
413 diff
+= "==== new file ====\n"
414 diff
+= "--- /dev/null\n"
415 diff
+= "+++ %s\n" % newFile
416 f
= open(newFile
, "r")
417 for line
in f
.readlines():
421 separatorLine
= "######## everything below this line is just the diff #######"
422 if platform
.system() == "Windows":
423 separatorLine
+= "\r"
424 separatorLine
+= "\n"
427 if self
.trustMeLikeAFool
:
430 firstIteration
= True
431 while response
== "e":
432 if not firstIteration
:
433 response
= raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
434 firstIteration
= False
436 [handle
, fileName
] = tempfile
.mkstemp()
437 tmpFile
= os
.fdopen(handle
, "w+")
438 tmpFile
.write(submitTemplate
+ separatorLine
+ diff
)
441 if platform
.system() == "Windows":
442 defaultEditor
= "notepad"
443 editor
= os
.environ
.get("EDITOR", defaultEditor
);
444 system(editor
+ " " + fileName
)
445 tmpFile
= open(fileName
, "rb")
446 message
= tmpFile
.read()
449 submitTemplate
= message
[:message
.index(separatorLine
)]
451 submitTemplate
= submitTemplate
.replace("\r\n", "\n")
453 if response
== "y" or response
== "yes":
456 raw_input("Press return to continue...")
458 if self
.directSubmit
:
459 print "Submitting to git first"
460 os
.chdir(self
.oldWorkingDirectory
)
461 write_pipe("git commit -a -F -", submitTemplate
)
462 os
.chdir(self
.clientPath
)
464 write_pipe("p4 submit -i", submitTemplate
)
465 elif response
== "s":
466 for f
in editedFiles
:
467 system("p4 revert \"%s\"" % f
);
469 system("p4 revert \"%s\"" % f
);
471 for f
in filesToDelete
:
472 system("p4 delete \"%s\"" % f
);
475 print "Not submitting!"
476 self
.interactive
= False
478 fileName
= "submit.txt"
479 file = open(fileName
, "w+")
480 file.write(self
.prepareLogMessage(template
, logMessage
))
482 print ("Perforce submit template written as %s. "
483 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
484 % (fileName
, fileName
))
488 self
.master
= currentGitBranch()
489 if len(self
.master
) == 0 or not gitBranchExists("refs/heads/%s" % self
.master
):
490 die("Detecting current git branch failed!")
492 self
.master
= args
[0]
498 if gitBranchExists("p4"):
499 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("p4"))
500 if len(depotPath
) == 0 and gitBranchExists("origin"):
501 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit("origin"))
502 depotPath
= settings
['depot-paths'][0]
504 if len(depotPath
) == 0:
505 print "Internal error: cannot locate perforce depot path from existing branches"
508 self
.clientPath
= p4Where(depotPath
)
510 if len(self
.clientPath
) == 0:
511 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
514 print "Perforce checkout for depot path %s located at %s" % (depotPath
, self
.clientPath
)
515 self
.oldWorkingDirectory
= os
.getcwd()
517 if self
.directSubmit
:
518 self
.diffStatus
= read_pipe_lines("git diff -r --name-status HEAD")
519 if len(self
.diffStatus
) == 0:
520 print "No changes in working directory to submit."
522 patch
= read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
523 self
.diffFile
= self
.gitdir
+ "/p4-git-diff"
524 f
= open(self
.diffFile
, "wb")
528 os
.chdir(self
.clientPath
)
529 response
= raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self
.clientPath
)
530 if response
== "y" or response
== "yes":
531 system("p4 sync ...")
533 if len(self
.origin
) == 0:
534 if gitBranchExists("p4"):
537 self
.origin
= "origin"
540 self
.firstTime
= True
542 if len(self
.substFile
) > 0:
543 for line
in open(self
.substFile
, "r").readlines():
544 tokens
= line
.strip().split("=")
545 self
.logSubstitutions
[tokens
[0]] = tokens
[1]
548 self
.configFile
= self
.gitdir
+ "/p4-git-sync.cfg"
549 self
.config
= shelve
.open(self
.configFile
, writeback
=True)
554 commits
= self
.config
.get("commits", [])
556 while len(commits
) > 0:
557 self
.firstTime
= False
559 commits
= commits
[1:]
560 self
.config
["commits"] = commits
561 self
.applyCommit(commit
)
562 if not self
.interactive
:
567 if self
.directSubmit
:
568 os
.remove(self
.diffFile
)
570 if len(commits
) == 0:
572 print "No changes found to apply between %s and current HEAD" % self
.origin
574 print "All changes applied!"
575 os
.chdir(self
.oldWorkingDirectory
)
576 response
= raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
577 if response
== "y" or response
== "yes":
580 os
.remove(self
.configFile
)
584 class P4Sync(Command
):
586 Command
.__init
__(self
)
588 optparse
.make_option("--branch", dest
="branch"),
589 optparse
.make_option("--detect-branches", dest
="detectBranches", action
="store_true"),
590 optparse
.make_option("--changesfile", dest
="changesFile"),
591 optparse
.make_option("--silent", dest
="silent", action
="store_true"),
592 optparse
.make_option("--detect-labels", dest
="detectLabels", action
="store_true"),
593 optparse
.make_option("--verbose", dest
="verbose", action
="store_true"),
594 optparse
.make_option("--import-local", dest
="importIntoRemotes", action
="store_false",
595 help="Import into refs/heads/ , not refs/remotes"),
596 optparse
.make_option("--max-changes", dest
="maxChanges"),
597 optparse
.make_option("--keep-path", dest
="keepRepoPath", action
='store_true',
598 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
600 self
.description
= """Imports from Perforce into a git repository.\n
602 //depot/my/project/ -- to import the current head
603 //depot/my/project/@all -- to import everything
604 //depot/my/project/@1,6 -- to import only from revision 1 to 6
606 (a ... is not needed in the path p4 specification, it's added implicitly)"""
608 self
.usage
+= " //depot/path[@revRange]"
610 self
.createdBranches
= Set()
611 self
.committedChanges
= Set()
613 self
.detectBranches
= False
614 self
.detectLabels
= False
615 self
.changesFile
= ""
616 self
.syncWithOrigin
= True
618 self
.importIntoRemotes
= True
620 self
.isWindows
= (platform
.system() == "Windows")
621 self
.keepRepoPath
= False
622 self
.depotPaths
= None
624 if gitConfig("git-p4.syncFromOrigin") == "false":
625 self
.syncWithOrigin
= False
627 def extractFilesFromCommit(self
, commit
):
630 while commit
.has_key("depotFile%s" % fnum
):
631 path
= commit
["depotFile%s" % fnum
]
633 found
= [p
for p
in self
.depotPaths
634 if path
.startswith (p
)]
641 file["rev"] = commit
["rev%s" % fnum
]
642 file["action"] = commit
["action%s" % fnum
]
643 file["type"] = commit
["type%s" % fnum
]
648 def stripRepoPath(self
, path
, prefixes
):
649 if self
.keepRepoPath
:
650 prefixes
= [re
.sub("^(//[^/]+/).*", r
'\1', prefixes
[0])]
653 if path
.startswith(p
):
658 def splitFilesIntoBranches(self
, commit
):
661 while commit
.has_key("depotFile%s" % fnum
):
662 path
= commit
["depotFile%s" % fnum
]
663 found
= [p
for p
in self
.depotPaths
664 if path
.startswith (p
)]
671 file["rev"] = commit
["rev%s" % fnum
]
672 file["action"] = commit
["action%s" % fnum
]
673 file["type"] = commit
["type%s" % fnum
]
676 relPath
= self
.stripRepoPath(path
, self
.depotPaths
)
678 for branch
in self
.knownBranches
.keys():
680 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
681 if relPath
.startswith(branch
+ "/"):
682 if branch
not in branches
:
683 branches
[branch
] = []
684 branches
[branch
].append(file)
688 ## Should move this out, doesn't use SELF.
689 def readP4Files(self
, files
):
690 files
= [f
for f
in files
691 if f
['action'] != 'delete']
696 filedata
= p4CmdList('print %s' % ' '.join(['"%s#%s"' % (f
['path'],
702 while j
< len(filedata
):
706 while j
< len(filedata
) and filedata
[j
]['code'] in ('text',
708 text
+= filedata
[j
]['data']
711 contents
[stat
['depotFile']] = text
714 assert not f
.has_key('data')
715 f
['data'] = contents
[f
['path']]
717 def commit(self
, details
, files
, branch
, branchPrefixes
, parent
= ""):
718 epoch
= details
["time"]
719 author
= details
["user"]
722 print "commit into %s" % branch
724 # start with reading files; if that fails, we should not
728 if [p
for p
in branchPrefixes
if f
['path'].startswith(p
)]:
731 sys
.stderr
.write("Ignoring file outside of prefix: %s\n" % path
)
733 self
.readP4Files(files
)
738 self
.gitStream
.write("commit %s\n" % branch
)
739 # gitStream.write("mark :%s\n" % details["change"])
740 self
.committedChanges
.add(int(details
["change"]))
742 if author
not in self
.users
:
743 self
.getUserMapFromPerforceServer()
744 if author
in self
.users
:
745 committer
= "%s %s %s" % (self
.users
[author
], epoch
, self
.tz
)
747 committer
= "%s <a@b> %s %s" % (author
, epoch
, self
.tz
)
749 self
.gitStream
.write("committer %s\n" % committer
)
751 self
.gitStream
.write("data <<EOT\n")
752 self
.gitStream
.write(details
["desc"])
753 self
.gitStream
.write("\n[git-p4: depot-paths = \"%s\": change = %s: "
755 % (','.join (branchPrefixes
), details
["change"],
758 self
.gitStream
.write("EOT\n\n")
762 print "parent %s" % parent
763 self
.gitStream
.write("from %s\n" % parent
)
766 if file["type"] == "apple":
767 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
770 relPath
= self
.stripRepoPath(file['path'], branchPrefixes
)
771 if file["action"] == "delete":
772 self
.gitStream
.write("D %s\n" % relPath
)
775 if file["type"].startswith("x"):
780 if self
.isWindows
and file["type"].endswith("text"):
781 data
= data
.replace("\r\n", "\n")
783 self
.gitStream
.write("M %d inline %s\n" % (mode
, relPath
))
784 self
.gitStream
.write("data %s\n" % len(data
))
785 self
.gitStream
.write(data
)
786 self
.gitStream
.write("\n")
788 self
.gitStream
.write("\n")
790 change
= int(details
["change"])
792 if self
.labels
.has_key(change
):
793 label
= self
.labels
[change
]
794 labelDetails
= label
[0]
795 labelRevisions
= label
[1]
797 print "Change %s is labelled %s" % (change
, labelDetails
)
799 files
= p4CmdList("files " + ' '.join (["%s...@%s" % (p
, change
)
800 for p
in branchPrefixes
]))
802 if len(files
) == len(labelRevisions
):
806 if info
["action"] == "delete":
808 cleanedFiles
[info
["depotFile"]] = info
["rev"]
810 if cleanedFiles
== labelRevisions
:
811 self
.gitStream
.write("tag tag_%s\n" % labelDetails
["label"])
812 self
.gitStream
.write("from %s\n" % branch
)
814 owner
= labelDetails
["Owner"]
816 if author
in self
.users
:
817 tagger
= "%s %s %s" % (self
.users
[owner
], epoch
, self
.tz
)
819 tagger
= "%s <a@b> %s %s" % (owner
, epoch
, self
.tz
)
820 self
.gitStream
.write("tagger %s\n" % tagger
)
821 self
.gitStream
.write("data <<EOT\n")
822 self
.gitStream
.write(labelDetails
["Description"])
823 self
.gitStream
.write("EOT\n\n")
827 print ("Tag %s does not match with change %s: files do not match."
828 % (labelDetails
["label"], change
))
832 print ("Tag %s does not match with change %s: file count is different."
833 % (labelDetails
["label"], change
))
835 def getUserCacheFilename(self
):
836 return os
.environ
["HOME"] + "/.gitp4-usercache.txt"
838 def getUserMapFromPerforceServer(self
):
839 if self
.userMapFromPerforceServer
:
843 for output
in p4CmdList("users"):
844 if not output
.has_key("User"):
846 self
.users
[output
["User"]] = output
["FullName"] + " <" + output
["Email"] + ">"
850 for (key
, val
) in self
.users
.items():
851 s
+= "%s\t%s\n" % (key
, val
)
853 open(self
.getUserCacheFilename(), "wb").write(s
)
854 self
.userMapFromPerforceServer
= True
856 def loadUserMapFromCache(self
):
858 self
.userMapFromPerforceServer
= False
860 cache
= open(self
.getUserCacheFilename(), "rb")
861 lines
= cache
.readlines()
864 entry
= line
.strip().split("\t")
865 self
.users
[entry
[0]] = entry
[1]
867 self
.getUserMapFromPerforceServer()
872 l
= p4CmdList("labels %s..." % ' '.join (self
.depotPaths
))
873 if len(l
) > 0 and not self
.silent
:
874 print "Finding files belonging to labels in %s" % `self
.depotPath`
877 label
= output
["label"]
881 print "Querying files for label %s" % label
882 for file in p4CmdList("files "
883 + ' '.join (["%s...@%s" % (p
, label
)
884 for p
in self
.depotPaths
])):
885 revisions
[file["depotFile"]] = file["rev"]
886 change
= int(file["change"])
887 if change
> newestChange
:
888 newestChange
= change
890 self
.labels
[newestChange
] = [output
, revisions
]
893 print "Label changes: %s" % self
.labels
.keys()
895 def guessProjectName(self
):
896 for p
in self
.depotPaths
:
897 return p
[p
.strip().rfind("/") + 1:]
899 def getBranchMapping(self
):
901 ## FIXME - what's a P4 projectName ?
902 self
.projectName
= self
.guessProjectName()
904 for info
in p4CmdList("branches"):
905 details
= p4Cmd("branch -o %s" % info
["branch"])
907 while details
.has_key("View%s" % viewIdx
):
908 paths
= details
["View%s" % viewIdx
].split(" ")
909 viewIdx
= viewIdx
+ 1
910 # require standard //depot/foo/... //depot/bar/... mapping
911 if len(paths
) != 2 or not paths
[0].endswith("/...") or not paths
[1].endswith("/..."):
914 destination
= paths
[1]
916 if source
.startswith(self
.depotPaths
[0]) and destination
.startswith(self
.depotPaths
[0]):
917 source
= source
[len(self
.depotPaths
[0]):-4]
918 destination
= destination
[len(self
.depotPaths
[0]):-4]
919 if destination
not in self
.knownBranches
:
920 self
.knownBranches
[destination
] = source
921 if source
not in self
.knownBranches
:
922 self
.knownBranches
[source
] = source
924 def listExistingP4GitBranches(self
):
925 self
.p4BranchesInGit
= []
927 cmdline
= "git rev-parse --symbolic "
928 if self
.importIntoRemotes
:
929 cmdline
+= " --remotes"
931 cmdline
+= " --branches"
933 for line
in read_pipe_lines(cmdline
):
936 ## only import to p4/
937 if not line
.startswith('p4/'):
940 if self
.importIntoRemotes
:
942 branch
= re
.sub ("^p4/", "", line
)
944 self
.p4BranchesInGit
.append(branch
)
945 self
.initialParents
[self
.refPrefix
+ branch
] = parseRevision(line
)
947 def createOrUpdateBranchesFromOrigin(self
):
949 print ("Creating/updating branch(es) in %s based on origin branch(es)"
952 for line
in read_pipe_lines("git rev-parse --symbolic --remotes"):
954 if (not line
.startswith("origin/")) or line
.endswith("HEAD\n"):
957 headName
= line
[len("origin/"):]
958 remoteHead
= self
.refPrefix
+ headName
959 originHead
= "origin/" + headName
961 original
= extractSettingsGitLog(extractLogMessageFromGitCommit(originHead
))
962 if (not original
.has_key('depot-paths')
963 or not original
.has_key('change')):
967 if not gitBranchExists(remoteHead
):
969 print "creating %s" % remoteHead
972 settings
= extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead
))
973 if settings
.has_key('change') > 0:
974 if settings
['depot-paths'] == original
['depot-paths']:
975 originP4Change
= int(original
['change'])
976 p4Change
= int(settings
['change'])
977 if originP4Change
> p4Change
:
978 print ("%s (%s) is newer than %s (%s). "
979 "Updating p4 branch from origin."
980 % (originHead
, originP4Change
,
981 remoteHead
, p4Change
))
984 print ("Ignoring: %s was imported from %s while "
985 "%s was imported from %s"
986 % (originHead
, ','.join(original
['depot-paths']),
987 remoteHead
, ','.join(settings
['depot-paths'])))
990 system("git update-ref %s %s" % (remoteHead
, originHead
))
992 def updateOptionDict(self
, d
):
994 if self
.keepRepoPath
:
995 option_keys
['keepRepoPath'] = 1
997 d
["options"] = ' '.join(sorted(option_keys
.keys()))
999 def readOptions(self
, d
):
1000 self
.keepRepoPath
= (d
.has_key('options')
1001 and ('keepRepoPath' in d
['options']))
1003 def run(self
, args
):
1004 self
.depotPaths
= []
1005 self
.changeRange
= ""
1006 self
.initialParent
= ""
1007 self
.previousDepotPaths
= []
1009 # map from branch depot path to parent branch
1010 self
.knownBranches
= {}
1011 self
.initialParents
= {}
1012 self
.hasOrigin
= gitBranchExists("origin")
1014 if self
.importIntoRemotes
:
1015 self
.refPrefix
= "refs/remotes/p4/"
1017 self
.refPrefix
= "refs/heads/"
1019 if self
.syncWithOrigin
and self
.hasOrigin
:
1021 print "Syncing with origin first by calling git fetch origin"
1022 system("git fetch origin")
1024 if len(self
.branch
) == 0:
1025 self
.branch
= self
.refPrefix
+ "p4/master"
1026 if gitBranchExists("refs/heads/p4") and self
.importIntoRemotes
:
1027 system("git update-ref %s refs/heads/p4" % self
.branch
)
1028 system("git branch -D p4");
1029 # create it /after/ importing, when master exists
1030 if not gitBranchExists(self
.refPrefix
+ "HEAD") and self
.importIntoRemotes
:
1031 system("git symbolic-ref %sHEAD %s" % (self
.refPrefix
, self
.branch
))
1033 # TODO: should always look at previous commits,
1034 # merge with previous imports, if possible.
1037 self
.createOrUpdateBranchesFromOrigin()
1038 self
.listExistingP4GitBranches()
1040 if len(self
.p4BranchesInGit
) > 1:
1042 print "Importing from/into multiple branches"
1043 self
.detectBranches
= True
1046 print "branches: %s" % self
.p4BranchesInGit
1049 for branch
in self
.p4BranchesInGit
:
1050 logMsg
= extractLogMessageFromGitCommit(self
.refPrefix
+ branch
)
1052 settings
= extractSettingsGitLog(logMsg
)
1054 self
.readOptions(settings
)
1055 if (settings
.has_key('depot-paths')
1056 and settings
.has_key ('change')):
1057 change
= int(settings
['change']) + 1
1058 p4Change
= max(p4Change
, change
)
1060 depotPaths
= sorted(settings
['depot-paths'])
1061 if self
.previousDepotPaths
== []:
1062 self
.previousDepotPaths
= depotPaths
1065 for (prev
, cur
) in zip(self
.previousDepotPaths
, depotPaths
):
1066 for i
in range(0, min(len(cur
), len(prev
))):
1067 if cur
[i
] <> prev
[i
]:
1071 paths
.append (cur
[:i
+ 1])
1073 self
.previousDepotPaths
= paths
1076 self
.depotPaths
= sorted(self
.previousDepotPaths
)
1077 self
.changeRange
= "@%s,#head" % p4Change
1078 if not self
.detectBranches
:
1079 self
.initialParent
= parseRevision(self
.branch
)
1080 if not self
.silent
and not self
.detectBranches
:
1081 print "Performing incremental import into %s git branch" % self
.branch
1083 if not self
.branch
.startswith("refs/"):
1084 self
.branch
= "refs/heads/" + self
.branch
1086 if len(args
) == 0 and self
.depotPaths
:
1088 print "Depot paths: %s" % ' '.join(self
.depotPaths
)
1090 if self
.depotPaths
and self
.depotPaths
!= args
:
1091 print ("previous import used depot path %s and now %s was specified. "
1092 "This doesn't work!" % (' '.join (self
.depotPaths
),
1096 self
.depotPaths
= sorted(args
)
1102 for p
in self
.depotPaths
:
1103 if p
.find("@") != -1:
1104 atIdx
= p
.index("@")
1105 self
.changeRange
= p
[atIdx
:]
1106 if self
.changeRange
== "@all":
1107 self
.changeRange
= ""
1108 elif ',' not in self
.changeRange
:
1109 self
.revision
= self
.changeRange
1110 self
.changeRange
= ""
1112 elif p
.find("#") != -1:
1113 hashIdx
= p
.index("#")
1114 self
.revision
= p
[hashIdx
:]
1116 elif self
.previousDepotPaths
== []:
1117 self
.revision
= "#head"
1119 p
= re
.sub ("\.\.\.$", "", p
)
1120 if not p
.endswith("/"):
1125 self
.depotPaths
= newPaths
1128 self
.loadUserMapFromCache()
1130 if self
.detectLabels
:
1133 if self
.detectBranches
:
1134 self
.getBranchMapping();
1136 print "p4-git branches: %s" % self
.p4BranchesInGit
1137 print "initial parents: %s" % self
.initialParents
1138 for b
in self
.p4BranchesInGit
:
1142 b
= b
[len(self
.projectName
):]
1143 self
.createdBranches
.add(b
)
1145 self
.tz
= "%+03d%02d" % (- time
.timezone
/ 3600, ((- time
.timezone
% 3600) / 60))
1147 importProcess
= subprocess
.Popen(["git", "fast-import"],
1148 stdin
=subprocess
.PIPE
, stdout
=subprocess
.PIPE
,
1149 stderr
=subprocess
.PIPE
);
1150 self
.gitOutput
= importProcess
.stdout
1151 self
.gitStream
= importProcess
.stdin
1152 self
.gitError
= importProcess
.stderr
1155 print "Doing initial import of %s from revision %s" % (' '.join(self
.depotPaths
), self
.revision
)
1157 details
= { "user" : "git perforce import user", "time" : int(time
.time()) }
1158 details
["desc"] = ("Initial import of %s from the state at revision %s"
1159 % (' '.join(self
.depotPaths
), self
.revision
))
1160 details
["change"] = self
.revision
1164 for info
in p4CmdList("files "
1165 + ' '.join(["%s...%s"
1166 % (p
, self
.revision
)
1167 for p
in self
.depotPaths
])):
1169 if info
['code'] == 'error':
1170 sys
.stderr
.write("p4 returned an error: %s\n"
1175 change
= int(info
["change"])
1176 if change
> newestRevision
:
1177 newestRevision
= change
1179 if info
["action"] == "delete":
1180 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1181 #fileCnt = fileCnt + 1
1184 for prop
in ["depotFile", "rev", "action", "type" ]:
1185 details
["%s%s" % (prop
, fileCnt
)] = info
[prop
]
1187 fileCnt
= fileCnt
+ 1
1189 details
["change"] = newestRevision
1190 self
.updateOptionDict(details
)
1192 self
.commit(details
, self
.extractFilesFromCommit(details
), self
.branch
, self
.depotPaths
)
1194 print "IO error with git fast-import. Is your git version recent enough?"
1195 print self
.gitError
.read()
1200 if len(self
.changesFile
) > 0:
1201 output
= open(self
.changesFile
).readlines()
1204 changeSet
.add(int(line
))
1206 for change
in changeSet
:
1207 changes
.append(change
)
1212 print "Getting p4 changes for %s...%s" % (', '.join(self
.depotPaths
),
1214 assert self
.depotPaths
1215 output
= read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p
, self
.changeRange
)
1216 for p
in self
.depotPaths
]))
1219 changeNum
= line
.split(" ")[1]
1220 changes
.append(changeNum
)
1224 if len(self
.maxChanges
) > 0:
1225 changes
= changes
[0:min(int(self
.maxChanges
), len(changes
))]
1227 if len(changes
) == 0:
1229 print "No changes to import!"
1232 self
.updatedBranches
= set()
1235 for change
in changes
:
1236 description
= p4Cmd("describe %s" % change
)
1237 self
.updateOptionDict(description
)
1240 sys
.stdout
.write("\rImporting revision %s (%s%%)" % (change
, cnt
* 100 / len(changes
)))
1245 if self
.detectBranches
:
1246 branches
= self
.splitFilesIntoBranches(description
)
1247 for branch
in branches
.keys():
1249 branchPrefix
= self
.depotPaths
[0] + branch
+ "/"
1253 filesForCommit
= branches
[branch
]
1256 print "branch is %s" % branch
1258 self
.updatedBranches
.add(branch
)
1260 if branch
not in self
.createdBranches
:
1261 self
.createdBranches
.add(branch
)
1262 parent
= self
.knownBranches
[branch
]
1263 if parent
== branch
:
1266 print "parent determined through known branches: %s" % parent
1268 # main branch? use master
1269 if branch
== "main":
1274 branch
= self
.projectName
+ branch
1276 if parent
== "main":
1278 elif len(parent
) > 0:
1280 parent
= self
.projectName
+ parent
1282 branch
= self
.refPrefix
+ branch
1284 parent
= self
.refPrefix
+ parent
1287 print "looking for initial parent for %s; current parent is %s" % (branch
, parent
)
1289 if len(parent
) == 0 and branch
in self
.initialParents
:
1290 parent
= self
.initialParents
[branch
]
1291 del self
.initialParents
[branch
]
1293 self
.commit(description
, filesForCommit
, branch
, branchPrefix
, parent
)
1295 files
= self
.extractFilesFromCommit(description
)
1296 self
.commit(description
, files
, self
.branch
, self
.depotPaths
,
1298 self
.initialParent
= ""
1300 print self
.gitError
.read()
1305 if len(self
.updatedBranches
) > 0:
1306 sys
.stdout
.write("Updated branches: ")
1307 for b
in self
.updatedBranches
:
1308 sys
.stdout
.write("%s " % b
)
1309 sys
.stdout
.write("\n")
1312 self
.gitStream
.close()
1313 if importProcess
.wait() != 0:
1314 die("fast-import failed: %s" % self
.gitError
.read())
1315 self
.gitOutput
.close()
1316 self
.gitError
.close()
1320 class P4Rebase(Command
):
1322 Command
.__init
__(self
)
1324 self
.description
= ("Fetches the latest revision from perforce and "
1325 + "rebases the current work (branch) against it")
1326 self
.verbose
= False
1328 def run(self
, args
):
1331 print "Rebasing the current branch"
1332 oldHead
= read_pipe("git rev-parse HEAD").strip()
1333 system("git rebase p4")
1334 system("git diff-tree --stat --summary -M %s HEAD" % oldHead
)
1337 class P4Clone(P4Sync
):
1339 P4Sync
.__init
__(self
)
1340 self
.description
= "Creates a new git repository and imports from Perforce into it"
1341 self
.usage
= "usage: %prog [options] //depot/path[@revRange]"
1342 self
.options
.append(
1343 optparse
.make_option("--destination", dest
="cloneDestination",
1344 action
='store', default
=None,
1345 help="where to leave result of the clone"))
1346 self
.cloneDestination
= None
1347 self
.needsGit
= False
1349 def defaultDestination(self
, args
):
1350 ## TODO: use common prefix of args?
1352 depotDir
= re
.sub("(@[^@]*)$", "", depotPath
)
1353 depotDir
= re
.sub("(#[^#]*)$", "", depotDir
)
1354 depotDir
= re
.sub(r
"\.\.\.$,", "", depotDir
)
1355 depotDir
= re
.sub(r
"/$", "", depotDir
)
1356 return os
.path
.split(depotDir
)[1]
1358 def run(self
, args
):
1362 if self
.keepRepoPath
and not self
.cloneDestination
:
1363 sys
.stderr
.write("Must specify destination for --keep-path\n")
1367 for p
in depotPaths
:
1368 if not p
.startswith("//"):
1371 if not self
.cloneDestination
:
1372 self
.cloneDestination
= self
.defaultDestination()
1374 print "Importing from %s into %s" % (', '.join(depotPaths
), self
.cloneDestination
)
1375 os
.makedirs(self
.cloneDestination
)
1376 os
.chdir(self
.cloneDestination
)
1378 self
.gitdir
= os
.getcwd() + "/.git"
1379 if not P4Sync
.run(self
, depotPaths
):
1381 if self
.branch
!= "master":
1382 if gitBranchExists("refs/remotes/p4/master"):
1383 system("git branch master refs/remotes/p4/master")
1384 system("git checkout -f")
1386 print "Could not detect main branch. No checkout/master branch created."
1390 class HelpFormatter(optparse
.IndentedHelpFormatter
):
1392 optparse
.IndentedHelpFormatter
.__init
__(self
)
1394 def format_description(self
, description
):
1396 return description
+ "\n"
1400 def printUsage(commands
):
1401 print "usage: %s <command> [options]" % sys
.argv
[0]
1403 print "valid commands: %s" % ", ".join(commands
)
1405 print "Try %s <command> --help for command specific help." % sys
.argv
[0]
1410 "submit" : P4Submit
,
1412 "rebase" : P4Rebase
,
1414 "rollback" : P4RollBack
1419 if len(sys
.argv
[1:]) == 0:
1420 printUsage(commands
.keys())
1424 cmdName
= sys
.argv
[1]
1426 klass
= commands
[cmdName
]
1429 print "unknown command %s" % cmdName
1431 printUsage(commands
.keys())
1434 options
= cmd
.options
1435 cmd
.gitdir
= os
.environ
.get("GIT_DIR", None)
1439 if len(options
) > 0:
1440 options
.append(optparse
.make_option("--git-dir", dest
="gitdir"))
1442 parser
= optparse
.OptionParser(cmd
.usage
.replace("%prog", "%prog " + cmdName
),
1444 description
= cmd
.description
,
1445 formatter
= HelpFormatter())
1447 (cmd
, args
) = parser
.parse_args(sys
.argv
[2:], cmd
);
1449 verbose
= cmd
.verbose
1451 if cmd
.gitdir
== None:
1452 cmd
.gitdir
= os
.path
.abspath(".git")
1453 if not isValidGitDir(cmd
.gitdir
):
1454 cmd
.gitdir
= read_pipe("git rev-parse --git-dir").strip()
1455 if os
.path
.exists(cmd
.gitdir
):
1456 cdup
= read_pipe("git rev-parse --show-cdup").strip()
1460 if not isValidGitDir(cmd
.gitdir
):
1461 if isValidGitDir(cmd
.gitdir
+ "/.git"):
1462 cmd
.gitdir
+= "/.git"
1464 die("fatal: cannot locate git repository at %s" % cmd
.gitdir
)
1466 os
.environ
["GIT_DIR"] = cmd
.gitdir
1468 if not cmd
.run(args
):
1472 if __name__
== '__main__':