blob: 41e86e76cb9e4718c87185fc0b25e630ad091939 [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
Scott Lamb9f90c732007-07-15 20:58:10 -070066def p4CmdList(cmd, stdin=None, stdin_mode='w+b'):
Simon Hausmann86949ee2007-03-19 20:59:12 +010067 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)
Scott Lamb9f90c732007-07-15 20:58:10 -070070
71 # Use a temporary file to avoid deadlocks without
72 # subprocess.communicate(), which would put another copy
73 # of stdout into memory.
74 stdin_file = None
75 if stdin is not None:
76 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
77 stdin_file.write(stdin)
78 stdin_file.flush()
79 stdin_file.seek(0)
80
81 p4 = subprocess.Popen(cmd, shell=True,
82 stdin=stdin_file,
83 stdout=subprocess.PIPE)
Simon Hausmann86949ee2007-03-19 20:59:12 +010084
85 result = []
86 try:
87 while True:
Scott Lamb9f90c732007-07-15 20:58:10 -070088 entry = marshal.load(p4.stdout)
Simon Hausmann86949ee2007-03-19 20:59:12 +010089 result.append(entry)
90 except EOFError:
91 pass
Scott Lamb9f90c732007-07-15 20:58:10 -070092 exitCode = p4.wait()
93 if exitCode != 0:
Simon Hausmannac3e0d72007-05-23 23:32:32 +020094 entry = {}
95 entry["p4ExitCode"] = exitCode
96 result.append(entry)
Simon Hausmann86949ee2007-03-19 20:59:12 +010097
98 return result
99
100def p4Cmd(cmd):
101 list = p4CmdList(cmd)
102 result = {}
103 for entry in list:
104 result.update(entry)
105 return result;
106
Simon Hausmanncb2c9db2007-03-24 09:15:11 +0100107def p4Where(depotPath):
108 if not depotPath.endswith("/"):
109 depotPath += "/"
110 output = p4Cmd("where %s..." % depotPath)
Simon Hausmanndc524032007-05-21 09:34:56 +0200111 if output["code"] == "error":
112 return ""
Simon Hausmanncb2c9db2007-03-24 09:15:11 +0100113 clientPath = ""
114 if "path" in output:
115 clientPath = output.get("path")
116 elif "data" in output:
117 data = output.get("data")
118 lastSpace = data.rfind(" ")
119 clientPath = data[lastSpace + 1:]
120
121 if clientPath.endswith("..."):
122 clientPath = clientPath[:-3]
123 return clientPath
124
Simon Hausmann86949ee2007-03-19 20:59:12 +0100125def currentGitBranch():
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300126 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
Simon Hausmann86949ee2007-03-19 20:59:12 +0100127
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100128def isValidGitDir(path):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300129 if (os.path.exists(path + "/HEAD")
130 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100131 return True;
132 return False
133
Simon Hausmann463e8af2007-05-17 09:13:54 +0200134def parseRevision(ref):
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300135 return read_pipe("git rev-parse %s" % ref).strip()
Simon Hausmann463e8af2007-05-17 09:13:54 +0200136
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100137def extractLogMessageFromGitCommit(commit):
138 logMessage = ""
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300139
140 ## fixme: title is first line of commit, not 1st paragraph.
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100141 foundTitle = False
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300142 for log in read_pipe_lines("git cat-file commit %s" % commit):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100143 if not foundTitle:
144 if len(log) == 1:
Simon Hausmann1c094182007-05-01 23:15:48 +0200145 foundTitle = True
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100146 continue
147
148 logMessage += log
149 return logMessage
150
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300151def extractSettingsGitLog(log):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100152 values = {}
153 for line in log.split("\n"):
154 line = line.strip()
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300155 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
156 if not m:
157 continue
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100158
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300159 assignments = m.group(1).split (':')
160 for a in assignments:
161 vals = a.split ('=')
162 key = vals[0].strip()
163 val = ('='.join (vals[1:])).strip()
164 if val.endswith ('\"') and val.startswith('"'):
165 val = val[1:-1]
166
167 values[key] = val
168
Simon Hausmann845b42c2007-06-07 09:19:34 +0200169 paths = values.get("depot-paths")
170 if not paths:
171 paths = values.get("depot-path")
Simon Hausmanna3fdd572007-06-07 22:54:32 +0200172 if paths:
173 values['depot-paths'] = paths.split(',')
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300174 return values
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100175
Simon Hausmann8136a632007-03-22 21:27:14 +0100176def gitBranchExists(branch):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300177 proc = subprocess.Popen(["git", "rev-parse", branch],
178 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
Simon Hausmanncaace112007-05-15 14:57:57 +0200179 return proc.wait() == 0;
Simon Hausmann8136a632007-03-22 21:27:14 +0100180
Simon Hausmann01265102007-05-25 10:36:10 +0200181def gitConfig(key):
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300182 return read_pipe("git config %s" % key, ignore_error=True).strip()
Simon Hausmann01265102007-05-25 10:36:10 +0200183
Simon Hausmann062410b2007-07-18 10:56:31 +0200184def p4BranchesInGit(branchesAreInRemotes = True):
185 branches = {}
186
187 cmdline = "git rev-parse --symbolic "
188 if branchesAreInRemotes:
189 cmdline += " --remotes"
190 else:
191 cmdline += " --branches"
192
193 for line in read_pipe_lines(cmdline):
194 line = line.strip()
195
196 ## only import to p4/
197 if not line.startswith('p4/') or line == "p4/HEAD":
198 continue
199 branch = line
200
201 # strip off p4
202 branch = re.sub ("^p4/", "", line)
203
204 branches[branch] = parseRevision(line)
205 return branches
206
Simon Hausmann9ceab362007-06-22 00:01:57 +0200207def findUpstreamBranchPoint(head = "HEAD"):
Simon Hausmann86506fe2007-07-18 12:40:12 +0200208 branches = p4BranchesInGit()
209 # map from depot-path to branch name
210 branchByDepotPath = {}
211 for branch in branches.keys():
212 tip = branches[branch]
213 log = extractLogMessageFromGitCommit(tip)
214 settings = extractSettingsGitLog(log)
215 if settings.has_key("depot-paths"):
216 paths = ",".join(settings["depot-paths"])
217 branchByDepotPath[paths] = "remotes/p4/" + branch
218
Simon Hausmann27d2d812007-06-12 14:31:59 +0200219 settings = None
Simon Hausmann27d2d812007-06-12 14:31:59 +0200220 parent = 0
221 while parent < 65535:
Simon Hausmann9ceab362007-06-22 00:01:57 +0200222 commit = head + "~%s" % parent
Simon Hausmann27d2d812007-06-12 14:31:59 +0200223 log = extractLogMessageFromGitCommit(commit)
224 settings = extractSettingsGitLog(log)
Simon Hausmann86506fe2007-07-18 12:40:12 +0200225 if settings.has_key("depot-paths"):
226 paths = ",".join(settings["depot-paths"])
227 if branchByDepotPath.has_key(paths):
228 return [branchByDepotPath[paths], settings]
Simon Hausmann27d2d812007-06-12 14:31:59 +0200229
Simon Hausmann86506fe2007-07-18 12:40:12 +0200230 parent = parent + 1
Simon Hausmann27d2d812007-06-12 14:31:59 +0200231
Simon Hausmann86506fe2007-07-18 12:40:12 +0200232 return ["", settings]
Simon Hausmann27d2d812007-06-12 14:31:59 +0200233
Simon Hausmannb9847332007-03-20 20:54:23 +0100234class Command:
235 def __init__(self):
236 self.usage = "usage: %prog [options]"
Simon Hausmann8910ac02007-03-26 08:18:55 +0200237 self.needsGit = True
Simon Hausmannb9847332007-03-20 20:54:23 +0100238
239class P4Debug(Command):
Simon Hausmann86949ee2007-03-19 20:59:12 +0100240 def __init__(self):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100241 Command.__init__(self)
Simon Hausmann86949ee2007-03-19 20:59:12 +0100242 self.options = [
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300243 optparse.make_option("--verbose", dest="verbose", action="store_true",
244 default=False),
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300245 ]
Simon Hausmannc8c39112007-03-19 21:02:30 +0100246 self.description = "A tool to debug the output of p4 -G."
Simon Hausmann8910ac02007-03-26 08:18:55 +0200247 self.needsGit = False
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300248 self.verbose = False
Simon Hausmann86949ee2007-03-19 20:59:12 +0100249
250 def run(self, args):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300251 j = 0
Simon Hausmann86949ee2007-03-19 20:59:12 +0100252 for output in p4CmdList(" ".join(args)):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300253 print 'Element: %d' % j
254 j += 1
Simon Hausmann86949ee2007-03-19 20:59:12 +0100255 print output
Simon Hausmannb9847332007-03-20 20:54:23 +0100256 return True
Simon Hausmann86949ee2007-03-19 20:59:12 +0100257
Simon Hausmann58346842007-05-21 22:57:06 +0200258class P4RollBack(Command):
259 def __init__(self):
260 Command.__init__(self)
261 self.options = [
Simon Hausmann0c66a782007-05-23 20:07:57 +0200262 optparse.make_option("--verbose", dest="verbose", action="store_true"),
263 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
Simon Hausmann58346842007-05-21 22:57:06 +0200264 ]
265 self.description = "A tool to debug the multi-branch import. Don't use :)"
Simon Hausmann52102d42007-05-21 23:44:24 +0200266 self.verbose = False
Simon Hausmann0c66a782007-05-23 20:07:57 +0200267 self.rollbackLocalBranches = False
Simon Hausmann58346842007-05-21 22:57:06 +0200268
269 def run(self, args):
270 if len(args) != 1:
271 return False
272 maxChange = int(args[0])
Simon Hausmann0c66a782007-05-23 20:07:57 +0200273
Simon Hausmannad192f22007-05-23 23:44:19 +0200274 if "p4ExitCode" in p4Cmd("changes -m 1"):
Simon Hausmann66a2f522007-05-23 23:40:48 +0200275 die("Problems executing p4");
276
Simon Hausmann0c66a782007-05-23 20:07:57 +0200277 if self.rollbackLocalBranches:
278 refPrefix = "refs/heads/"
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300279 lines = read_pipe_lines("git rev-parse --symbolic --branches")
Simon Hausmann0c66a782007-05-23 20:07:57 +0200280 else:
281 refPrefix = "refs/remotes/"
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300282 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
Simon Hausmann0c66a782007-05-23 20:07:57 +0200283
284 for line in lines:
285 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300286 line = line.strip()
287 ref = refPrefix + line
Simon Hausmann58346842007-05-21 22:57:06 +0200288 log = extractLogMessageFromGitCommit(ref)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300289 settings = extractSettingsGitLog(log)
290
291 depotPaths = settings['depot-paths']
292 change = settings['change']
293
Simon Hausmann58346842007-05-21 22:57:06 +0200294 changed = False
Simon Hausmann52102d42007-05-21 23:44:24 +0200295
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300296 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
297 for p in depotPaths]))) == 0:
Simon Hausmann52102d42007-05-21 23:44:24 +0200298 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
299 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
300 continue
301
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300302 while change and int(change) > maxChange:
Simon Hausmann58346842007-05-21 22:57:06 +0200303 changed = True
Simon Hausmann52102d42007-05-21 23:44:24 +0200304 if self.verbose:
305 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
Simon Hausmann58346842007-05-21 22:57:06 +0200306 system("git update-ref %s \"%s^\"" % (ref, ref))
307 log = extractLogMessageFromGitCommit(ref)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300308 settings = extractSettingsGitLog(log)
309
310
311 depotPaths = settings['depot-paths']
312 change = settings['change']
Simon Hausmann58346842007-05-21 22:57:06 +0200313
314 if changed:
Simon Hausmann52102d42007-05-21 23:44:24 +0200315 print "%s rewound to %s" % (ref, change)
Simon Hausmann58346842007-05-21 22:57:06 +0200316
317 return True
318
Simon Hausmann711544b2007-04-01 15:40:46 +0200319class P4Submit(Command):
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100320 def __init__(self):
Simon Hausmannb9847332007-03-20 20:54:23 +0100321 Command.__init__(self)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100322 self.options = [
323 optparse.make_option("--continue", action="store_false", dest="firstTime"),
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300324 optparse.make_option("--verbose", dest="verbose", action="store_true"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100325 optparse.make_option("--origin", dest="origin"),
326 optparse.make_option("--reset", action="store_true", dest="reset"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100327 optparse.make_option("--log-substitutions", dest="substFile"),
Simon Hausmann04219c02007-03-21 10:11:20 +0100328 optparse.make_option("--dry-run", action="store_true"),
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200329 optparse.make_option("--direct", dest="directSubmit", action="store_true"),
Simon Hausmanncb4f1282007-05-25 22:34:30 +0200330 optparse.make_option("--trust-me-like-a-fool", dest="trustMeLikeAFool", action="store_true"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100331 ]
332 self.description = "Submit changes from git to the perforce depot."
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200333 self.usage += " [name of git branch to submit into perforce depot]"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100334 self.firstTime = True
335 self.reset = False
336 self.interactive = True
337 self.dryRun = False
338 self.substFile = ""
339 self.firstTime = True
Simon Hausmann95124972007-03-23 09:16:07 +0100340 self.origin = ""
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200341 self.directSubmit = False
Simon Hausmanncb4f1282007-05-25 22:34:30 +0200342 self.trustMeLikeAFool = False
Simon Hausmannb0d10df2007-06-07 13:09:14 +0200343 self.verbose = False
Marius Storm-Olsenf7baba82007-06-07 14:07:01 +0200344 self.isWindows = (platform.system() == "Windows")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100345
346 self.logSubstitutions = {}
347 self.logSubstitutions["<enter description here>"] = "%log%"
348 self.logSubstitutions["\tDetails:"] = "\tDetails: %log%"
349
350 def check(self):
351 if len(p4CmdList("opened ...")) > 0:
352 die("You have files opened with perforce! Close them before starting the sync.")
353
354 def start(self):
355 if len(self.config) > 0 and not self.reset:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300356 die("Cannot start sync. Previous sync config found at %s\n"
357 "If you want to start submitting again from scratch "
358 "maybe you want to call git-p4 submit --reset" % self.configFile)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100359
360 commits = []
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200361 if self.directSubmit:
362 commits.append("0")
363 else:
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300364 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 -0300365 commits.append(line.strip())
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200366 commits.reverse()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100367
368 self.config["commits"] = commits
369
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100370 def prepareLogMessage(self, template, message):
371 result = ""
372
373 for line in template.split("\n"):
374 if line.startswith("#"):
375 result += line + "\n"
376 continue
377
378 substituted = False
379 for key in self.logSubstitutions.keys():
380 if line.find(key) != -1:
381 value = self.logSubstitutions[key]
382 value = value.replace("%log%", message)
383 if value != "@remove@":
384 result += line.replace(key, value) + "\n"
385 substituted = True
386 break
387
388 if not substituted:
389 result += line + "\n"
390
391 return result
392
Han-Wen Nienhuys7cb5cbe2007-05-23 16:55:48 -0300393 def applyCommit(self, id):
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200394 if self.directSubmit:
395 print "Applying local change in working directory/index"
396 diff = self.diffStatus
397 else:
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300398 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
399 diff = read_pipe_lines("git diff-tree -r --name-status \"%s^\" \"%s\"" % (id, id))
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100400 filesToAdd = set()
401 filesToDelete = set()
Simon Hausmannd336c152007-05-16 09:41:26 +0200402 editedFiles = set()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100403 for line in diff:
404 modifier = line[0]
405 path = line[1:].strip()
406 if modifier == "M":
Simon Hausmannd336c152007-05-16 09:41:26 +0200407 system("p4 edit \"%s\"" % path)
408 editedFiles.add(path)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100409 elif modifier == "A":
410 filesToAdd.add(path)
411 if path in filesToDelete:
412 filesToDelete.remove(path)
413 elif modifier == "D":
414 filesToDelete.add(path)
415 if path in filesToAdd:
416 filesToAdd.remove(path)
417 else:
418 die("unknown modifier %s for %s" % (modifier, path))
419
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200420 if self.directSubmit:
421 diffcmd = "cat \"%s\"" % self.diffFile
422 else:
423 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
Simon Hausmann47a130b2007-05-20 16:33:21 +0200424 patchcmd = diffcmd + " | git apply "
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200425 tryPatchCmd = patchcmd + "--check -"
426 applyPatchCmd = patchcmd + "--check --apply -"
Simon Hausmann51a26402007-04-15 09:59:56 +0200427
Simon Hausmann47a130b2007-05-20 16:33:21 +0200428 if os.system(tryPatchCmd) != 0:
Simon Hausmann51a26402007-04-15 09:59:56 +0200429 print "Unfortunately applying the change failed!"
430 print "What do you want to do?"
431 response = "x"
432 while response != "s" and response != "a" and response != "w":
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300433 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
434 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
Simon Hausmann51a26402007-04-15 09:59:56 +0200435 if response == "s":
436 print "Skipping! Good luck with the next patches..."
437 return
438 elif response == "a":
Simon Hausmann47a130b2007-05-20 16:33:21 +0200439 os.system(applyPatchCmd)
Simon Hausmann51a26402007-04-15 09:59:56 +0200440 if len(filesToAdd) > 0:
441 print "You may also want to call p4 add on the following files:"
442 print " ".join(filesToAdd)
443 if len(filesToDelete):
444 print "The following files should be scheduled for deletion with p4 delete:"
445 print " ".join(filesToDelete)
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300446 die("Please resolve and submit the conflict manually and "
447 + "continue afterwards with git-p4 submit --continue")
Simon Hausmann51a26402007-04-15 09:59:56 +0200448 elif response == "w":
449 system(diffcmd + " > patch.txt")
450 print "Patch saved to patch.txt in %s !" % self.clientPath
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300451 die("Please resolve and submit the conflict manually and "
452 "continue afterwards with git-p4 submit --continue")
Simon Hausmann51a26402007-04-15 09:59:56 +0200453
Simon Hausmann47a130b2007-05-20 16:33:21 +0200454 system(applyPatchCmd)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100455
456 for f in filesToAdd:
Simon Hausmanne6b711f2007-06-11 23:40:25 +0200457 system("p4 add \"%s\"" % f)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100458 for f in filesToDelete:
Simon Hausmanne6b711f2007-06-11 23:40:25 +0200459 system("p4 revert \"%s\"" % f)
460 system("p4 delete \"%s\"" % f)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100461
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200462 logMessage = ""
463 if not self.directSubmit:
464 logMessage = extractLogMessageFromGitCommit(id)
465 logMessage = logMessage.replace("\n", "\n\t")
Marius Storm-Olsenf7baba82007-06-07 14:07:01 +0200466 if self.isWindows:
467 logMessage = logMessage.replace("\n", "\r\n")
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300468 logMessage = logMessage.strip()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100469
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300470 template = read_pipe("p4 change -o")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100471
472 if self.interactive:
473 submitTemplate = self.prepareLogMessage(template, logMessage)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300474 diff = read_pipe("p4 diff -du ...")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100475
476 for newFile in filesToAdd:
477 diff += "==== new file ====\n"
478 diff += "--- /dev/null\n"
479 diff += "+++ %s\n" % newFile
480 f = open(newFile, "r")
481 for line in f.readlines():
482 diff += "+" + line
483 f.close()
484
Simon Hausmann25df95c2007-05-15 15:15:39 +0200485 separatorLine = "######## everything below this line is just the diff #######"
486 if platform.system() == "Windows":
487 separatorLine += "\r"
488 separatorLine += "\n"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100489
490 response = "e"
Simon Hausmanncb4f1282007-05-25 22:34:30 +0200491 if self.trustMeLikeAFool:
492 response = "y"
493
Simon Hausmann53150252007-03-21 21:04:12 +0100494 firstIteration = True
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100495 while response == "e":
Simon Hausmann53150252007-03-21 21:04:12 +0100496 if not firstIteration:
Simon Hausmannd336c152007-05-16 09:41:26 +0200497 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 +0100498 firstIteration = False
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100499 if response == "e":
500 [handle, fileName] = tempfile.mkstemp()
501 tmpFile = os.fdopen(handle, "w+")
Simon Hausmann53150252007-03-21 21:04:12 +0100502 tmpFile.write(submitTemplate + separatorLine + diff)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100503 tmpFile.close()
Simon Hausmann25df95c2007-05-15 15:15:39 +0200504 defaultEditor = "vi"
505 if platform.system() == "Windows":
506 defaultEditor = "notepad"
507 editor = os.environ.get("EDITOR", defaultEditor);
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100508 system(editor + " " + fileName)
Simon Hausmann25df95c2007-05-15 15:15:39 +0200509 tmpFile = open(fileName, "rb")
Simon Hausmann53150252007-03-21 21:04:12 +0100510 message = tmpFile.read()
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100511 tmpFile.close()
512 os.remove(fileName)
Simon Hausmann53150252007-03-21 21:04:12 +0100513 submitTemplate = message[:message.index(separatorLine)]
Marius Storm-Olsenf7baba82007-06-07 14:07:01 +0200514 if self.isWindows:
515 submitTemplate = submitTemplate.replace("\r\n", "\n")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100516
517 if response == "y" or response == "yes":
518 if self.dryRun:
519 print submitTemplate
520 raw_input("Press return to continue...")
521 else:
Simon Hausmann7944f142007-05-21 11:04:26 +0200522 if self.directSubmit:
523 print "Submitting to git first"
524 os.chdir(self.oldWorkingDirectory)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300525 write_pipe("git commit -a -F -", submitTemplate)
Simon Hausmann7944f142007-05-21 11:04:26 +0200526 os.chdir(self.clientPath)
527
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300528 write_pipe("p4 submit -i", submitTemplate)
Simon Hausmannd336c152007-05-16 09:41:26 +0200529 elif response == "s":
530 for f in editedFiles:
531 system("p4 revert \"%s\"" % f);
532 for f in filesToAdd:
533 system("p4 revert \"%s\"" % f);
534 system("rm %s" %f)
535 for f in filesToDelete:
536 system("p4 delete \"%s\"" % f);
537 return
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100538 else:
539 print "Not submitting!"
540 self.interactive = False
541 else:
542 fileName = "submit.txt"
543 file = open(fileName, "w+")
544 file.write(self.prepareLogMessage(template, logMessage))
545 file.close()
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300546 print ("Perforce submit template written as %s. "
547 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
548 % (fileName, fileName))
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100549
550 def run(self, args):
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200551 if len(args) == 0:
552 self.master = currentGitBranch()
Simon Hausmann4280e532007-05-25 08:49:18 +0200553 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200554 die("Detecting current git branch failed!")
555 elif len(args) == 1:
556 self.master = args[0]
557 else:
558 return False
559
Simon Hausmann27d2d812007-06-12 14:31:59 +0200560 [upstream, settings] = findUpstreamBranchPoint()
561 depotPath = settings['depot-paths'][0]
562 if len(self.origin) == 0:
563 self.origin = upstream
Simon Hausmanna3fdd572007-06-07 22:54:32 +0200564
565 if self.verbose:
566 print "Origin branch is " + self.origin
Simon Hausmann95124972007-03-23 09:16:07 +0100567
568 if len(depotPath) == 0:
569 print "Internal error: cannot locate perforce depot path from existing branches"
570 sys.exit(128)
571
Simon Hausmann51a26402007-04-15 09:59:56 +0200572 self.clientPath = p4Where(depotPath)
Simon Hausmann95124972007-03-23 09:16:07 +0100573
Simon Hausmann51a26402007-04-15 09:59:56 +0200574 if len(self.clientPath) == 0:
Simon Hausmann95124972007-03-23 09:16:07 +0100575 print "Error: Cannot locate perforce checkout of %s in client view" % depotPath
576 sys.exit(128)
577
Simon Hausmann51a26402007-04-15 09:59:56 +0200578 print "Perforce checkout for depot path %s located at %s" % (depotPath, self.clientPath)
Simon Hausmann7944f142007-05-21 11:04:26 +0200579 self.oldWorkingDirectory = os.getcwd()
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200580
581 if self.directSubmit:
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300582 self.diffStatus = read_pipe_lines("git diff -r --name-status HEAD")
Simon Hausmanncbf5efa2007-05-21 10:08:11 +0200583 if len(self.diffStatus) == 0:
584 print "No changes in working directory to submit."
585 return True
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300586 patch = read_pipe("git diff -p --binary --diff-filter=ACMRTUXB HEAD")
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -0300587 self.diffFile = self.gitdir + "/p4-git-diff"
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200588 f = open(self.diffFile, "wb")
589 f.write(patch)
590 f.close();
591
Simon Hausmann51a26402007-04-15 09:59:56 +0200592 os.chdir(self.clientPath)
593 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 +0100594 if response == "y" or response == "yes":
595 system("p4 sync ...")
596
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100597 if self.reset:
598 self.firstTime = True
599
600 if len(self.substFile) > 0:
601 for line in open(self.substFile, "r").readlines():
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300602 tokens = line.strip().split("=")
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100603 self.logSubstitutions[tokens[0]] = tokens[1]
604
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100605 self.check()
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -0300606 self.configFile = self.gitdir + "/p4-git-sync.cfg"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100607 self.config = shelve.open(self.configFile, writeback=True)
608
609 if self.firstTime:
610 self.start()
611
612 commits = self.config.get("commits", [])
613
614 while len(commits) > 0:
615 self.firstTime = False
616 commit = commits[0]
617 commits = commits[1:]
618 self.config["commits"] = commits
Han-Wen Nienhuys7cb5cbe2007-05-23 16:55:48 -0300619 self.applyCommit(commit)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100620 if not self.interactive:
621 break
622
623 self.config.close()
624
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200625 if self.directSubmit:
626 os.remove(self.diffFile)
627
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100628 if len(commits) == 0:
629 if self.firstTime:
630 print "No changes found to apply between %s and current HEAD" % self.origin
631 else:
632 print "All changes applied!"
Simon Hausmann7944f142007-05-21 11:04:26 +0200633 os.chdir(self.oldWorkingDirectory)
634 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 +0200635 if response == "y" or response == "yes":
Simon Hausmann80b59102007-04-09 12:43:40 +0200636 rebase = P4Rebase()
637 rebase.run([])
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100638 os.remove(self.configFile)
639
Simon Hausmannb9847332007-03-20 20:54:23 +0100640 return True
641
Simon Hausmann711544b2007-04-01 15:40:46 +0200642class P4Sync(Command):
Simon Hausmannb9847332007-03-20 20:54:23 +0100643 def __init__(self):
644 Command.__init__(self)
645 self.options = [
646 optparse.make_option("--branch", dest="branch"),
647 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
648 optparse.make_option("--changesfile", dest="changesFile"),
649 optparse.make_option("--silent", dest="silent", action="store_true"),
Simon Hausmannef48f902007-05-17 22:17:49 +0200650 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
Simon Hausmanna028a982007-05-23 00:03:08 +0200651 optparse.make_option("--verbose", dest="verbose", action="store_true"),
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300652 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
653 help="Import into refs/heads/ , not refs/remotes"),
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300654 optparse.make_option("--max-changes", dest="maxChanges"),
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300655 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
656 help="Keep entire BRANCH/DIR/SUBDIR prefix during import")
Simon Hausmannb9847332007-03-20 20:54:23 +0100657 ]
658 self.description = """Imports from Perforce into a git repository.\n
659 example:
660 //depot/my/project/ -- to import the current head
661 //depot/my/project/@all -- to import everything
662 //depot/my/project/@1,6 -- to import only from revision 1 to 6
663
664 (a ... is not needed in the path p4 specification, it's added implicitly)"""
665
666 self.usage += " //depot/path[@revRange]"
Simon Hausmannb9847332007-03-20 20:54:23 +0100667 self.silent = False
Simon Hausmannb9847332007-03-20 20:54:23 +0100668 self.createdBranches = Set()
669 self.committedChanges = Set()
Simon Hausmann569d1bd2007-03-22 21:34:16 +0100670 self.branch = ""
Simon Hausmannb9847332007-03-20 20:54:23 +0100671 self.detectBranches = False
Simon Hausmanncb53e1f2007-04-08 00:12:02 +0200672 self.detectLabels = False
Simon Hausmannb9847332007-03-20 20:54:23 +0100673 self.changesFile = ""
Simon Hausmann01265102007-05-25 10:36:10 +0200674 self.syncWithOrigin = True
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200675 self.verbose = False
Simon Hausmanna028a982007-05-23 00:03:08 +0200676 self.importIntoRemotes = True
Simon Hausmann01a9c9c2007-05-23 00:07:35 +0200677 self.maxChanges = ""
Marius Storm-Olsenc1f91972007-05-24 14:07:55 +0200678 self.isWindows = (platform.system() == "Windows")
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300679 self.keepRepoPath = False
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300680 self.depotPaths = None
Simon Hausmann3c699642007-06-16 13:09:21 +0200681 self.p4BranchesInGit = []
Simon Hausmannb9847332007-03-20 20:54:23 +0100682
Simon Hausmann01265102007-05-25 10:36:10 +0200683 if gitConfig("git-p4.syncFromOrigin") == "false":
684 self.syncWithOrigin = False
685
Simon Hausmannb9847332007-03-20 20:54:23 +0100686 def extractFilesFromCommit(self, commit):
687 files = []
688 fnum = 0
689 while commit.has_key("depotFile%s" % fnum):
690 path = commit["depotFile%s" % fnum]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300691
692 found = [p for p in self.depotPaths
693 if path.startswith (p)]
694 if not found:
Simon Hausmannb9847332007-03-20 20:54:23 +0100695 fnum = fnum + 1
696 continue
697
698 file = {}
699 file["path"] = path
700 file["rev"] = commit["rev%s" % fnum]
701 file["action"] = commit["action%s" % fnum]
702 file["type"] = commit["type%s" % fnum]
703 files.append(file)
704 fnum = fnum + 1
705 return files
706
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300707 def stripRepoPath(self, path, prefixes):
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300708 if self.keepRepoPath:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300709 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -0300710
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300711 for p in prefixes:
712 if path.startswith(p):
713 path = path[len(p):]
714
715 return path
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -0300716
Simon Hausmann71b112d2007-05-19 11:54:11 +0200717 def splitFilesIntoBranches(self, commit):
Simon Hausmannd5904672007-05-19 11:07:32 +0200718 branches = {}
Simon Hausmann71b112d2007-05-19 11:54:11 +0200719 fnum = 0
720 while commit.has_key("depotFile%s" % fnum):
721 path = commit["depotFile%s" % fnum]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300722 found = [p for p in self.depotPaths
723 if path.startswith (p)]
724 if not found:
Simon Hausmann71b112d2007-05-19 11:54:11 +0200725 fnum = fnum + 1
726 continue
727
728 file = {}
729 file["path"] = path
730 file["rev"] = commit["rev%s" % fnum]
731 file["action"] = commit["action%s" % fnum]
732 file["type"] = commit["type%s" % fnum]
733 fnum = fnum + 1
734
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300735 relPath = self.stripRepoPath(path, self.depotPaths)
Simon Hausmannb9847332007-03-20 20:54:23 +0100736
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200737 for branch in self.knownBranches.keys():
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -0300738
739 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
740 if relPath.startswith(branch + "/"):
Simon Hausmannd5904672007-05-19 11:07:32 +0200741 if branch not in branches:
742 branches[branch] = []
Simon Hausmann71b112d2007-05-19 11:54:11 +0200743 branches[branch].append(file)
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200744 break
Simon Hausmannb9847332007-03-20 20:54:23 +0100745
746 return branches
747
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300748 ## Should move this out, doesn't use SELF.
749 def readP4Files(self, files):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300750 files = [f for f in files
Han-Wen Nienhuys982bb8a2007-05-23 18:49:35 -0300751 if f['action'] != 'delete']
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300752
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300753 if not files:
Han-Wen Nienhuysf2eda792007-05-23 18:49:35 -0300754 return
755
Scott Lamb78800192007-07-15 20:58:11 -0700756 filedata = p4CmdList('-x - print',
757 stdin='\n'.join(['%s#%s' % (f['path'], f['rev'])
758 for f in files]),
759 stdin_mode='w+')
760 if "p4ExitCode" in filedata[0]:
761 die("Problems executing p4. Error: [%d]."
762 % (filedata[0]['p4ExitCode']));
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300763
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300764 j = 0;
765 contents = {}
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300766 while j < len(filedata):
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300767 stat = filedata[j]
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300768 j += 1
769 text = ''
Han-Wen Nienhuys7530a402007-05-23 18:49:35 -0300770 while j < len(filedata) and filedata[j]['code'] in ('text',
771 'binary'):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300772 text += filedata[j]['data']
773 j += 1
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300774
Han-Wen Nienhuys1b9a4682007-05-23 18:49:35 -0300775
776 if not stat.has_key('depotFile'):
777 sys.stderr.write("p4 print fails with: %s\n" % repr(stat))
778 continue
779
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300780 contents[stat['depotFile']] = text
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300781
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -0300782 for f in files:
783 assert not f.has_key('data')
784 f['data'] = contents[f['path']]
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300785
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300786 def commit(self, details, files, branch, branchPrefixes, parent = ""):
Simon Hausmannb9847332007-03-20 20:54:23 +0100787 epoch = details["time"]
788 author = details["user"]
789
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200790 if self.verbose:
791 print "commit into %s" % branch
792
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -0300793 # start with reading files; if that fails, we should not
794 # create a commit.
795 new_files = []
796 for f in files:
797 if [p for p in branchPrefixes if f['path'].startswith(p)]:
798 new_files.append (f)
799 else:
800 sys.stderr.write("Ignoring file outside of prefix: %s\n" % path)
801 files = new_files
802 self.readP4Files(files)
803
804
805
806
Simon Hausmannb9847332007-03-20 20:54:23 +0100807 self.gitStream.write("commit %s\n" % branch)
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300808# gitStream.write("mark :%s\n" % details["change"])
Simon Hausmannb9847332007-03-20 20:54:23 +0100809 self.committedChanges.add(int(details["change"]))
810 committer = ""
Simon Hausmannb607e712007-05-20 10:55:54 +0200811 if author not in self.users:
812 self.getUserMapFromPerforceServer()
Simon Hausmannb9847332007-03-20 20:54:23 +0100813 if author in self.users:
Simon Hausmann0828ab12007-03-20 20:59:30 +0100814 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +0100815 else:
Simon Hausmann0828ab12007-03-20 20:59:30 +0100816 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +0100817
818 self.gitStream.write("committer %s\n" % committer)
819
820 self.gitStream.write("data <<EOT\n")
821 self.gitStream.write(details["desc"])
Simon Hausmann6581de02007-06-11 10:01:58 +0200822 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
823 % (','.join (branchPrefixes), details["change"]))
824 if len(details['options']) > 0:
825 self.gitStream.write(": options = %s" % details['options'])
826 self.gitStream.write("]\nEOT\n\n")
Simon Hausmannb9847332007-03-20 20:54:23 +0100827
828 if len(parent) > 0:
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200829 if self.verbose:
830 print "parent %s" % parent
Simon Hausmannb9847332007-03-20 20:54:23 +0100831 self.gitStream.write("from %s\n" % parent)
832
Simon Hausmannb9847332007-03-20 20:54:23 +0100833 for file in files:
Simon Hausmannb9847332007-03-20 20:54:23 +0100834 if file["type"] == "apple":
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300835 print "\nfile %s is a strange apple file that forks. Ignoring!" % file['path']
Simon Hausmannb9847332007-03-20 20:54:23 +0100836 continue
837
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300838 relPath = self.stripRepoPath(file['path'], branchPrefixes)
839 if file["action"] == "delete":
Simon Hausmannb9847332007-03-20 20:54:23 +0100840 self.gitStream.write("D %s\n" % relPath)
841 else:
842 mode = 644
843 if file["type"].startswith("x"):
844 mode = 755
845
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300846 data = file['data']
Simon Hausmannb9847332007-03-20 20:54:23 +0100847
Marius Storm-Olsenc1f91972007-05-24 14:07:55 +0200848 if self.isWindows and file["type"].endswith("text"):
849 data = data.replace("\r\n", "\n")
850
Han-Wen Nienhuys7530a402007-05-23 18:49:35 -0300851 self.gitStream.write("M %d inline %s\n" % (mode, relPath))
Simon Hausmannb9847332007-03-20 20:54:23 +0100852 self.gitStream.write("data %s\n" % len(data))
853 self.gitStream.write(data)
854 self.gitStream.write("\n")
855
856 self.gitStream.write("\n")
857
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200858 change = int(details["change"])
859
Simon Hausmann9bda3a82007-05-19 12:05:40 +0200860 if self.labels.has_key(change):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200861 label = self.labels[change]
862 labelDetails = label[0]
863 labelRevisions = label[1]
Simon Hausmann71b112d2007-05-19 11:54:11 +0200864 if self.verbose:
865 print "Change %s is labelled %s" % (change, labelDetails)
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200866
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300867 files = p4CmdList("files " + ' '.join (["%s...@%s" % (p, change)
868 for p in branchPrefixes]))
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200869
870 if len(files) == len(labelRevisions):
871
872 cleanedFiles = {}
873 for info in files:
874 if info["action"] == "delete":
875 continue
876 cleanedFiles[info["depotFile"]] = info["rev"]
877
878 if cleanedFiles == labelRevisions:
879 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
880 self.gitStream.write("from %s\n" % branch)
881
882 owner = labelDetails["Owner"]
883 tagger = ""
884 if author in self.users:
885 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
886 else:
887 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
888 self.gitStream.write("tagger %s\n" % tagger)
889 self.gitStream.write("data <<EOT\n")
890 self.gitStream.write(labelDetails["Description"])
891 self.gitStream.write("EOT\n\n")
892
893 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +0200894 if not self.silent:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300895 print ("Tag %s does not match with change %s: files do not match."
896 % (labelDetails["label"], change))
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200897
898 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +0200899 if not self.silent:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300900 print ("Tag %s does not match with change %s: file count is different."
901 % (labelDetails["label"], change))
Simon Hausmannb9847332007-03-20 20:54:23 +0100902
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300903 def getUserCacheFilename(self):
Simon Hausmannb2d2d162007-07-25 09:31:38 +0200904 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
905 return home + "/.gitp4-usercache.txt"
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300906
Simon Hausmannb607e712007-05-20 10:55:54 +0200907 def getUserMapFromPerforceServer(self):
Simon Hausmannebd81162007-05-24 00:24:52 +0200908 if self.userMapFromPerforceServer:
909 return
Simon Hausmannb9847332007-03-20 20:54:23 +0100910 self.users = {}
911
912 for output in p4CmdList("users"):
913 if not output.has_key("User"):
914 continue
915 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
916
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300917
918 s = ''
919 for (key, val) in self.users.items():
920 s += "%s\t%s\n" % (key, val)
921
922 open(self.getUserCacheFilename(), "wb").write(s)
Simon Hausmannebd81162007-05-24 00:24:52 +0200923 self.userMapFromPerforceServer = True
Simon Hausmannb607e712007-05-20 10:55:54 +0200924
925 def loadUserMapFromCache(self):
926 self.users = {}
Simon Hausmannebd81162007-05-24 00:24:52 +0200927 self.userMapFromPerforceServer = False
Simon Hausmannb607e712007-05-20 10:55:54 +0200928 try:
Han-Wen Nienhuys183b8ef2007-05-23 18:49:35 -0300929 cache = open(self.getUserCacheFilename(), "rb")
Simon Hausmannb607e712007-05-20 10:55:54 +0200930 lines = cache.readlines()
931 cache.close()
932 for line in lines:
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300933 entry = line.strip().split("\t")
Simon Hausmannb607e712007-05-20 10:55:54 +0200934 self.users[entry[0]] = entry[1]
935 except IOError:
936 self.getUserMapFromPerforceServer()
937
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200938 def getLabels(self):
939 self.labels = {}
940
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300941 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
Simon Hausmann10c32112007-04-08 10:15:47 +0200942 if len(l) > 0 and not self.silent:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300943 print "Finding files belonging to labels in %s" % `self.depotPath`
Simon Hausmann01ce1fe2007-04-07 23:46:50 +0200944
945 for output in l:
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200946 label = output["label"]
947 revisions = {}
948 newestChange = 0
Simon Hausmann71b112d2007-05-19 11:54:11 +0200949 if self.verbose:
950 print "Querying files for label %s" % label
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300951 for file in p4CmdList("files "
952 + ' '.join (["%s...@%s" % (p, label)
953 for p in self.depotPaths])):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200954 revisions[file["depotFile"]] = file["rev"]
955 change = int(file["change"])
956 if change > newestChange:
957 newestChange = change
958
Simon Hausmann9bda3a82007-05-19 12:05:40 +0200959 self.labels[newestChange] = [output, revisions]
960
961 if self.verbose:
962 print "Label changes: %s" % self.labels.keys()
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +0200963
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300964 def guessProjectName(self):
965 for p in self.depotPaths:
Simon Hausmann6e5295c2007-06-11 08:50:57 +0200966 if p.endswith("/"):
967 p = p[:-1]
968 p = p[p.strip().rfind("/") + 1:]
969 if not p.endswith("/"):
970 p += "/"
971 return p
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -0300972
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200973 def getBranchMapping(self):
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200974 lostAndFoundBranches = set()
975
Simon Hausmann4b97ffb2007-05-18 21:45:23 +0200976 for info in p4CmdList("branches"):
977 details = p4Cmd("branch -o %s" % info["branch"])
978 viewIdx = 0
979 while details.has_key("View%s" % viewIdx):
980 paths = details["View%s" % viewIdx].split(" ")
981 viewIdx = viewIdx + 1
982 # require standard //depot/foo/... //depot/bar/... mapping
983 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
984 continue
985 source = paths[0]
986 destination = paths[1]
Simon Hausmann6509e192007-06-07 09:41:53 +0200987 ## HACK
988 if source.startswith(self.depotPaths[0]) and destination.startswith(self.depotPaths[0]):
989 source = source[len(self.depotPaths[0]):-4]
990 destination = destination[len(self.depotPaths[0]):-4]
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200991
Simon Hausmann1a2edf42007-06-17 15:10:24 +0200992 if destination in self.knownBranches:
993 if not self.silent:
994 print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
995 print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
996 continue
997
Simon Hausmann6555b2c2007-06-17 11:25:34 +0200998 self.knownBranches[destination] = source
999
1000 lostAndFoundBranches.discard(destination)
1001
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001002 if source not in self.knownBranches:
Simon Hausmann6555b2c2007-06-17 11:25:34 +02001003 lostAndFoundBranches.add(source)
1004
1005
1006 for branch in lostAndFoundBranches:
1007 self.knownBranches[branch] = branch
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001008
1009 def listExistingP4GitBranches(self):
Simon Hausmann144ff462007-07-18 17:27:50 +02001010 # branches holds mapping from name to commit
1011 branches = p4BranchesInGit(self.importIntoRemotes)
1012 self.p4BranchesInGit = branches.keys()
1013 for branch in branches.keys():
1014 self.initialParents[self.refPrefix + branch] = branches[branch]
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001015
Simon Hausmannabcd7902007-05-24 22:25:36 +02001016 def createOrUpdateBranchesFromOrigin(self):
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001017 if not self.silent:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001018 print ("Creating/updating branch(es) in %s based on origin branch(es)"
1019 % self.refPrefix)
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001020
Simon Hausmanncae7b732007-06-10 10:57:40 +02001021 originPrefix = "origin/p4/"
1022
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -03001023 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
1024 line = line.strip()
Simon Hausmanncae7b732007-06-10 10:57:40 +02001025 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001026 continue
Simon Hausmann65c5f3e2007-05-25 08:44:41 +02001027
Simon Hausmanncae7b732007-06-10 10:57:40 +02001028 headName = line[len(originPrefix):]
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001029 remoteHead = self.refPrefix + headName
Simon Hausmanncae7b732007-06-10 10:57:40 +02001030 originHead = line
Simon Hausmannabcd7902007-05-24 22:25:36 +02001031
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001032 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
1033 if (not original.has_key('depot-paths')
1034 or not original.has_key('change')):
Simon Hausmann65c5f3e2007-05-25 08:44:41 +02001035 continue
1036
Simon Hausmannabcd7902007-05-24 22:25:36 +02001037 update = False
Simon Hausmann4280e532007-05-25 08:49:18 +02001038 if not gitBranchExists(remoteHead):
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001039 if self.verbose:
1040 print "creating %s" % remoteHead
Simon Hausmannabcd7902007-05-24 22:25:36 +02001041 update = True
1042 else:
Simon Hausmanna3fdd572007-06-07 22:54:32 +02001043 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001044 if settings.has_key('change') > 0:
1045 if settings['depot-paths'] == original['depot-paths']:
1046 originP4Change = int(original['change'])
1047 p4Change = int(settings['change'])
Simon Hausmannabcd7902007-05-24 22:25:36 +02001048 if originP4Change > p4Change:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001049 print ("%s (%s) is newer than %s (%s). "
1050 "Updating p4 branch from origin."
1051 % (originHead, originP4Change,
1052 remoteHead, p4Change))
Simon Hausmannabcd7902007-05-24 22:25:36 +02001053 update = True
1054 else:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001055 print ("Ignoring: %s was imported from %s while "
1056 "%s was imported from %s"
1057 % (originHead, ','.join(original['depot-paths']),
1058 remoteHead, ','.join(settings['depot-paths'])))
Simon Hausmannabcd7902007-05-24 22:25:36 +02001059
1060 if update:
1061 system("git update-ref %s %s" % (remoteHead, originHead))
Simon Hausmannd1874ed2007-05-24 21:23:04 +02001062
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001063 def updateOptionDict(self, d):
1064 option_keys = {}
1065 if self.keepRepoPath:
1066 option_keys['keepRepoPath'] = 1
1067
1068 d["options"] = ' '.join(sorted(option_keys.keys()))
1069
1070 def readOptions(self, d):
1071 self.keepRepoPath = (d.has_key('options')
1072 and ('keepRepoPath' in d['options']))
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001073
Simon Hausmannb9847332007-03-20 20:54:23 +01001074 def run(self, args):
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001075 self.depotPaths = []
Simon Hausmann179caeb2007-03-22 22:17:42 +01001076 self.changeRange = ""
1077 self.initialParent = ""
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001078 self.previousDepotPaths = []
Han-Wen Nienhuysce6f33c2007-05-23 16:46:29 -03001079
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001080 # map from branch depot path to parent branch
1081 self.knownBranches = {}
1082 self.initialParents = {}
Simon Hausmanncae7b732007-06-10 10:57:40 +02001083 self.hasOrigin = gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
Simon Hausmanna43ff002007-06-11 09:59:27 +02001084 if not self.syncWithOrigin:
1085 self.hasOrigin = False
Simon Hausmann179caeb2007-03-22 22:17:42 +01001086
Simon Hausmanna028a982007-05-23 00:03:08 +02001087 if self.importIntoRemotes:
1088 self.refPrefix = "refs/remotes/p4/"
1089 else:
Marius Storm-Olsendb775552007-06-07 15:13:59 +02001090 self.refPrefix = "refs/heads/p4/"
Simon Hausmanna028a982007-05-23 00:03:08 +02001091
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001092 if self.syncWithOrigin and self.hasOrigin:
1093 if not self.silent:
1094 print "Syncing with origin first by calling git fetch origin"
1095 system("git fetch origin")
Simon Hausmann10f880f2007-05-24 22:28:28 +02001096
Simon Hausmann569d1bd2007-03-22 21:34:16 +01001097 if len(self.branch) == 0:
Marius Storm-Olsendb775552007-06-07 15:13:59 +02001098 self.branch = self.refPrefix + "master"
Simon Hausmanna028a982007-05-23 00:03:08 +02001099 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
Simon Hausmann48df6fd2007-05-17 21:18:53 +02001100 system("git update-ref %s refs/heads/p4" % self.branch)
Simon Hausmann48df6fd2007-05-17 21:18:53 +02001101 system("git branch -D p4");
Simon Hausmannfaf1bd22007-05-21 10:05:30 +02001102 # create it /after/ importing, when master exists
Simon Hausmanna028a982007-05-23 00:03:08 +02001103 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes:
Simon Hausmanna3c55c02007-05-27 15:48:01 +02001104 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
Simon Hausmann179caeb2007-03-22 22:17:42 +01001105
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001106 # TODO: should always look at previous commits,
1107 # merge with previous imports, if possible.
1108 if args == []:
Simon Hausmannd414c742007-05-25 11:36:42 +02001109 if self.hasOrigin:
1110 self.createOrUpdateBranchesFromOrigin()
Simon Hausmannabcd7902007-05-24 22:25:36 +02001111 self.listExistingP4GitBranches()
1112
1113 if len(self.p4BranchesInGit) > 1:
1114 if not self.silent:
1115 print "Importing from/into multiple branches"
1116 self.detectBranches = True
Simon Hausmann967f72e2007-03-23 09:30:41 +01001117
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001118 if self.verbose:
1119 print "branches: %s" % self.p4BranchesInGit
1120
1121 p4Change = 0
1122 for branch in self.p4BranchesInGit:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001123 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001124
1125 settings = extractSettingsGitLog(logMsg)
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001126
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001127 self.readOptions(settings)
1128 if (settings.has_key('depot-paths')
1129 and settings.has_key ('change')):
1130 change = int(settings['change']) + 1
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001131 p4Change = max(p4Change, change)
1132
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001133 depotPaths = sorted(settings['depot-paths'])
1134 if self.previousDepotPaths == []:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001135 self.previousDepotPaths = depotPaths
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001136 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001137 paths = []
1138 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
Simon Hausmann583e1702007-06-07 09:37:13 +02001139 for i in range(0, min(len(cur), len(prev))):
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001140 if cur[i] <> prev[i]:
Simon Hausmann583e1702007-06-07 09:37:13 +02001141 i = i - 1
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001142 break
1143
Simon Hausmann583e1702007-06-07 09:37:13 +02001144 paths.append (cur[:i + 1])
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001145
1146 self.previousDepotPaths = paths
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001147
1148 if p4Change > 0:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001149 self.depotPaths = sorted(self.previousDepotPaths)
Simon Hausmannd5904672007-05-19 11:07:32 +02001150 self.changeRange = "@%s,#head" % p4Change
Simon Hausmann330f53b2007-06-07 09:39:51 +02001151 if not self.detectBranches:
1152 self.initialParent = parseRevision(self.branch)
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001153 if not self.silent and not self.detectBranches:
Simon Hausmann967f72e2007-03-23 09:30:41 +01001154 print "Performing incremental import into %s git branch" % self.branch
Simon Hausmann569d1bd2007-03-22 21:34:16 +01001155
Simon Hausmannf9162f62007-05-17 09:02:45 +02001156 if not self.branch.startswith("refs/"):
1157 self.branch = "refs/heads/" + self.branch
Simon Hausmann179caeb2007-03-22 22:17:42 +01001158
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001159 if len(args) == 0 and self.depotPaths:
Simon Hausmannb9847332007-03-20 20:54:23 +01001160 if not self.silent:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001161 print "Depot paths: %s" % ' '.join(self.depotPaths)
Simon Hausmannb9847332007-03-20 20:54:23 +01001162 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001163 if self.depotPaths and self.depotPaths != args:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001164 print ("previous import used depot path %s and now %s was specified. "
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001165 "This doesn't work!" % (' '.join (self.depotPaths),
1166 ' '.join (args)))
Simon Hausmannb9847332007-03-20 20:54:23 +01001167 sys.exit(1)
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001168
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001169 self.depotPaths = sorted(args)
Simon Hausmannb9847332007-03-20 20:54:23 +01001170
Simon Hausmannb9847332007-03-20 20:54:23 +01001171 self.revision = ""
1172 self.users = {}
Simon Hausmannb9847332007-03-20 20:54:23 +01001173
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001174 newPaths = []
1175 for p in self.depotPaths:
1176 if p.find("@") != -1:
1177 atIdx = p.index("@")
1178 self.changeRange = p[atIdx:]
1179 if self.changeRange == "@all":
1180 self.changeRange = ""
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001181 elif ',' not in self.changeRange:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001182 self.revision = self.changeRange
1183 self.changeRange = ""
Han-Wen Nienhuys7fcff9d2007-07-23 15:56:37 -07001184 p = p[:atIdx]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001185 elif p.find("#") != -1:
1186 hashIdx = p.index("#")
1187 self.revision = p[hashIdx:]
Han-Wen Nienhuys7fcff9d2007-07-23 15:56:37 -07001188 p = p[:hashIdx]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001189 elif self.previousDepotPaths == []:
1190 self.revision = "#head"
Simon Hausmannb9847332007-03-20 20:54:23 +01001191
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001192 p = re.sub ("\.\.\.$", "", p)
1193 if not p.endswith("/"):
1194 p += "/"
1195
1196 newPaths.append(p)
1197
1198 self.depotPaths = newPaths
1199
Simon Hausmannb9847332007-03-20 20:54:23 +01001200
Simon Hausmannb607e712007-05-20 10:55:54 +02001201 self.loadUserMapFromCache()
Simon Hausmanncb53e1f2007-04-08 00:12:02 +02001202 self.labels = {}
1203 if self.detectLabels:
1204 self.getLabels();
Simon Hausmannb9847332007-03-20 20:54:23 +01001205
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001206 if self.detectBranches:
Simon Hausmanndf450922007-06-08 08:49:22 +02001207 ## FIXME - what's a P4 projectName ?
1208 self.projectName = self.guessProjectName()
1209
1210 if not self.hasOrigin:
1211 self.getBranchMapping();
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001212 if self.verbose:
1213 print "p4-git branches: %s" % self.p4BranchesInGit
1214 print "initial parents: %s" % self.initialParents
1215 for b in self.p4BranchesInGit:
1216 if b != "master":
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001217
1218 ## FIXME
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001219 b = b[len(self.projectName):]
1220 self.createdBranches.add(b)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001221
Simon Hausmannf291b4e2007-04-14 11:21:50 +02001222 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
Simon Hausmannb9847332007-03-20 20:54:23 +01001223
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001224 importProcess = subprocess.Popen(["git", "fast-import"],
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001225 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
1226 stderr=subprocess.PIPE);
Simon Hausmann08483582007-05-15 14:31:06 +02001227 self.gitOutput = importProcess.stdout
1228 self.gitStream = importProcess.stdin
1229 self.gitError = importProcess.stderr
Simon Hausmannb9847332007-03-20 20:54:23 +01001230
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001231 if self.revision:
Simon Hausmanna9d1a272007-06-11 23:28:03 +02001232 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 +01001233
1234 details = { "user" : "git perforce import user", "time" : int(time.time()) }
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001235 details["desc"] = ("Initial import of %s from the state at revision %s"
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001236 % (' '.join(self.depotPaths), self.revision))
Simon Hausmannb9847332007-03-20 20:54:23 +01001237 details["change"] = self.revision
1238 newestRevision = 0
1239
1240 fileCnt = 0
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001241 for info in p4CmdList("files "
1242 + ' '.join(["%s...%s"
1243 % (p, self.revision)
1244 for p in self.depotPaths])):
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -03001245
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -03001246 if info['code'] == 'error':
1247 sys.stderr.write("p4 returned an error: %s\n"
1248 % info['data'])
1249 sys.exit(1)
1250
1251
Simon Hausmannb9847332007-03-20 20:54:23 +01001252 change = int(info["change"])
1253 if change > newestRevision:
1254 newestRevision = change
1255
1256 if info["action"] == "delete":
Simon Hausmannc45b1cf2007-04-08 10:13:32 +02001257 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1258 #fileCnt = fileCnt + 1
Simon Hausmannb9847332007-03-20 20:54:23 +01001259 continue
1260
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -03001261 for prop in ["depotFile", "rev", "action", "type" ]:
Simon Hausmannb9847332007-03-20 20:54:23 +01001262 details["%s%s" % (prop, fileCnt)] = info[prop]
1263
1264 fileCnt = fileCnt + 1
1265
1266 details["change"] = newestRevision
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001267 self.updateOptionDict(details)
Simon Hausmannb9847332007-03-20 20:54:23 +01001268 try:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001269 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
Simon Hausmannc7157062007-03-20 21:13:49 +01001270 except IOError:
Simon Hausmannfd4ca862007-04-13 22:21:10 +02001271 print "IO error with git fast-import. Is your git version recent enough?"
Simon Hausmannb9847332007-03-20 20:54:23 +01001272 print self.gitError.read()
1273
1274 else:
1275 changes = []
1276
Simon Hausmann0828ab12007-03-20 20:59:30 +01001277 if len(self.changesFile) > 0:
Simon Hausmannb9847332007-03-20 20:54:23 +01001278 output = open(self.changesFile).readlines()
1279 changeSet = Set()
1280 for line in output:
1281 changeSet.add(int(line))
1282
1283 for change in changeSet:
1284 changes.append(change)
1285
1286 changes.sort()
1287 else:
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001288 if self.verbose:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001289 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001290 self.changeRange)
1291 assert self.depotPaths
1292 output = read_pipe_lines("p4 changes " + ' '.join (["%s...%s" % (p, self.changeRange)
1293 for p in self.depotPaths]))
Simon Hausmannb9847332007-03-20 20:54:23 +01001294
1295 for line in output:
1296 changeNum = line.split(" ")[1]
1297 changes.append(changeNum)
1298
Han-Wen Nienhuysa4eba022007-07-23 15:51:49 -07001299 changes.sort()
Simon Hausmannb9847332007-03-20 20:54:23 +01001300
Simon Hausmann01a9c9c2007-05-23 00:07:35 +02001301 if len(self.maxChanges) > 0:
Han-Wen Nienhuys7fcff9d2007-07-23 15:56:37 -07001302 changes = changes[:min(int(self.maxChanges), len(changes))]
Simon Hausmann01a9c9c2007-05-23 00:07:35 +02001303
Simon Hausmannb9847332007-03-20 20:54:23 +01001304 if len(changes) == 0:
Simon Hausmann0828ab12007-03-20 20:59:30 +01001305 if not self.silent:
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001306 print "No changes to import!"
Simon Hausmann1f52af62007-04-08 00:07:02 +02001307 return True
Simon Hausmannb9847332007-03-20 20:54:23 +01001308
Simon Hausmanna9d1a272007-06-11 23:28:03 +02001309 if not self.silent and not self.detectBranches:
1310 print "Import destination: %s" % self.branch
1311
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001312 self.updatedBranches = set()
1313
Simon Hausmannb9847332007-03-20 20:54:23 +01001314 cnt = 1
1315 for change in changes:
1316 description = p4Cmd("describe %s" % change)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001317 self.updateOptionDict(description)
Simon Hausmannb9847332007-03-20 20:54:23 +01001318
Simon Hausmann0828ab12007-03-20 20:59:30 +01001319 if not self.silent:
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001320 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
Simon Hausmannb9847332007-03-20 20:54:23 +01001321 sys.stdout.flush()
1322 cnt = cnt + 1
1323
1324 try:
Simon Hausmannb9847332007-03-20 20:54:23 +01001325 if self.detectBranches:
Simon Hausmann71b112d2007-05-19 11:54:11 +02001326 branches = self.splitFilesIntoBranches(description)
Simon Hausmannd5904672007-05-19 11:07:32 +02001327 for branch in branches.keys():
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001328 ## HACK --hwn
1329 branchPrefix = self.depotPaths[0] + branch + "/"
Simon Hausmannb9847332007-03-20 20:54:23 +01001330
Simon Hausmannb9847332007-03-20 20:54:23 +01001331 parent = ""
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001332
Simon Hausmannd5904672007-05-19 11:07:32 +02001333 filesForCommit = branches[branch]
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001334
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001335 if self.verbose:
1336 print "branch is %s" % branch
1337
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001338 self.updatedBranches.add(branch)
1339
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001340 if branch not in self.createdBranches:
Simon Hausmannb9847332007-03-20 20:54:23 +01001341 self.createdBranches.add(branch)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001342 parent = self.knownBranches[branch]
Simon Hausmannb9847332007-03-20 20:54:23 +01001343 if parent == branch:
1344 parent = ""
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001345 elif self.verbose:
1346 print "parent determined through known branches: %s" % parent
Simon Hausmannb9847332007-03-20 20:54:23 +01001347
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001348 # main branch? use master
1349 if branch == "main":
1350 branch = "master"
1351 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001352
1353 ## FIXME
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001354 branch = self.projectName + branch
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001355
1356 if parent == "main":
1357 parent = "master"
1358 elif len(parent) > 0:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001359 ## FIXME
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001360 parent = self.projectName + parent
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001361
Simon Hausmanna028a982007-05-23 00:03:08 +02001362 branch = self.refPrefix + branch
Simon Hausmannb9847332007-03-20 20:54:23 +01001363 if len(parent) > 0:
Simon Hausmanna028a982007-05-23 00:03:08 +02001364 parent = self.refPrefix + parent
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001365
1366 if self.verbose:
1367 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1368
1369 if len(parent) == 0 and branch in self.initialParents:
1370 parent = self.initialParents[branch]
1371 del self.initialParents[branch]
1372
Simon Hausmann86fda6a2007-06-11 08:54:45 +02001373 self.commit(description, filesForCommit, branch, [branchPrefix], parent)
Simon Hausmannb9847332007-03-20 20:54:23 +01001374 else:
Simon Hausmann71b112d2007-05-19 11:54:11 +02001375 files = self.extractFilesFromCommit(description)
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001376 self.commit(description, files, self.branch, self.depotPaths,
1377 self.initialParent)
Simon Hausmannb9847332007-03-20 20:54:23 +01001378 self.initialParent = ""
1379 except IOError:
1380 print self.gitError.read()
1381 sys.exit(1)
1382
Simon Hausmann341dc1c2007-05-21 00:39:16 +02001383 if not self.silent:
1384 print ""
1385 if len(self.updatedBranches) > 0:
1386 sys.stdout.write("Updated branches: ")
1387 for b in self.updatedBranches:
1388 sys.stdout.write("%s " % b)
1389 sys.stdout.write("\n")
Simon Hausmannb9847332007-03-20 20:54:23 +01001390
Simon Hausmannb9847332007-03-20 20:54:23 +01001391
1392 self.gitStream.close()
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001393 if importProcess.wait() != 0:
1394 die("fast-import failed: %s" % self.gitError.read())
Simon Hausmannb9847332007-03-20 20:54:23 +01001395 self.gitOutput.close()
1396 self.gitError.close()
1397
Simon Hausmannb9847332007-03-20 20:54:23 +01001398 return True
1399
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001400class P4Rebase(Command):
1401 def __init__(self):
1402 Command.__init__(self)
Simon Hausmann01265102007-05-25 10:36:10 +02001403 self.options = [ ]
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001404 self.description = ("Fetches the latest revision from perforce and "
1405 + "rebases the current work (branch) against it")
Simon Hausmann68c42152007-06-07 12:51:03 +02001406 self.verbose = False
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001407
1408 def run(self, args):
1409 sync = P4Sync()
1410 sync.run([])
Simon Hausmannd7e38682007-06-12 14:34:46 +02001411
1412 [upstream, settings] = findUpstreamBranchPoint()
1413 if len(upstream) == 0:
1414 die("Cannot find upstream branchpoint for rebase")
1415
1416 # the branchpoint may be p4/foo~3, so strip off the parent
1417 upstream = re.sub("~[0-9]+$", "", upstream)
1418
1419 print "Rebasing the current branch onto %s" % upstream
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -03001420 oldHead = read_pipe("git rev-parse HEAD").strip()
Simon Hausmannd7e38682007-06-12 14:34:46 +02001421 system("git rebase %s" % upstream)
Simon Hausmann1f52af62007-04-08 00:07:02 +02001422 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001423 return True
1424
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001425class P4Clone(P4Sync):
1426 def __init__(self):
1427 P4Sync.__init__(self)
1428 self.description = "Creates a new git repository and imports from Perforce into it"
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001429 self.usage = "usage: %prog [options] //depot/path[@revRange]"
1430 self.options.append(
1431 optparse.make_option("--destination", dest="cloneDestination",
1432 action='store', default=None,
1433 help="where to leave result of the clone"))
1434 self.cloneDestination = None
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001435 self.needsGit = False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001436
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001437 def defaultDestination(self, args):
1438 ## TODO: use common prefix of args?
1439 depotPath = args[0]
1440 depotDir = re.sub("(@[^@]*)$", "", depotPath)
1441 depotDir = re.sub("(#[^#]*)$", "", depotDir)
1442 depotDir = re.sub(r"\.\.\.$,", "", depotDir)
1443 depotDir = re.sub(r"/$", "", depotDir)
1444 return os.path.split(depotDir)[1]
1445
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001446 def run(self, args):
1447 if len(args) < 1:
1448 return False
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001449
1450 if self.keepRepoPath and not self.cloneDestination:
1451 sys.stderr.write("Must specify destination for --keep-path\n")
1452 sys.exit(1)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001453
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001454 depotPaths = args
Simon Hausmann5e100b52007-06-07 21:12:25 +02001455
1456 if not self.cloneDestination and len(depotPaths) > 1:
1457 self.cloneDestination = depotPaths[-1]
1458 depotPaths = depotPaths[:-1]
1459
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001460 for p in depotPaths:
1461 if not p.startswith("//"):
1462 return False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001463
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001464 if not self.cloneDestination:
Marius Storm-Olsen98ad4fa2007-06-07 15:08:33 +02001465 self.cloneDestination = self.defaultDestination(args)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001466
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001467 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
Kevin Greenc3bf3f12007-06-11 16:48:07 -04001468 if not os.path.exists(self.cloneDestination):
1469 os.makedirs(self.cloneDestination)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001470 os.chdir(self.cloneDestination)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001471 system("git init")
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001472 self.gitdir = os.getcwd() + "/.git"
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001473 if not P4Sync.run(self, depotPaths):
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001474 return False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001475 if self.branch != "master":
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02001476 if gitBranchExists("refs/remotes/p4/master"):
1477 system("git branch master refs/remotes/p4/master")
1478 system("git checkout -f")
1479 else:
1480 print "Could not detect main branch. No checkout/master branch created."
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001481
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02001482 return True
1483
Simon Hausmann09d89de2007-06-20 23:10:28 +02001484class P4Branches(Command):
1485 def __init__(self):
1486 Command.__init__(self)
1487 self.options = [ ]
1488 self.description = ("Shows the git branches that hold imports and their "
1489 + "corresponding perforce depot paths")
1490 self.verbose = False
1491
1492 def run(self, args):
1493 cmdline = "git rev-parse --symbolic "
1494 cmdline += " --remotes"
1495
1496 for line in read_pipe_lines(cmdline):
1497 line = line.strip()
1498
1499 if not line.startswith('p4/') or line == "p4/HEAD":
1500 continue
1501 branch = line
1502
1503 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
1504 settings = extractSettingsGitLog(log)
1505
1506 print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
1507 return True
1508
Simon Hausmannb9847332007-03-20 20:54:23 +01001509class HelpFormatter(optparse.IndentedHelpFormatter):
1510 def __init__(self):
1511 optparse.IndentedHelpFormatter.__init__(self)
1512
1513 def format_description(self, description):
1514 if description:
1515 return description + "\n"
1516 else:
1517 return ""
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001518
Simon Hausmann86949ee2007-03-19 20:59:12 +01001519def printUsage(commands):
1520 print "usage: %s <command> [options]" % sys.argv[0]
1521 print ""
1522 print "valid commands: %s" % ", ".join(commands)
1523 print ""
1524 print "Try %s <command> --help for command specific help." % sys.argv[0]
1525 print ""
1526
1527commands = {
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001528 "debug" : P4Debug,
1529 "submit" : P4Submit,
1530 "sync" : P4Sync,
1531 "rebase" : P4Rebase,
1532 "clone" : P4Clone,
Simon Hausmann09d89de2007-06-20 23:10:28 +02001533 "rollback" : P4RollBack,
1534 "branches" : P4Branches
Simon Hausmann86949ee2007-03-19 20:59:12 +01001535}
1536
Simon Hausmann86949ee2007-03-19 20:59:12 +01001537
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001538def main():
1539 if len(sys.argv[1:]) == 0:
1540 printUsage(commands.keys())
1541 sys.exit(2)
Simon Hausmann86949ee2007-03-19 20:59:12 +01001542
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001543 cmd = ""
1544 cmdName = sys.argv[1]
1545 try:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001546 klass = commands[cmdName]
1547 cmd = klass()
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001548 except KeyError:
1549 print "unknown command %s" % cmdName
1550 print ""
1551 printUsage(commands.keys())
1552 sys.exit(2)
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001553
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001554 options = cmd.options
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001555 cmd.gitdir = os.environ.get("GIT_DIR", None)
Simon Hausmann86949ee2007-03-19 20:59:12 +01001556
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001557 args = sys.argv[2:]
Simon Hausmanne20a9e52007-03-26 00:13:51 +02001558
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001559 if len(options) > 0:
1560 options.append(optparse.make_option("--git-dir", dest="gitdir"))
Simon Hausmanne20a9e52007-03-26 00:13:51 +02001561
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001562 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
1563 options,
1564 description = cmd.description,
1565 formatter = HelpFormatter())
Simon Hausmann86949ee2007-03-19 20:59:12 +01001566
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001567 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
1568 global verbose
1569 verbose = cmd.verbose
1570 if cmd.needsGit:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001571 if cmd.gitdir == None:
1572 cmd.gitdir = os.path.abspath(".git")
1573 if not isValidGitDir(cmd.gitdir):
1574 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
1575 if os.path.exists(cmd.gitdir):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001576 cdup = read_pipe("git rev-parse --show-cdup").strip()
1577 if len(cdup) > 0:
1578 os.chdir(cdup);
1579
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001580 if not isValidGitDir(cmd.gitdir):
1581 if isValidGitDir(cmd.gitdir + "/.git"):
1582 cmd.gitdir += "/.git"
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001583 else:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001584 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
Simon Hausmann8910ac02007-03-26 08:18:55 +02001585
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03001586 os.environ["GIT_DIR"] = cmd.gitdir
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001587
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001588 if not cmd.run(args):
1589 parser.print_help()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001590
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001591
1592if __name__ == '__main__':
1593 main()