index 05b308f5be19f1aad5bf45b4215a6bdbc5eb54ec..794286ee8e43394c93c0aae66d540efc2da8d26e 100755 (executable)
import optparse, sys, os, marshal, popen2, subprocess, shelve
import tempfile, getopt, sha, os.path, time, platform
import re
+
from sets import Set;
gitdir = os.environ.get("GIT_DIR", "")
-silent = False
+silent = True
-def write_pipe (c, str):
+def write_pipe(c, str):
if not silent:
- sys.stderr.write ('writing pipe: %s\n' % c)
+ sys.stderr.write('writing pipe: %s\n' % c)
- ## todo: check return status
- pipe = os.popen (c, 'w')
+ pipe = os.popen(c, 'w')
val = pipe.write(str)
- if pipe.close ():
- sys.stderr.write ('Command failed')
- sys.exit (1)
+ if pipe.close():
+ sys.stderr.write('Command failed: %s' % c)
+ sys.exit(1)
return val
-def read_pipe (c):
- sys.stderr.write ('reading pipe: %s\n' % c)
- ## todo: check return status
- pipe = os.popen (c, 'rb')
+def read_pipe(c):
+ if not silent:
+ sys.stderr.write('reading pipe: %s\n' % c)
+
+ pipe = os.popen(c, 'rb')
val = pipe.read()
- if pipe.close ():
- sys.stderr.write ('Command failed')
- sys.exit (1)
+ if pipe.close():
+ sys.stderr.write('Command failed: %s' % c)
+ sys.exit(1)
return val
-def read_pipe_lines (c):
- sys.stderr.write ('reading pipe: %s\n' % c)
+def read_pipe_lines(c):
+ if not silent:
+ sys.stderr.write('reading pipe: %s\n' % c)
## todo: check return status
- pipe = os.popen (c, 'rb')
+ pipe = os.popen(c, 'rb')
val = pipe.readlines()
- if pipe.close ():
- sys.stderr.write ('Command failed')
- sys.exit (1)
+ if pipe.close():
+ sys.stderr.write('Command failed: %s' % c)
+ sys.exit(1)
return val
+def system(cmd):
+ if not silent:
+ sys.stderr.write("executing %s" % cmd)
+ if os.system(cmd) != 0:
+ die("command failed: %s" % cmd)
+
def p4CmdList(cmd):
cmd = "p4 -G %s" % cmd
pipe = os.popen(cmd, "rb")
sys.exit(1)
def currentGitBranch():
- return read_pipe("git name-rev HEAD").split(" ")[1][:-1]
+ return read_pipe("git name-rev HEAD").split(" ")[1].strip()
def isValidGitDir(path):
if os.path.exists(path + "/HEAD") and os.path.exists(path + "/refs") and os.path.exists(path + "/objects"):
return False
def parseRevision(ref):
- return read_pipe("git rev-parse %s" % ref)[:-1]
-
-def system(cmd):
- if os.system(cmd) != 0:
- die("command failed: %s" % cmd)
+ return read_pipe("git rev-parse %s" % ref).strip()
def extractLogMessageFromGitCommit(commit):
logMessage = ""
return proc.wait() == 0;
def gitConfig(key):
- return mypopen("git config %s" % key).read()[:-1]
+ return os.popen("git config %s" % key, "rb").read()[:-1]
class Command:
def __init__(self):
for line in lines:
if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
- ref = refPrefix + line[:-1]
+ line = line.strip()
+ ref = refPrefix + line
log = extractLogMessageFromGitCommit(ref)
depotPath, change = extractDepotPathAndChangeFromGitLog(log)
changed = False
commits.append("0")
else:
for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
- commits.append(line[:-1])
+ commits.append(line.strip())
commits.reverse()
self.config["commits"] = commits
if not self.directSubmit:
logMessage = extractLogMessageFromGitCommit(id)
logMessage = logMessage.replace("\n", "\n\t")
- logMessage = logMessage[:-1]
+ logMessage = logMessage.strip()
template = read_pipe("p4 change -o")
if len(self.substFile) > 0:
for line in open(self.substFile, "r").readlines():
- tokens = line[:-1].split("=")
+ tokens = line.strip().split("=")
self.logSubstitutions[tokens[0]] = tokens[1]
self.check()
optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
optparse.make_option("--verbose", dest="verbose", action="store_true"),
optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false"),
- optparse.make_option("--max-changes", dest="maxChanges")
+ optparse.make_option("--max-changes", dest="maxChanges"),
+ optparse.make_option("--keep-path", dest="keepRepoPath")
]
self.description = """Imports from Perforce into a git repository.\n
example:
(a ... is not needed in the path p4 specification, it's added implicitly)"""
self.usage += " //depot/path[@revRange]"
-
self.silent = False
self.createdBranches = Set()
self.committedChanges = Set()
self.importIntoRemotes = True
self.maxChanges = ""
self.isWindows = (platform.system() == "Windows")
+ self.depotPath = None
+ self.keepRepoPath = False
if gitConfig("git-p4.syncFromOrigin") == "false":
self.syncWithOrigin = False
fnum = fnum + 1
return files
+ def stripRepoPath(self, path, prefix):
+ if self.keepRepoPath:
+ prefix = re.sub("^(//[^/]+/).*", r'\1', prefix)
+
+ return path[len(prefix):]
+
def splitFilesIntoBranches(self, commit):
branches = {}
-
fnum = 0
while commit.has_key("depotFile%s" % fnum):
path = commit["depotFile%s" % fnum]
file["type"] = commit["type%s" % fnum]
fnum = fnum + 1
- relPath = path[len(self.depotPath):]
+ relPath = self.stripRepoPath(path, self.depotPath)
for branch in self.knownBranches.keys():
- if relPath.startswith(branch + "/"): # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
+
+ # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
+ if relPath.startswith(branch + "/"):
if branch not in branches:
branches[branch] = []
branches[branch].append(file)
continue
rev = file["rev"]
depotPath = path + "#" + rev
- relPath = path[len(branchPrefix):]
+ relPath = self.stripRepoPath(path, branchPrefix)
action = file["action"]
if file["type"] == "apple":
lines = cache.readlines()
cache.close()
for line in lines:
- entry = line[:-1].split("\t")
+ entry = line.strip().split("\t")
self.users[entry[0]] = entry[1]
except IOError:
self.getUserMapFromPerforceServer()
print "Label changes: %s" % self.labels.keys()
def getBranchMapping(self):
- self.projectName = self.depotPath[self.depotPath[:-1].rfind("/") + 1:]
+ self.projectName = self.depotPath[self.depotPath.strip().rfind("/") + 1:]
for info in p4CmdList("branches"):
details = p4Cmd("branch -o %s" % info["branch"])
cmdline += " --branches"
for line in read_pipe_lines(cmdline):
- if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD\n"):
+ line = line.strip()
+ if self.importIntoRemotes and ((not line.startswith("p4/")) or line == "p4/HEAD"):
continue
+
if self.importIntoRemotes:
# strip off p4
- branch = line[3:-1]
- else:
- branch = line[:-1]
+ branch = re.sub ("^p4/", "", line)
+
self.p4BranchesInGit.append(branch)
- self.initialParents[self.refPrefix + branch] = parseRevision(line[:-1])
+ self.initialParents[self.refPrefix + branch] = parseRevision(line)
def createOrUpdateBranchesFromOrigin(self):
if not self.silent:
print "Creating/updating branch(es) in %s based on origin branch(es)" % self.refPrefix
- for line in mypopen("git rev-parse --symbolic --remotes"):
+ for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
if (not line.startswith("origin/")) or line.endswith("HEAD\n"):
continue
self.branch = "refs/heads/" + self.branch
if len(self.depotPath) != 0:
- self.depotPath = self.depotPath[:-1]
+ self.depotPath = self.depotPath.strip()
if len(args) == 0 and len(self.depotPath) != 0:
if not self.silent:
elif len(self.previousDepotPath) == 0:
self.revision = "#head"
- if self.depotPath.endswith("..."):
- self.depotPath = self.depotPath[:-3]
-
+ self.depotPath = re.sub ("\.\.\.$", "", self.depotPath)
if not self.depotPath.endswith("/"):
self.depotPath += "/"
sync = P4Sync()
sync.run([])
print "Rebasing the current branch"
- oldHead = read_pipe("git rev-parse HEAD")[:-1]
+ oldHead = read_pipe("git rev-parse HEAD").strip()
system("git rebase p4")
system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
return True
depotDir = re.sub(r"/$", "", depotDir)
if not destination:
- destination = os.path.split(depotDir)[-1]
+ destination = os.path.split(depotDir)[1]
print "Importing from %s into %s" % (depotPath, destination)
os.makedirs(destination)
if len(gitdir) == 0:
gitdir = ".git"
if not isValidGitDir(gitdir):
- gitdir = read_pipe("git rev-parse --git-dir")[:-1]
+ gitdir = read_pipe("git rev-parse --git-dir").strip()
if os.path.exists(gitdir):
- cdup = read_pipe("git rev-parse --show-cdup")[:-1];
+ cdup = read_pipe("git rev-parse --show-cdup").strip()
if len(cdup) > 0:
os.chdir(cdup);