blob: 2040591383e93db3544b50a118f8151062591d3d [file] [log] [blame]
Simon Hausmann86949ee2007-03-19 20:59:12 +01001#!/usr/bin/env python
2#
3# git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
4#
Simon Hausmannc8cbbee2007-05-28 14:43:25 +02005# Author: Simon Hausmann <simon@lst.de>
6# Copyright: 2007 Simon Hausmann <simon@lst.de>
Simon Hausmann83dce552007-03-19 22:26:36 +01007# 2007 Trolltech ASA
Simon Hausmann86949ee2007-03-19 20:59:12 +01008# License: MIT <http://www.opensource.org/licenses/mit-license.php>
9#
10
Simon Hausmann08483582007-05-15 14:31:06 +020011import optparse, sys, os, marshal, popen2, subprocess, shelve
Simon Hausmann25df95c2007-05-15 15:15:39 +020012import tempfile, getopt, sha, os.path, time, platform
Han-Wen Nienhuysce6f33c2007-05-23 16:46:29 -030013import re
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -030014
Simon Hausmannb9847332007-03-20 20:54:23 +010015from sets import Set;
Simon Hausmann4f5cf762007-03-19 22:25:17 +010016
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030017verbose = False
Simon Hausmann86949ee2007-03-19 20:59:12 +010018
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030019def die(msg):
20 if verbose:
21 raise Exception(msg)
22 else:
23 sys.stderr.write(msg + "\n")
24 sys.exit(1)
25
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -030026def write_pipe(c, str):
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030027 if verbose:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030028 sys.stderr.write('Writing pipe: %s\n' % c)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030029
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -030030 pipe = os.popen(c, 'w')
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030031 val = pipe.write(str)
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -030032 if pipe.close():
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030033 die('Command failed: %s' % c)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030034
35 return val
36
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030037def read_pipe(c, ignore_error=False):
38 if verbose:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030039 sys.stderr.write('Reading pipe: %s\n' % c)
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -030040
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -030041 pipe = os.popen(c, 'rb')
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030042 val = pipe.read()
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030043 if pipe.close() and not ignore_error:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030044 die('Command failed: %s' % c)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030045
46 return val
47
48
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -030049def read_pipe_lines(c):
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030050 if verbose:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030051 sys.stderr.write('Reading pipe: %s\n' % c)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030052 ## todo: check return status
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -030053 pipe = os.popen(c, 'rb')
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030054 val = pipe.readlines()
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -030055 if pipe.close():
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030056 die('Command failed: %s' % c)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030057
58 return val
Simon Hausmanncaace112007-05-15 14:57:57 +020059
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -030060def system(cmd):
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030061 if verbose:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -030062 sys.stderr.write("executing %s\n" % cmd)
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -030063 if os.system(cmd) != 0:
64 die("command failed: %s" % cmd)
65
Simon Hausmann86949ee2007-03-19 20:59:12 +010066def p4CmdList(cmd):
67 cmd = "p4 -G %s" % cmd
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -030068 if verbose:
69 sys.stderr.write("Opening pipe: %s\n" % cmd)
Simon Hausmann86949ee2007-03-19 20:59:12 +010070 pipe = os.popen(cmd, "rb")
71
72 result = []
73 try:
74 while True:
75 entry = marshal.load(pipe)
76 result.append(entry)
77 except EOFError:
78 pass
Simon Hausmanna6d5da32007-05-23 23:27:31 +020079 exitCode = pipe.close()
80 if exitCode != None:
Simon Hausmannac3e0d72007-05-23 23:32:32 +020081 entry = {}
82 entry["p4ExitCode"] = exitCode
83 result.append(entry)
Simon Hausmann86949ee2007-03-19 20:59:12 +010084
85 return result
86
87def p4Cmd(cmd):
88 list = p4CmdList(cmd)
89 result = {}
90 for entry in list:
91 result.update(entry)
92 return result;
93
Simon Hausmanncb2c9db2007-03-24 09:15:11 +010094def p4Where(depotPath):
95 if not depotPath.endswith("/"):
96 depotPath += "/"
97 output = p4Cmd("where %s..." % depotPath)
Simon Hausmanndc524032007-05-21 09:34:56 +020098 if output["code"] == "error":
99 return ""
Simon Hausmanncb2c9db2007-03-24 09:15:11 +0100100 clientPath = ""
101 if "path" in output:
102 clientPath = output.get("path")
103 elif "data" in output:
104 data = output.get("data")
105 lastSpace = data.rfind(" ")
106 clientPath = data[lastSpace + 1:]
107
108 if clientPath.endswith("..."):
109 clientPath = clientPath[:-3]
110 return clientPath
111
Simon Hausmann86949ee2007-03-19 20:59:12 +0100112def currentGitBranch():
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300113 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
Simon Hausmann86949ee2007-03-19 20:59:12 +0100114
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100115def isValidGitDir(path):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300116 if (os.path.exists(path + "/HEAD")
117 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100118 return True;
119 return False
120
Simon Hausmann463e8af2007-05-17 09:13:54 +0200121def parseRevision(ref):
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300122 return read_pipe("git rev-parse %s" % ref).strip()
Simon Hausmann463e8af2007-05-17 09:13:54 +0200123
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100124def extractLogMessageFromGitCommit(commit):
125 logMessage = ""
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300126
127 ## fixme: title is first line of commit, not 1st paragraph.
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100128 foundTitle = False
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300129 for log in read_pipe_lines("git cat-file commit %s" % commit):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100130 if not foundTitle:
131 if len(log) == 1:
Simon Hausmann1c094182007-05-01 23:15:48 +0200132 foundTitle = True
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100133 continue
134
135 logMessage += log
136 return logMessage
137
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300138def extractSettingsGitLog(log):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100139 values = {}
140 for line in log.split("\n"):
141 line = line.strip()
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300142 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
143 if not m:
144 continue
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100145
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300146 assignments = m.group(1).split (':')
147 for a in assignments:
148 vals = a.split ('=')
149 key = vals[0].strip()
150 val = ('='.join (vals[1:])).strip()
151 if val.endswith ('\"') and val.startswith('"'):
152 val = val[1:-1]
153
154 values[key] = val
155
Simon Hausmann845b42c2007-06-07 09:19:34 +0200156 paths = values.get("depot-paths")
157 if not paths:
158 paths = values.get("depot-path")
Simon Hausmanna3fdd572007-06-07 22:54:32 +0200159 if paths:
160 values['depot-paths'] = paths.split(',')
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300161 return values
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100162
Simon Hausmann8136a632007-03-22 21:27:14 +0100163def gitBranchExists(branch):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300164 proc = subprocess.Popen(["git", "rev-parse", branch],
165 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
Simon Hausmanncaace112007-05-15 14:57:57 +0200166 return proc.wait() == 0;
Simon Hausmann8136a632007-03-22 21:27:14 +0100167
Simon Hausmann01265102007-05-25 10:36:10 +0200168def gitConfig(key):
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300169 return read_pipe("git config %s" % key, ignore_error=True).strip()
Simon Hausmann01265102007-05-25 10:36:10 +0200170
Simon Hausmann27d2d812007-06-12 14:31:59 +0200171def findUpstreamBranchPoint():
172 settings = None
173 branchPoint = ""
174 parent = 0
175 while parent < 65535:
176 commit = "HEAD~%s" % parent
177 log = extractLogMessageFromGitCommit(commit)
178 settings = extractSettingsGitLog(log)
179 if not settings.has_key("depot-paths"):
180 parent = parent + 1
181 continue
182
Marius Storm-Olsencbae7082007-06-12 15:27:52 +0200183 names = read_pipe_lines("git name-rev \"--refs=refs/remotes/p4/*\" \"%s\"" % commit)
Simon Hausmann27d2d812007-06-12 14:31:59 +0200184 if len(names) <= 0:
185 continue
186
187 # strip away the beginning of 'HEAD~42 refs/remotes/p4/foo'
188 branchPoint = names[0].strip()[len(commit) + 1:]
189 break
190
191 return [branchPoint, settings]
192
Simon Hausmannb9847332007-03-20 20:54:23 +0100193class Command:
194 def __init__(self):
195 self.usage = "usage: %prog [options]"
Simon Hausmann8910ac02007-03-26 08:18:55 +0200196 self.needsGit = True
Simon Hausmannb9847332007-03-20 20:54:23 +0100197
198class P4Debug(Command):
Simon Hausmann86949ee2007-03-19 20:59:12 +0100199 def __init__(self):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100200 Command.__init__(self)
Simon Hausmann86949ee2007-03-19 20:59:12 +0100201 self.options = [
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300202 optparse.make_option("--verbose", dest="verbose", action="store_true",
203 default=False),
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300204 ]
Simon Hausmannc8c39112007-03-19 21:02:30 +0100205 self.description = "A tool to debug the output of p4 -G."
Simon Hausmann8910ac02007-03-26 08:18:55 +0200206 self.needsGit = False
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300207 self.verbose = False
Simon Hausmann86949ee2007-03-19 20:59:12 +0100208
209 def run(self, args):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300210 j = 0
Simon Hausmann86949ee2007-03-19 20:59:12 +0100211 for output in p4CmdList(" ".join(args)):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300212 print 'Element: %d' % j
213 j += 1
Simon Hausmann86949ee2007-03-19 20:59:12 +0100214 print output
Simon Hausmannb9847332007-03-20 20:54:23 +0100215 return True
Simon Hausmann86949ee2007-03-19 20:59:12 +0100216
Simon Hausmann58346842007-05-21 22:57:06 +0200217class P4RollBack(Command):
218 def __init__(self):
219 Command.__init__(self)
220 self.options = [
Simon Hausmann0c66a782007-05-23 20:07:57 +0200221 optparse.make_option("--verbose", dest="verbose", action="store_true"),
222 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
Simon Hausmann58346842007-05-21 22:57:06 +0200223 ]
224 self.description = "A tool to debug the multi-branch import. Don't use :)"
Simon Hausmann52102d42007-05-21 23:44:24 +0200225 self.verbose = False
Simon Hausmann0c66a782007-05-23 20:07:57 +0200226 self.rollbackLocalBranches = False
Simon Hausmann58346842007-05-21 22:57:06 +0200227
228 def run(self, args):
229 if len(args) != 1:
230 return False
231 maxChange = int(args[0])
Simon Hausmann0c66a782007-05-23 20:07:57 +0200232
Simon Hausmannad192f22007-05-23 23:44:19 +0200233 if "p4ExitCode" in p4Cmd("changes -m 1"):
Simon Hausmann66a2f522007-05-23 23:40:48 +0200234 die("Problems executing p4");
235
Simon Hausmann0c66a782007-05-23 20:07:57 +0200236 if self.rollbackLocalBranches:
237 refPrefix = "refs/heads/"
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300238 lines = read_pipe_lines("git rev-parse --symbolic --branches")
Simon Hausmann0c66a782007-05-23 20:07:57 +0200239 else:
240 refPrefix = "refs/remotes/"
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300241 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
Simon Hausmann0c66a782007-05-23 20:07:57 +0200242
243 for line in lines:
244 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300245 line = line.strip()
246 ref = refPrefix + line
Simon Hausmann58346842007-05-21 22:57:06 +0200247 log = extractLogMessageFromGitCommit(ref)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300248 settings = extractSettingsGitLog(log)
249
250 depotPaths = settings['depot-paths']
251 change = settings['change']
252
Simon Hausmann58346842007-05-21 22:57:06 +0200253 changed = False
Simon Hausmann52102d42007-05-21 23:44:24 +0200254
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300255 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
256 for p in depotPaths]))) == 0:
Simon Hausmann52102d42007-05-21 23:44:24 +0200257 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
258 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
259 continue
260
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300261 while change and int(change) > maxChange:
Simon Hausmann58346842007-05-21 22:57:06 +0200262 changed = True
Simon Hausmann52102d42007-05-21 23:44:24 +0200263 if self.verbose:
264 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
Simon Hausmann58346842007-05-21 22:57:06 +0200265 system("git update-ref %s \"%s^\"" % (ref, ref))
266 log = extractLogMessageFromGitCommit(ref)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300267 settings = extractSettingsGitLog(log)
268
269
270 depotPaths = settings['depot-paths']
271 change = settings['change']
Simon Hausmann58346842007-05-21 22:57:06 +0200272
273 if changed:
Simon Hausmann52102d42007-05-21 23:44:24 +0200274 print "%s rewound to %s" % (ref, change)
Simon Hausmann58346842007-05-21 22:57:06 +0200275
276 return True
277
Simon Hausmann711544b2007-04-01 15:40:46 +0200278class P4Submit(Command):
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100279 def __init__(self):
Simon Hausmannb9847332007-03-20 20:54:23 +0100280 Command.__init__(self)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100281 self.options = [
282 optparse.make_option("--continue", action="store_false", dest="firstTime"),
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300283 optparse.make_option("--verbose", dest="verbose", action="store_true"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100284 optparse.make_option("--origin", dest="origin"),
285 optparse.make_option("--reset", action="store_true", dest="reset"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100286 optparse.make_option("--log-substitutions", dest="substFile"),
Simon Hausmann04219c02007-03-21 10:11:20 +0100287 optparse.make_option("--dry-run", action="store_true"),
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200288 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
Simon Hausmanncb4f1282007-05-25 22:34:30 +0200289 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100290 ]
291 self.description = "Submit changes from git to the perforce depot."
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200292 self.usage += " [name of git branch to submit into perforce depot]"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100293 self.firstTime = True
294 self.reset = False
295 self.interactive = True
296 self.dryRun = False
297 self.substFile = ""
298 self.firstTime = True
Simon Hausmann95124972007-03-23 09:16:07 +0100299 self.origin = ""
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200300 self.directSubmit = False
Simon Hausmanncb4f1282007-05-25 22:34:30 +0200301 self.trustMeLikeAFool = False
Simon Hausmannb0d10df2007-06-07 13:09:14 +0200302 self.verbose = False
Marius Storm-Olsenf7baba82007-06-07 14:07:01 +0200303 self.isWindows = (platform.system() == "Windows")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100304
305 self.logSubstitutions = {}
306 self.logSubstitutions["<enter description here>"] = "%log%"
307 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
308
309 def check(self):
310 if len(p4CmdList("opened ...")) > 0:
311 die("You have files opened with perforce! Close them before starting the sync.")
312
313 def start(self):
314 if len(self.config) > 0 and not self.reset:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300315 die("Cannot start sync. Previous sync config found at %s\n"
316 "If you want to start submitting again from scratch "
317 "maybe you want to call git-p4 submit --reset" % self.configFile)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100318
319 commits = []
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200320 if self.directSubmit:
321 commits.append("0")
322 else:
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300323 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300324 commits.append(line.strip())
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200325 commits.reverse()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100326
327 self.config["commits"] = commits
328
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100329 def prepareLogMessage(self, template, message):
330 result = ""
331
332 for line in template.split("\n"):
333 if line.startswith("#"):
334 result += line + "\n"
335 continue
336
337 substituted = False
338 for key in self.logSubstitutions.keys():
339 if line.find(key) != -1:
340 value = self.logSubstitutions[key]
341 value = value.replace("%log%", message)
342 if value != "@remove@":
343 result += line.replace(key, value) + "\n"
344 substituted = True
345 break
346
347 if not substituted:
348 result += line + "\n"
349
350 return result
351
Han-Wen Nienhuys7cb5cbe2007-05-23 16:55:48 -0300352 def applyCommit(self, id):
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200353 if self.directSubmit:
354 print "Applying local change in working directory/index"
355 diff = self.diffStatus
356 else:
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300357 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
358 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100359 filesToAdd = set()
360 filesToDelete = set()
Simon Hausmannd336c152007-05-16 09:41:26 +0200361 editedFiles = set()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100362 for line in diff:
363 modifier = line[0]
364 path = line[1:].strip()
365 if modifier == "M":
Simon Hausmannd336c152007-05-16 09:41:26 +0200366 system("p4 edit \"%s\"" % path)
367 editedFiles.add(path)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100368 elif modifier == "A":
369 filesToAdd.add(path)
370 if path in filesToDelete:
371 filesToDelete.remove(path)
372 elif modifier == "D":
373 filesToDelete.add(path)
374 if path in filesToAdd:
375 filesToAdd.remove(path)
376 else:
377 die("unknown modifier %s for %s" % (modifier, path))
378
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200379 if self.directSubmit:
380 diffcmd = "cat \"%s\"" % self.diffFile
381 else:
382 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
Simon Hausmann47a130b2007-05-20 16:33:21 +0200383 patchcmd = diffcmd + " | git apply "
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200384 tryPatchCmd = patchcmd + "--check -"
385 applyPatchCmd = patchcmd + "--check --apply -"
Simon Hausmann51a26402007-04-15 09:59:56 +0200386
Simon Hausmann47a130b2007-05-20 16:33:21 +0200387 if os.system(tryPatchCmd) != 0:
Simon Hausmann51a26402007-04-15 09:59:56 +0200388 print "Unfortunately applying the change failed!"
389 print "What do you want to do?"
390 response = "x"
391 while response != "s" and response != "a" and response != "w":
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300392 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
393 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
Simon Hausmann51a26402007-04-15 09:59:56 +0200394 if response == "s":
395 print "Skipping! Good luck with the next patches..."
396 return
397 elif response == "a":
Simon Hausmann47a130b2007-05-20 16:33:21 +0200398 os.system(applyPatchCmd)
Simon Hausmann51a26402007-04-15 09:59:56 +0200399 if len(filesToAdd) > 0:
400 print "You may also want to call p4 add on the following files:"
401 print " ".join(filesToAdd)
402 if len(filesToDelete):
403 print "The following files should be scheduled for deletion with p4 delete:"
404 print " ".join(filesToDelete)
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300405 die("Please resolve and submit the conflict manually and "
406 + "continue afterwards with git-p4 submit --continue")
Simon Hausmann51a26402007-04-15 09:59:56 +0200407 elif response == "w":
408 system(diffcmd + " > patch.txt")
409 print "Patch saved to patch.txt in %s !" % self.clientPath
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300410 die("Please resolve and submit the conflict manually and "
411 "continue afterwards with git-p4 submit --continue")
Simon Hausmann51a26402007-04-15 09:59:56 +0200412
Simon Hausmann47a130b2007-05-20 16:33:21 +0200413 system(applyPatchCmd)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100414
415 for f in filesToAdd:
Simon Hausmanne6b711f2007-06-11 23:40:25 +0200416 system("p4 add \"%s\"" % f)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100417 for f in filesToDelete:
Simon Hausmanne6b711f2007-06-11 23:40:25 +0200418 system("p4 revert \"%s\"" % f)
419 system("p4 delete \"%s\"" % f)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100420
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200421 logMessage = ""
422 if not self.directSubmit:
423 logMessage = extractLogMessageFromGitCommit(id)
424 logMessage = logMessage.replace("\n", "\n\t")
Marius Storm-Olsenf7baba82007-06-07 14:07:01 +0200425 if self.isWindows:
426 logMessage = logMessage.replace("\n", "\r\n")
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300427 logMessage = logMessage.strip()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100428
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300429 template = read_pipe("p4 change -o")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100430
431 if self.interactive:
432 submitTemplate = self.prepareLogMessage(template, logMessage)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300433 diff = read_pipe("p4 diff -du ...")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100434
435 for newFile in filesToAdd:
436 diff += "==== new file ====\n"
437 diff += "--- /dev/null\n"
438 diff += "+++ %s\n" % newFile
439 f = open(newFile, "r")
440 for line in f.readlines():
441 diff += "+" + line
442 f.close()
443
Simon Hausmann25df95c2007-05-15 15:15:39 +0200444 separatorLine = "######## everything below this line is just the diff #######"
445 if platform.system() == "Windows":
446 separatorLine += "\r"
447 separatorLine += "\n"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100448
449 response = "e"
Simon Hausmanncb4f1282007-05-25 22:34:30 +0200450 if self.trustMeLikeAFool:
451 response = "y"
452
Simon Hausmann53150252007-03-21 21:04:12 +0100453 firstIteration = True
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100454 while response == "e":
Simon Hausmann53150252007-03-21 21:04:12 +0100455 if not firstIteration:
Simon Hausmannd336c152007-05-16 09:41:26 +0200456 response = raw_input("Do you want to submit this change? [y]es/[e]dit/[n]o/[s]kip ")
Simon Hausmann53150252007-03-21 21:04:12 +0100457 firstIteration = False
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100458 if response == "e":
459 [handle, fileName] = tempfile.mkstemp()
460 tmpFile = os.fdopen(handle, "w+")
Simon Hausmann53150252007-03-21 21:04:12 +0100461 tmpFile.write(submitTemplate + separatorLine + diff)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100462 tmpFile.close()
Simon Hausmann25df95c2007-05-15 15:15:39 +0200463 defaultEditor = "vi"
464 if platform.system() == "Windows":
465 defaultEditor = "notepad"
466 editor = os.environ.get("EDITOR", defaultEditor);
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100467 system(editor + " " + fileName)
Simon Hausmann25df95c2007-05-15 15:15:39 +0200468 tmpFile = open(fileName, "rb")
Simon Hausmann53150252007-03-21 21:04:12 +0100469 message = tmpFile.read()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100470 tmpFile.close()
471 os.remove(fileName)
Simon Hausmann53150252007-03-21 21:04:12 +0100472 submitTemplate = message[:message.index(separatorLine)]
Marius Storm-Olsenf7baba82007-06-07 14:07:01 +0200473 if self.isWindows:
474 submitTemplate = submitTemplate.replace("\r\n", "\n")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100475
476 if response == "y" or response == "yes":
477 if self.dryRun:
478 print submitTemplate
479 raw_input("Press return to continue...")
480 else:
Simon Hausmann7944f142007-05-21 11:04:26 +0200481 if self.directSubmit:
482 print "Submitting to git first"
483 os.chdir(self.oldWorkingDirectory)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300484 write_pipe("git commit -a -F -", submitTemplate)
Simon Hausmann7944f142007-05-21 11:04:26 +0200485 os.chdir(self.clientPath)
486
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300487 write_pipe("p4 submit -i", submitTemplate)
Simon Hausmannd336c152007-05-16 09:41:26 +0200488 elif response == "s":
489 for f in editedFiles:
490 system("p4 revert \"%s\"" % f);
491 for f in filesToAdd:
492 system("p4 revert \"%s\"" % f);
493 system("rm %s" %f)
494 for f in filesToDelete:
495 system("p4 delete \"%s\"" % f);
496 return
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100497 else:
498 print "Not submitting!"
499 self.interactive = False
500 else:
501 fileName = "submit.txt"
502 file = open(fileName, "w+")
503 file.write(self.prepareLogMessage(template, logMessage))
504 file.close()
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300505 print ("Perforce submit template written as %s. "
506 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
507 % (fileName, fileName))
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100508
509 def run(self, args):
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200510 if len(args) == 0:
511 self.master = currentGitBranch()
Simon Hausmann4280e532007-05-25 08:49:18 +0200512 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200513 die("Detecting current git branch failed!")
514 elif len(args) == 1:
515 self.master = args[0]
516 else:
517 return False
518
Simon Hausmann27d2d812007-06-12 14:31:59 +0200519 [upstream, settings] = findUpstreamBranchPoint()
520 depotPath = settings['depot-paths'][0]
521 if len(self.origin) == 0:
522 self.origin = upstream
Simon Hausmanna3fdd572007-06-07 22:54:32 +0200523
524 if self.verbose:
525 print "Origin branch is " + self.origin
Simon Hausmann95124972007-03-23 09:16:07 +0100526
527 if len(depotPath) == 0:
528 print "Internal error: cannot locate perforce depot path from existing branches"
529 sys.exit(128)
530
Simon Hausmann51a26402007-04-15 09:59:56 +0200531 self.clientPath = p4Where(depotPath)
Simon Hausmann95124972007-03-23 09:16:07 +0100532
Simon Hausmann51a26402007-04-15 09:59:56 +0200533 if len(self.clientPath) == 0:
Simon Hausmann95124972007-03-23 09:16:07 +0100534 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
535 sys.exit(128)
536
Simon Hausmann51a26402007-04-15 09:59:56 +0200537 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
Simon Hausmann7944f142007-05-21 11:04:26 +0200538 self.oldWorkingDirectory = os.getcwd()
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200539
540 if self.directSubmit:
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300541 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
Simon Hausmanncbf5efa2007-05-21 10:08:11 +0200542 if len(self.diffStatus) == 0:
543 print "No changes in working directory to submit."
544 return True
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300545 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -0300546 self.diffFile = self.gitdir + "/p4-git-diff"
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200547 f = open(self.diffFile, "wb")
548 f.write(patch)
549 f.close();
550
Simon Hausmann51a26402007-04-15 09:59:56 +0200551 os.chdir(self.clientPath)
552 response = raw_input("Do you want to sync %s with p4 sync? [y]es/[n]o " % self.clientPath)
Simon Hausmann95124972007-03-23 09:16:07 +0100553 if response == "y" or response == "yes":
554 system("p4 sync ...")
555
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100556 if self.reset:
557 self.firstTime = True
558
559 if len(self.substFile) > 0:
560 for line in open(self.substFile, "r").readlines():
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300561 tokens = line.strip().split("=")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100562 self.logSubstitutions[tokens[0]] = tokens[1]
563
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100564 self.check()
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -0300565 self.configFile = self.gitdir + "/p4-git-sync.cfg"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100566 self.config = shelve.open(self.configFile, writeback=True)
567
568 if self.firstTime:
569 self.start()
570
571 commits = self.config.get("commits", [])
572
573 while len(commits) > 0:
574 self.firstTime = False
575 commit = commits[0]
576 commits = commits[1:]
577 self.config["commits"] = commits
Han-Wen Nienhuys7cb5cbe2007-05-23 16:55:48 -0300578 self.applyCommit(commit)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100579 if not self.interactive:
580 break
581
582 self.config.close()
583
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200584 if self.directSubmit:
585 os.remove(self.diffFile)
586
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100587 if len(commits) == 0:
588 if self.firstTime:
589 print "No changes found to apply between %s and current HEAD" % self.origin
590 else:
591 print "All changes applied!"
Simon Hausmann7944f142007-05-21 11:04:26 +0200592 os.chdir(self.oldWorkingDirectory)
593 response = raw_input("Do you want to sync from Perforce now using git-p4 rebase? [y]es/[n]o ")
Simon Hausmann80b59102007-04-09 12:43:40 +0200594 if response == "y" or response == "yes":
Simon Hausmann80b59102007-04-09 12:43:40 +0200595 rebase = P4Rebase()
596 rebase.run([])
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100597 os.remove(self.configFile)
598
Simon Hausmannb9847332007-03-20 20:54:23 +0100599 return True
600
Simon Hausmann711544b2007-04-01 15:40:46 +0200601class P4Sync(Command):
Simon Hausmannb9847332007-03-20 20:54:23 +0100602 def __init__(self):
603 Command.__init__(self)
604 self.options = [
605 optparse.make_option("--branch", dest="branch"),
606 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
607 optparse.make_option("--changesfile", dest="changesFile"),
608 optparse.make_option("--silent", dest="silent", action="store_true"),
Simon Hausmannef48f902007-05-17 22:17:49 +0200609 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
Simon Hausmanna028a982007-05-23 00:03:08 +0200610 optparse.make_option("--verbose", dest="verbose", action="store_true"),
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300611 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
612 help="Import into refs/heads/ , not refs/remotes"),
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300613 optparse.make_option("--max-changes", dest="maxChanges"),
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300614 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
615 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
Simon Hausmannb9847332007-03-20 20:54:23 +0100616 ]
617 self.description = """Imports from Perforce into a git repository.\n
618 example:
619 //depot/my/project/ -- to import the current head
620 //depot/my/project/@all -- to import everything
621 //depot/my/project/@1,6 -- to import only from revision 1 to 6
622
623 (a ... is not needed in the path p4 specification, it's added implicitly)"""
624
625 self.usage += " //depot/path[@revRange]"
Simon Hausmannb9847332007-03-20 20:54:23 +0100626 self.silent = False
Simon Hausmannb9847332007-03-20 20:54:23 +0100627 self.createdBranches = Set()
628 self.committedChanges = Set()
Simon Hausmann569d1bd2007-03-22 21:34:16 +0100629 self.branch = ""
Simon Hausmannb9847332007-03-20 20:54:23 +0100630 self.detectBranches = False
Simon Hausmanncb53e1f2007-04-08 00:12:02 +0200631 self.detectLabels = False
Simon Hausmannb9847332007-03-20 20:54:23 +0100632 self.changesFile = ""
Simon Hausmann01265102007-05-25 10:36:10 +0200633 self.syncWithOrigin = True
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200634 self.verbose = False
Simon Hausmanna028a982007-05-23 00:03:08 +0200635 self.importIntoRemotes = True
Simon Hausmann01a9c9c2007-05-23 00:07:35 +0200636 self.maxChanges = ""
Marius Storm-Olsenc1f91972007-05-24 14:07:55 +0200637 self.isWindows = (platform.system() == "Windows")
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300638 self.keepRepoPath = False
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300639 self.depotPaths = None
Simon Hausmann3c699642007-06-16 13:09:21 +0200640 self.p4BranchesInGit = []
Simon Hausmannb9847332007-03-20 20:54:23 +0100641
Simon Hausmann01265102007-05-25 10:36:10 +0200642 if gitConfig("git-p4.syncFromOrigin") == "false":
643 self.syncWithOrigin = False
644
Simon Hausmannb9847332007-03-20 20:54:23 +0100645 def extractFilesFromCommit(self, commit):
646 files = []
647 fnum = 0
648 while commit.has_key("depotFile%s" % fnum):
649 path = commit["depotFile%s" % fnum]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300650
651 found = [p for p in self.depotPaths
652 if path.startswith (p)]
653 if not found:
Simon Hausmannb9847332007-03-20 20:54:23 +0100654 fnum = fnum + 1
655 continue
656
657 file = {}
658 file["path"] = path
659 file["rev"] = commit["rev%s" % fnum]
660 file["action"] = commit["action%s" % fnum]
661 file["type"] = commit["type%s" % fnum]
662 files.append(file)
663 fnum = fnum + 1
664 return files
665
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300666 def stripRepoPath(self, path, prefixes):
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300667 if self.keepRepoPath:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300668 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300669
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300670 for p in prefixes:
671 if path.startswith(p):
672 path = path[len(p):]
673
674 return path
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -0300675
Simon Hausmann71b112d2007-05-19 11:54:11 +0200676 def splitFilesIntoBranches(self, commit):
Simon Hausmannd5904672007-05-19 11:07:32 +0200677 branches = {}
Simon Hausmann71b112d2007-05-19 11:54:11 +0200678 fnum = 0
679 while commit.has_key("depotFile%s" % fnum):
680 path = commit["depotFile%s" % fnum]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300681 found = [p for p in self.depotPaths
682 if path.startswith (p)]
683 if not found:
Simon Hausmann71b112d2007-05-19 11:54:11 +0200684 fnum = fnum + 1
685 continue
686
687 file = {}
688 file["path"] = path
689 file["rev"] = commit["rev%s" % fnum]
690 file["action"] = commit["action%s" % fnum]
691 file["type"] = commit["type%s" % fnum]
692 fnum = fnum + 1
693
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300694 relPath = self.stripRepoPath(path, self.depotPaths)
Simon Hausmannb9847332007-03-20 20:54:23 +0100695
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200696 for branch in self.knownBranches.keys():
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -0300697
698 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
699 if relPath.startswith(branch + "/"):
Simon Hausmannd5904672007-05-19 11:07:32 +0200700 if branch not in branches:
701 branches[branch] = []
Simon Hausmann71b112d2007-05-19 11:54:11 +0200702 branches[branch].append(file)
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200703 break
Simon Hausmannb9847332007-03-20 20:54:23 +0100704
705 return branches
706
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300707 ## Should move this out, doesn't use SELF.
708 def readP4Files(self, files):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300709 files = [f for f in files
Han-Wen Nienhuys982bb8a2007-05-23 18:49:35 -0300710 if f['action'] != 'delete']
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300711
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300712 if not files:
Han-Wen Nienhuysf2eda792007-05-23 18:49:35 -0300713 return
714
Benjamin Sergeantda4a6602007-06-08 11:13:55 -0700715 # We cannot put all the files on the command line
716 # OS have limitations on the max lenght of arguments
717 # POSIX says it's 4096 bytes, default for Linux seems to be 130 K.
718 # and all OS from the table below seems to be higher than POSIX.
719 # See http://www.in-ulm.de/~mascheck/various/argmax/
720 argmax = min(4000, os.sysconf('SC_ARG_MAX'))
721 chunk = ''
722 filedata = []
723 for i in xrange(len(files)):
724 f = files[i]
725 chunk += '"%s#%s" ' % (f['path'], f['rev'])
726 if len(chunk) > argmax or i == len(files)-1:
727 data = p4CmdList('print %s' % chunk)
728 if "p4ExitCode" in data[0]:
729 die("Problems executing p4. Error: [%d]." % (data[0]['p4ExitCode']));
730 filedata.extend(data)
731 chunk = ''
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300732
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300733 j = 0;
734 contents = {}
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300735 while j < len(filedata):
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300736 stat = filedata[j]
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300737 j += 1
738 text = ''
Han-Wen Nienhuys7530a402007-05-23 18:49:35 -0300739 while j < len(filedata) and filedata[j]['code'] in ('text',
740 'binary'):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300741 text += filedata[j]['data']
742 j += 1
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300743
Han-Wen Nienhuys1b9a4682007-05-23 18:49:35 -0300744
745 if not stat.has_key('depotFile'):
746 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
747 continue
748
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300749 contents[stat['depotFile']] = text
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300750
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300751 for f in files:
752 assert not f.has_key('data')
753 f['data'] = contents[f['path']]
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300754
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300755 def commit(self, details, files, branch, branchPrefixes, parent = ""):
Simon Hausmannb9847332007-03-20 20:54:23 +0100756 epoch = details["time"]
757 author = details["user"]
758
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200759 if self.verbose:
760 print "commit into %s" % branch
761
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -0300762 # start with reading files; if that fails, we should not
763 # create a commit.
764 new_files = []
765 for f in files:
766 if [p for p in branchPrefixes if f['path'].startswith(p)]:
767 new_files.append (f)
768 else:
769 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
770 files = new_files
771 self.readP4Files(files)
772
773
774
775
Simon Hausmannb9847332007-03-20 20:54:23 +0100776 self.gitStream.write("commit %s\n" % branch)
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300777# gitStream.write("mark :%s\n" % details["change"])
Simon Hausmannb9847332007-03-20 20:54:23 +0100778 self.committedChanges.add(int(details["change"]))
779 committer = ""
Simon Hausmannb607e712007-05-20 10:55:54 +0200780 if author not in self.users:
781 self.getUserMapFromPerforceServer()
Simon Hausmannb9847332007-03-20 20:54:23 +0100782 if author in self.users:
Simon Hausmann0828ab12007-03-20 20:59:30 +0100783 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +0100784 else:
Simon Hausmann0828ab12007-03-20 20:59:30 +0100785 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +0100786
787 self.gitStream.write("committer %s\n" % committer)
788
789 self.gitStream.write("data <<EOT\n")
790 self.gitStream.write(details["desc"])
Simon Hausmann6581de02007-06-11 10:01:58 +0200791 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
792 % (','.join (branchPrefixes), details["change"]))
793 if len(details['options']) > 0:
794 self.gitStream.write(": options = %s" % details['options'])
795 self.gitStream.write("]\nEOT\n\n")
Simon Hausmannb9847332007-03-20 20:54:23 +0100796
797 if len(parent) > 0:
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200798 if self.verbose:
799 print "parent %s" % parent
Simon Hausmannb9847332007-03-20 20:54:23 +0100800 self.gitStream.write("from %s\n" % parent)
801
Simon Hausmannb9847332007-03-20 20:54:23 +0100802 for file in files:
Simon Hausmannb9847332007-03-20 20:54:23 +0100803 if file["type"] == "apple":
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300804 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
Simon Hausmannb9847332007-03-20 20:54:23 +0100805 continue
806
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300807 relPath = self.stripRepoPath(file['path'], branchPrefixes)
808 if file["action"] == "delete":
Simon Hausmannb9847332007-03-20 20:54:23 +0100809 self.gitStream.write("D %s\n" % relPath)
810 else:
811 mode = 644
812 if file["type"].startswith("x"):
813 mode = 755
814
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300815 data = file['data']
Simon Hausmannb9847332007-03-20 20:54:23 +0100816
Marius Storm-Olsenc1f91972007-05-24 14:07:55 +0200817 if self.isWindows and file["type"].endswith("text"):
818 data = data.replace("\r\n", "\n")
819
Han-Wen Nienhuys7530a402007-05-23 18:49:35 -0300820 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
Simon Hausmannb9847332007-03-20 20:54:23 +0100821 self.gitStream.write("data %s\n" % len(data))
822 self.gitStream.write(data)
823 self.gitStream.write("\n")
824
825 self.gitStream.write("\n")
826
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200827 change = int(details["change"])
828
Simon Hausmann9bda3a82007-05-19 12:05:40 +0200829 if self.labels.has_key(change):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200830 label = self.labels[change]
831 labelDetails = label[0]
832 labelRevisions = label[1]
Simon Hausmann71b112d2007-05-19 11:54:11 +0200833 if self.verbose:
834 print "Change %s is labelled %s" % (change, labelDetails)
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200835
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300836 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
837 for p in branchPrefixes]))
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200838
839 if len(files) == len(labelRevisions):
840
841 cleanedFiles = {}
842 for info in files:
843 if info["action"] == "delete":
844 continue
845 cleanedFiles[info["depotFile"]] = info["rev"]
846
847 if cleanedFiles == labelRevisions:
848 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
849 self.gitStream.write("from %s\n" % branch)
850
851 owner = labelDetails["Owner"]
852 tagger = ""
853 if author in self.users:
854 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
855 else:
856 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
857 self.gitStream.write("tagger %s\n" % tagger)
858 self.gitStream.write("data <<EOT\n")
859 self.gitStream.write(labelDetails["Description"])
860 self.gitStream.write("EOT\n\n")
861
862 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +0200863 if not self.silent:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300864 print ("Tag %s does not match with change %s: files do not match."
865 % (labelDetails["label"], change))
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200866
867 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +0200868 if not self.silent:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300869 print ("Tag %s does not match with change %s: file count is different."
870 % (labelDetails["label"], change))
Simon Hausmannb9847332007-03-20 20:54:23 +0100871
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300872 def getUserCacheFilename(self):
Han-Wen Nienhuysa3287be2007-05-23 18:49:35 -0300873 return os.environ["HOME"] + "/.gitp4-usercache.txt"
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300874
Simon Hausmannb607e712007-05-20 10:55:54 +0200875 def getUserMapFromPerforceServer(self):
Simon Hausmannebd81162007-05-24 00:24:52 +0200876 if self.userMapFromPerforceServer:
877 return
Simon Hausmannb9847332007-03-20 20:54:23 +0100878 self.users = {}
879
880 for output in p4CmdList("users"):
881 if not output.has_key("User"):
882 continue
883 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
884
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300885
886 s = ''
887 for (key, val) in self.users.items():
888 s += "%s\t%s\n" % (key, val)
889
890 open(self.getUserCacheFilename(), "wb").write(s)
Simon Hausmannebd81162007-05-24 00:24:52 +0200891 self.userMapFromPerforceServer = True
Simon Hausmannb607e712007-05-20 10:55:54 +0200892
893 def loadUserMapFromCache(self):
894 self.users = {}
Simon Hausmannebd81162007-05-24 00:24:52 +0200895 self.userMapFromPerforceServer = False
Simon Hausmannb607e712007-05-20 10:55:54 +0200896 try:
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300897 cache = open(self.getUserCacheFilename(), "rb")
Simon Hausmannb607e712007-05-20 10:55:54 +0200898 lines = cache.readlines()
899 cache.close()
900 for line in lines:
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300901 entry = line.strip().split("\t")
Simon Hausmannb607e712007-05-20 10:55:54 +0200902 self.users[entry[0]] = entry[1]
903 except IOError:
904 self.getUserMapFromPerforceServer()
905
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200906 def getLabels(self):
907 self.labels = {}
908
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300909 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
Simon Hausmann10c32112007-04-08 10:15:47 +0200910 if len(l) > 0 and not self.silent:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300911 print "Finding files belonging to labels in %s" % `self.depotPath`
Simon Hausmann01ce1fe2007-04-07 23:46:50 +0200912
913 for output in l:
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200914 label = output["label"]
915 revisions = {}
916 newestChange = 0
Simon Hausmann71b112d2007-05-19 11:54:11 +0200917 if self.verbose:
918 print "Querying files for label %s" % label
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300919 for file in p4CmdList("files "
920 + ' '.join (["%s...@%s" % (p, label)
921 for p in self.depotPaths])):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200922 revisions[file["depotFile"]] = file["rev"]
923 change = int(file["change"])
924 if change > newestChange:
925 newestChange = change
926
Simon Hausmann9bda3a82007-05-19 12:05:40 +0200927 self.labels[newestChange] = [output, revisions]
928
929 if self.verbose:
930 print "Label changes: %s" % self.labels.keys()
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200931
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300932 def guessProjectName(self):
933 for p in self.depotPaths:
Simon Hausmann6e5295c2007-06-11 08:50:57 +0200934 if p.endswith("/"):
935 p = p[:-1]
936 p = p[p.strip().rfind("/") + 1:]
937 if not p.endswith("/"):
938 p += "/"
939 return p
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300940
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200941 def getBranchMapping(self):
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200942 lostAndFoundBranches = set()
943
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200944 for info in p4CmdList("branches"):
945 details = p4Cmd("branch -o %s" % info["branch"])
946 viewIdx = 0
947 while details.has_key("View%s" % viewIdx):
948 paths = details["View%s" % viewIdx].split(" ")
949 viewIdx = viewIdx + 1
950 # require standard //depot/foo/... //depot/bar/... mapping
951 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
952 continue
953 source = paths[0]
954 destination = paths[1]
Simon Hausmann6509e192007-06-07 09:41:53 +0200955 ## HACK
956 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
957 source = source[len(self.depotPaths[0]):-4]
958 destination = destination[len(self.depotPaths[0]):-4]
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200959
Simon Hausmann1a2edf42007-06-17 15:10:24 +0200960 if destination in self.knownBranches:
961 if not self.silent:
962 print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
963 print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
964 continue
965
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200966 self.knownBranches[destination] = source
967
968 lostAndFoundBranches.discard(destination)
969
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200970 if source not in self.knownBranches:
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200971 lostAndFoundBranches.add(source)
972
973
974 for branch in lostAndFoundBranches:
975 self.knownBranches[branch] = branch
Simon Hausmann29bdbac2007-05-19 10:23:12 +0200976
977 def listExistingP4GitBranches(self):
978 self.p4BranchesInGit = []
979
Simon Hausmanna028a982007-05-23 00:03:08 +0200980 cmdline = "git rev-parse --symbolic "
981 if self.importIntoRemotes:
982 cmdline += " --remotes"
983 else:
984 cmdline += " --branches"
985
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300986 for line in read_pipe_lines(cmdline):
Simon Hausmanncfeb59b2007-05-28 19:24:57 +0200987 line = line.strip()
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300988
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300989 ## only import to p4/
Marius Storm-Olsenc4b33252007-06-07 15:28:04 +0200990 if not line.startswith('p4/') or line == "p4/HEAD":
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300991 continue
992 branch = line
Han-Wen Nienhuys5265bfc2007-05-23 18:49:35 -0300993
994 # strip off p4
995 branch = re.sub ("^p4/", "", line)
Han-Wen Nienhuysb76f0562007-05-23 18:29:34 -0300996
Simon Hausmann57284052007-05-23 00:15:50 +0200997 self.p4BranchesInGit.append(branch)
Han-Wen Nienhuysb76f0562007-05-23 18:29:34 -0300998 self.initialParents[self.refPrefix + branch] = parseRevision(line)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200999
Simon Hausmannabcd7902007-05-24 22:25:36 +02001000 def createOrUpdateBranchesFromOrigin(self):
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001001 if not self.silent:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001002 print ("Creating/updating branch(es) in %s based on origin branch(es)"
1003 % self.refPrefix)
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001004
Simon Hausmanncae7b732007-06-10 10:57:40 +02001005 originPrefix = "origin/p4/"
1006
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -03001007 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
1008 line = line.strip()
Simon Hausmanncae7b732007-06-10 10:57:40 +02001009 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001010 continue
Simon Hausmann65c5f3e2007-05-25 08:44:41 +02001011
Simon Hausmanncae7b732007-06-10 10:57:40 +02001012 headName = line[len(originPrefix):]
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001013 remoteHead = self.refPrefix + headName
Simon Hausmanncae7b732007-06-10 10:57:40 +02001014 originHead = line
Simon Hausmannabcd7902007-05-24 22:25:36 +02001015
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001016 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
1017 if (not original.has_key('depot-paths')
1018 or not original.has_key('change')):
Simon Hausmann65c5f3e2007-05-25 08:44:41 +02001019 continue
1020
Simon Hausmannabcd7902007-05-24 22:25:36 +02001021 update = False
Simon Hausmann4280e532007-05-25 08:49:18 +02001022 if not gitBranchExists(remoteHead):
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001023 if self.verbose:
1024 print "creating %s" % remoteHead
Simon Hausmannabcd7902007-05-24 22:25:36 +02001025 update = True
1026 else:
Simon Hausmanna3fdd572007-06-07 22:54:32 +02001027 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001028 if settings.has_key('change') > 0:
1029 if settings['depot-paths'] == original['depot-paths']:
1030 originP4Change = int(original['change'])
1031 p4Change = int(settings['change'])
Simon Hausmannabcd7902007-05-24 22:25:36 +02001032 if originP4Change > p4Change:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001033 print ("%s (%s) is newer than %s (%s). "
1034 "Updating p4 branch from origin."
1035 % (originHead, originP4Change,
1036 remoteHead, p4Change))
Simon Hausmannabcd7902007-05-24 22:25:36 +02001037 update = True
1038 else:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001039 print ("Ignoring: %s was imported from %s while "
1040 "%s was imported from %s"
1041 % (originHead, ','.join(original['depot-paths']),
1042 remoteHead, ','.join(settings['depot-paths'])))
Simon Hausmannabcd7902007-05-24 22:25:36 +02001043
1044 if update:
1045 system("git update-ref %s %s" % (remoteHead, originHead))
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001046
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001047 def updateOptionDict(self, d):
1048 option_keys = {}
1049 if self.keepRepoPath:
1050 option_keys['keepRepoPath'] = 1
1051
1052 d["options"] = ' '.join(sorted(option_keys.keys()))
1053
1054 def readOptions(self, d):
1055 self.keepRepoPath = (d.has_key('options')
1056 and ('keepRepoPath' in d['options']))
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001057
Simon Hausmannb9847332007-03-20 20:54:23 +01001058 def run(self, args):
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001059 self.depotPaths = []
Simon Hausmann179caeb2007-03-22 22:17:42 +01001060 self.changeRange = ""
1061 self.initialParent = ""
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001062 self.previousDepotPaths = []
Han-Wen Nienhuysce6f33c2007-05-23 16:46:29 -03001063
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001064 # map from branch depot path to parent branch
1065 self.knownBranches = {}
1066 self.initialParents = {}
Simon Hausmanncae7b732007-06-10 10:57:40 +02001067 self.hasOrigin = gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
Simon Hausmanna43ff002007-06-11 09:59:27 +02001068 if not self.syncWithOrigin:
1069 self.hasOrigin = False
Simon Hausmann179caeb2007-03-22 22:17:42 +01001070
Simon Hausmanna028a982007-05-23 00:03:08 +02001071 if self.importIntoRemotes:
1072 self.refPrefix = "refs/remotes/p4/"
1073 else:
Marius Storm-Olsendb775552007-06-07 15:13:59 +02001074 self.refPrefix = "refs/heads/p4/"
Simon Hausmanna028a982007-05-23 00:03:08 +02001075
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001076 if self.syncWithOrigin and self.hasOrigin:
1077 if not self.silent:
1078 print "Syncing with origin first by calling git fetch origin"
1079 system("git fetch origin")
Simon Hausmann10f880f2007-05-24 22:28:28 +02001080
Simon Hausmann569d1bd2007-03-22 21:34:16 +01001081 if len(self.branch) == 0:
Marius Storm-Olsendb775552007-06-07 15:13:59 +02001082 self.branch = self.refPrefix + "master"
Simon Hausmanna028a982007-05-23 00:03:08 +02001083 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
Simon Hausmann48df6fd2007-05-17 21:18:53 +02001084 system("git update-ref %s refs/heads/p4" % self.branch)
Simon Hausmann48df6fd2007-05-17 21:18:53 +02001085 system("git branch -D p4");
Simon Hausmannfaf1bd22007-05-21 10:05:30 +02001086 # create it /after/ importing, when master exists
Simon Hausmanna028a982007-05-23 00:03:08 +02001087 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
Simon Hausmanna3c55c02007-05-27 15:48:01 +02001088 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
Simon Hausmann179caeb2007-03-22 22:17:42 +01001089
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001090 # TODO: should always look at previous commits,
1091 # merge with previous imports, if possible.
1092 if args == []:
Simon Hausmannd414c742007-05-25 11:36:42 +02001093 if self.hasOrigin:
1094 self.createOrUpdateBranchesFromOrigin()
Simon Hausmannabcd7902007-05-24 22:25:36 +02001095 self.listExistingP4GitBranches()
1096
1097 if len(self.p4BranchesInGit) > 1:
1098 if not self.silent:
1099 print "Importing from/into multiple branches"
1100 self.detectBranches = True
Simon Hausmann967f72e2007-03-23 09:30:41 +01001101
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001102 if self.verbose:
1103 print "branches: %s" % self.p4BranchesInGit
1104
1105 p4Change = 0
1106 for branch in self.p4BranchesInGit:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001107 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001108
1109 settings = extractSettingsGitLog(logMsg)
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001110
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001111 self.readOptions(settings)
1112 if (settings.has_key('depot-paths')
1113 and settings.has_key ('change')):
1114 change = int(settings['change']) + 1
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001115 p4Change = max(p4Change, change)
1116
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001117 depotPaths = sorted(settings['depot-paths'])
1118 if self.previousDepotPaths == []:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001119 self.previousDepotPaths = depotPaths
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001120 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001121 paths = []
1122 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
Simon Hausmann583e1702007-06-07 09:37:13 +02001123 for i in range(0, min(len(cur), len(prev))):
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001124 if cur[i] <> prev[i]:
Simon Hausmann583e1702007-06-07 09:37:13 +02001125 i = i - 1
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001126 break
1127
Simon Hausmann583e1702007-06-07 09:37:13 +02001128 paths.append (cur[:i + 1])
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001129
1130 self.previousDepotPaths = paths
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001131
1132 if p4Change > 0:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001133 self.depotPaths = sorted(self.previousDepotPaths)
Simon Hausmannd5904672007-05-19 11:07:32 +02001134 self.changeRange = "@%s,#head" % p4Change
Simon Hausmann330f53b2007-06-07 09:39:51 +02001135 if not self.detectBranches:
1136 self.initialParent = parseRevision(self.branch)
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001137 if not self.silent and not self.detectBranches:
Simon Hausmann967f72e2007-03-23 09:30:41 +01001138 print "Performing incremental import into %s git branch" % self.branch
Simon Hausmann569d1bd2007-03-22 21:34:16 +01001139
Simon Hausmannf9162f62007-05-17 09:02:45 +02001140 if not self.branch.startswith("refs/"):
1141 self.branch = "refs/heads/" + self.branch
Simon Hausmann179caeb2007-03-22 22:17:42 +01001142
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001143 if len(args) == 0 and self.depotPaths:
Simon Hausmannb9847332007-03-20 20:54:23 +01001144 if not self.silent:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001145 print "Depot paths: %s" % ' '.join(self.depotPaths)
Simon Hausmannb9847332007-03-20 20:54:23 +01001146 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001147 if self.depotPaths and self.depotPaths != args:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001148 print ("previous import used depot path %s and now %s was specified. "
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001149 "This doesn't work!" % (' '.join (self.depotPaths),
1150 ' '.join (args)))
Simon Hausmannb9847332007-03-20 20:54:23 +01001151 sys.exit(1)
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001152
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001153 self.depotPaths = sorted(args)
Simon Hausmannb9847332007-03-20 20:54:23 +01001154
Simon Hausmannb9847332007-03-20 20:54:23 +01001155 self.revision = ""
1156 self.users = {}
Simon Hausmannb9847332007-03-20 20:54:23 +01001157
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001158 newPaths = []
1159 for p in self.depotPaths:
1160 if p.find("@") != -1:
1161 atIdx = p.index("@")
1162 self.changeRange = p[atIdx:]
1163 if self.changeRange == "@all":
1164 self.changeRange = ""
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001165 elif ',' not in self.changeRange:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001166 self.revision = self.changeRange
1167 self.changeRange = ""
1168 p = p[0:atIdx]
1169 elif p.find("#") != -1:
1170 hashIdx = p.index("#")
1171 self.revision = p[hashIdx:]
1172 p = p[0:hashIdx]
1173 elif self.previousDepotPaths == []:
1174 self.revision = "#head"
Simon Hausmannb9847332007-03-20 20:54:23 +01001175
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001176 p = re.sub ("\.\.\.$", "", p)
1177 if not p.endswith("/"):
1178 p += "/"
1179
1180 newPaths.append(p)
1181
1182 self.depotPaths = newPaths
1183
Simon Hausmannb9847332007-03-20 20:54:23 +01001184
Simon Hausmannb607e712007-05-20 10:55:54 +02001185 self.loadUserMapFromCache()
Simon Hausmanncb53e1f2007-04-08 00:12:02 +02001186 self.labels = {}
1187 if self.detectLabels:
1188 self.getLabels();
Simon Hausmannb9847332007-03-20 20:54:23 +01001189
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001190 if self.detectBranches:
Simon Hausmanndf450922007-06-08 08:49:22 +02001191 ## FIXME - what's a P4 projectName ?
1192 self.projectName = self.guessProjectName()
1193
1194 if not self.hasOrigin:
1195 self.getBranchMapping();
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001196 if self.verbose:
1197 print "p4-git branches: %s" % self.p4BranchesInGit
1198 print "initial parents: %s" % self.initialParents
1199 for b in self.p4BranchesInGit:
1200 if b != "master":
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001201
1202 ## FIXME
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001203 b = b[len(self.projectName):]
1204 self.createdBranches.add(b)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001205
Simon Hausmannf291b4e2007-04-14 11:21:50 +02001206 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
Simon Hausmannb9847332007-03-20 20:54:23 +01001207
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001208 importProcess = subprocess.Popen(["git", "fast-import"],
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001209 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1210 stderr=subprocess.PIPE);
Simon Hausmann08483582007-05-15 14:31:06 +02001211 self.gitOutput = importProcess.stdout
1212 self.gitStream = importProcess.stdin
1213 self.gitError = importProcess.stderr
Simon Hausmannb9847332007-03-20 20:54:23 +01001214
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001215 if self.revision:
Simon Hausmanna9d1a272007-06-11 23:28:03 +02001216 print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), self.revision, self.branch)
Simon Hausmannb9847332007-03-20 20:54:23 +01001217
1218 details = { "user" : "git perforce import user", "time" : int(time.time()) }
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001219 details["desc"] = ("Initial import of %s from the state at revision %s"
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001220 % (' '.join(self.depotPaths), self.revision))
Simon Hausmannb9847332007-03-20 20:54:23 +01001221 details["change"] = self.revision
1222 newestRevision = 0
1223
1224 fileCnt = 0
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001225 for info in p4CmdList("files "
1226 + ' '.join(["%s...%s"
1227 % (p, self.revision)
1228 for p in self.depotPaths])):
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -03001229
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -03001230 if info['code'] == 'error':
1231 sys.stderr.write("p4 returned an error: %s\n"
1232 % info['data'])
1233 sys.exit(1)
1234
1235
Simon Hausmannb9847332007-03-20 20:54:23 +01001236 change = int(info["change"])
1237 if change > newestRevision:
1238 newestRevision = change
1239
1240 if info["action"] == "delete":
Simon Hausmannc45b1cf2007-04-08 10:13:32 +02001241 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1242 #fileCnt = fileCnt + 1
Simon Hausmannb9847332007-03-20 20:54:23 +01001243 continue
1244
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -03001245 for prop in ["depotFile", "rev", "action", "type" ]:
Simon Hausmannb9847332007-03-20 20:54:23 +01001246 details["%s%s" % (prop, fileCnt)] = info[prop]
1247
1248 fileCnt = fileCnt + 1
1249
1250 details["change"] = newestRevision
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001251 self.updateOptionDict(details)
Simon Hausmannb9847332007-03-20 20:54:23 +01001252 try:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001253 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
Simon Hausmannc7157062007-03-20 21:13:49 +01001254 except IOError:
Simon Hausmannfd4ca862007-04-13 22:21:10 +02001255 print "IO error with git fast-import. Is your git version recent enough?"
Simon Hausmannb9847332007-03-20 20:54:23 +01001256 print self.gitError.read()
1257
1258 else:
1259 changes = []
1260
Simon Hausmann0828ab12007-03-20 20:59:30 +01001261 if len(self.changesFile) > 0:
Simon Hausmannb9847332007-03-20 20:54:23 +01001262 output = open(self.changesFile).readlines()
1263 changeSet = Set()
1264 for line in output:
1265 changeSet.add(int(line))
1266
1267 for change in changeSet:
1268 changes.append(change)
1269
1270 changes.sort()
1271 else:
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001272 if self.verbose:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001273 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001274 self.changeRange)
1275 assert self.depotPaths
1276 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1277 for p in self.depotPaths]))
Simon Hausmannb9847332007-03-20 20:54:23 +01001278
1279 for line in output:
1280 changeNum = line.split(" ")[1]
1281 changes.append(changeNum)
1282
1283 changes.reverse()
1284
Simon Hausmann01a9c9c2007-05-23 00:07:35 +02001285 if len(self.maxChanges) > 0:
1286 changes = changes[0:min(int(self.maxChanges), len(changes))]
1287
Simon Hausmannb9847332007-03-20 20:54:23 +01001288 if len(changes) == 0:
Simon Hausmann0828ab12007-03-20 20:59:30 +01001289 if not self.silent:
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001290 print "No changes to import!"
Simon Hausmann1f52af62007-04-08 00:07:02 +02001291 return True
Simon Hausmannb9847332007-03-20 20:54:23 +01001292
Simon Hausmanna9d1a272007-06-11 23:28:03 +02001293 if not self.silent and not self.detectBranches:
1294 print "Import destination: %s" % self.branch
1295
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001296 self.updatedBranches = set()
1297
Simon Hausmannb9847332007-03-20 20:54:23 +01001298 cnt = 1
1299 for change in changes:
1300 description = p4Cmd("describe %s" % change)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001301 self.updateOptionDict(description)
Simon Hausmannb9847332007-03-20 20:54:23 +01001302
Simon Hausmann0828ab12007-03-20 20:59:30 +01001303 if not self.silent:
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001304 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
Simon Hausmannb9847332007-03-20 20:54:23 +01001305 sys.stdout.flush()
1306 cnt = cnt + 1
1307
1308 try:
Simon Hausmannb9847332007-03-20 20:54:23 +01001309 if self.detectBranches:
Simon Hausmann71b112d2007-05-19 11:54:11 +02001310 branches = self.splitFilesIntoBranches(description)
Simon Hausmannd5904672007-05-19 11:07:32 +02001311 for branch in branches.keys():
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001312 ## HACK --hwn
1313 branchPrefix = self.depotPaths[0] + branch + "/"
Simon Hausmannb9847332007-03-20 20:54:23 +01001314
Simon Hausmannb9847332007-03-20 20:54:23 +01001315 parent = ""
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001316
Simon Hausmannd5904672007-05-19 11:07:32 +02001317 filesForCommit = branches[branch]
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001318
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001319 if self.verbose:
1320 print "branch is %s" % branch
1321
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001322 self.updatedBranches.add(branch)
1323
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001324 if branch not in self.createdBranches:
Simon Hausmannb9847332007-03-20 20:54:23 +01001325 self.createdBranches.add(branch)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001326 parent = self.knownBranches[branch]
Simon Hausmannb9847332007-03-20 20:54:23 +01001327 if parent == branch:
1328 parent = ""
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001329 elif self.verbose:
1330 print "parent determined through known branches: %s" % parent
Simon Hausmannb9847332007-03-20 20:54:23 +01001331
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001332 # main branch? use master
1333 if branch == "main":
1334 branch = "master"
1335 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001336
1337 ## FIXME
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001338 branch = self.projectName + branch
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001339
1340 if parent == "main":
1341 parent = "master"
1342 elif len(parent) > 0:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001343 ## FIXME
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001344 parent = self.projectName + parent
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001345
Simon Hausmanna028a982007-05-23 00:03:08 +02001346 branch = self.refPrefix + branch
Simon Hausmannb9847332007-03-20 20:54:23 +01001347 if len(parent) > 0:
Simon Hausmanna028a982007-05-23 00:03:08 +02001348 parent = self.refPrefix + parent
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001349
1350 if self.verbose:
1351 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1352
1353 if len(parent) == 0 and branch in self.initialParents:
1354 parent = self.initialParents[branch]
1355 del self.initialParents[branch]
1356
Simon Hausmann86fda6a2007-06-11 08:54:45 +02001357 self.commit(description, filesForCommit, branch, [branchPrefix], parent)
Simon Hausmannb9847332007-03-20 20:54:23 +01001358 else:
Simon Hausmann71b112d2007-05-19 11:54:11 +02001359 files = self.extractFilesFromCommit(description)
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001360 self.commit(description, files, self.branch, self.depotPaths,
1361 self.initialParent)
Simon Hausmannb9847332007-03-20 20:54:23 +01001362 self.initialParent = ""
1363 except IOError:
1364 print self.gitError.read()
1365 sys.exit(1)
1366
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001367 if not self.silent:
1368 print ""
1369 if len(self.updatedBranches) > 0:
1370 sys.stdout.write("Updated branches: ")
1371 for b in self.updatedBranches:
1372 sys.stdout.write("%s " % b)
1373 sys.stdout.write("\n")
Simon Hausmannb9847332007-03-20 20:54:23 +01001374
Simon Hausmannb9847332007-03-20 20:54:23 +01001375
1376 self.gitStream.close()
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001377 if importProcess.wait() != 0:
1378 die("fast-import failed: %s" % self.gitError.read())
Simon Hausmannb9847332007-03-20 20:54:23 +01001379 self.gitOutput.close()
1380 self.gitError.close()
1381
Simon Hausmannb9847332007-03-20 20:54:23 +01001382 return True
1383
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001384class P4Rebase(Command):
1385 def __init__(self):
1386 Command.__init__(self)
Simon Hausmann01265102007-05-25 10:36:10 +02001387 self.options = [ ]
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001388 self.description = ("Fetches the latest revision from perforce and "
1389 + "rebases the current work (branch) against it")
Simon Hausmann68c42152007-06-07 12:51:03 +02001390 self.verbose = False
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001391
1392 def run(self, args):
1393 sync = P4Sync()
1394 sync.run([])
Simon Hausmannd7e38682007-06-12 14:34:46 +02001395
1396 [upstream, settings] = findUpstreamBranchPoint()
1397 if len(upstream) == 0:
1398 die("Cannot find upstream branchpoint for rebase")
1399
1400 # the branchpoint may be p4/foo~3, so strip off the parent
1401 upstream = re.sub("~[0-9]+$", "", upstream)
1402
1403 print "Rebasing the current branch onto %s" % upstream
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -03001404 oldHead = read_pipe("git rev-parse HEAD").strip()
Simon Hausmannd7e38682007-06-12 14:34:46 +02001405 system("git rebase %s" % upstream)
Simon Hausmann1f52af62007-04-08 00:07:02 +02001406 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001407 return True
1408
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001409class P4Clone(P4Sync):
1410 def __init__(self):
1411 P4Sync.__init__(self)
1412 self.description = "Creates a new git repository and imports from Perforce into it"
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001413 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1414 self.options.append(
1415 optparse.make_option("--destination", dest="cloneDestination",
1416 action='store', default=None,
1417 help="where to leave result of the clone"))
1418 self.cloneDestination = None
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001419 self.needsGit = False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001420
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001421 def defaultDestination(self, args):
1422 ## TODO: use common prefix of args?
1423 depotPath = args[0]
1424 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1425 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1426 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1427 depotDir = re.sub(r"/$", "", depotDir)
1428 return os.path.split(depotDir)[1]
1429
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001430 def run(self, args):
1431 if len(args) < 1:
1432 return False
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001433
1434 if self.keepRepoPath and not self.cloneDestination:
1435 sys.stderr.write("Must specify destination for --keep-path\n")
1436 sys.exit(1)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001437
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001438 depotPaths = args
Simon Hausmann5e100b52007-06-07 21:12:25 +02001439
1440 if not self.cloneDestination and len(depotPaths) > 1:
1441 self.cloneDestination = depotPaths[-1]
1442 depotPaths = depotPaths[:-1]
1443
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001444 for p in depotPaths:
1445 if not p.startswith("//"):
1446 return False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001447
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001448 if not self.cloneDestination:
Marius Storm-Olsen98ad4fa2007-06-07 15:08:33 +02001449 self.cloneDestination = self.defaultDestination(args)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001450
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001451 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
Kevin Greenc3bf3f12007-06-11 16:48:07 -04001452 if not os.path.exists(self.cloneDestination):
1453 os.makedirs(self.cloneDestination)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001454 os.chdir(self.cloneDestination)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001455 system("git init")
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001456 self.gitdir = os.getcwd() + "/.git"
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001457 if not P4Sync.run(self, depotPaths):
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001458 return False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001459 if self.branch != "master":
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001460 if gitBranchExists("refs/remotes/p4/master"):
1461 system("git branch master refs/remotes/p4/master")
1462 system("git checkout -f")
1463 else:
1464 print "Could not detect main branch. No checkout/master branch created."
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001465
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001466 return True
1467
Simon Hausmannb9847332007-03-20 20:54:23 +01001468class HelpFormatter(optparse.IndentedHelpFormatter):
1469 def __init__(self):
1470 optparse.IndentedHelpFormatter.__init__(self)
1471
1472 def format_description(self, description):
1473 if description:
1474 return description + "\n"
1475 else:
1476 return ""
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001477
Simon Hausmann86949ee2007-03-19 20:59:12 +01001478def printUsage(commands):
1479 print "usage: %s <command> [options]" % sys.argv[0]
1480 print ""
1481 print "valid commands: %s" % ", ".join(commands)
1482 print ""
1483 print "Try %s <command> --help for command specific help." % sys.argv[0]
1484 print ""
1485
1486commands = {
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001487 "debug" : P4Debug,
1488 "submit" : P4Submit,
1489 "sync" : P4Sync,
1490 "rebase" : P4Rebase,
1491 "clone" : P4Clone,
1492 "rollback" : P4RollBack
Simon Hausmann86949ee2007-03-19 20:59:12 +01001493}
1494
Simon Hausmann86949ee2007-03-19 20:59:12 +01001495
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001496def main():
1497 if len(sys.argv[1:]) == 0:
1498 printUsage(commands.keys())
1499 sys.exit(2)
Simon Hausmann86949ee2007-03-19 20:59:12 +01001500
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001501 cmd = ""
1502 cmdName = sys.argv[1]
1503 try:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001504 klass = commands[cmdName]
1505 cmd = klass()
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001506 except KeyError:
1507 print "unknown command %s" % cmdName
1508 print ""
1509 printUsage(commands.keys())
1510 sys.exit(2)
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001511
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001512 options = cmd.options
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001513 cmd.gitdir = os.environ.get("GIT_DIR", None)
Simon Hausmann86949ee2007-03-19 20:59:12 +01001514
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001515 args = sys.argv[2:]
Simon Hausmanne20a9e52007-03-26 00:13:51 +02001516
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001517 if len(options) > 0:
1518 options.append(optparse.make_option("--git-dir", dest="gitdir"))
Simon Hausmanne20a9e52007-03-26 00:13:51 +02001519
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001520 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1521 options,
1522 description = cmd.description,
1523 formatter = HelpFormatter())
Simon Hausmann86949ee2007-03-19 20:59:12 +01001524
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001525 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1526 global verbose
1527 verbose = cmd.verbose
1528 if cmd.needsGit:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001529 if cmd.gitdir == None:
1530 cmd.gitdir = os.path.abspath(".git")
1531 if not isValidGitDir(cmd.gitdir):
1532 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1533 if os.path.exists(cmd.gitdir):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001534 cdup = read_pipe("git rev-parse --show-cdup").strip()
1535 if len(cdup) > 0:
1536 os.chdir(cdup);
1537
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001538 if not isValidGitDir(cmd.gitdir):
1539 if isValidGitDir(cmd.gitdir + "/.git"):
1540 cmd.gitdir += "/.git"
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001541 else:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001542 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
Simon Hausmann8910ac02007-03-26 08:18:55 +02001543
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001544 os.environ["GIT_DIR"] = cmd.gitdir
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001545
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001546 if not cmd.run(args):
1547 parser.print_help()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001548
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001549
1550if __name__ == '__main__':
1551 main()