blob: dafc4a2c82eb795eb1f5e7eff2998c26760985ea [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
Reilly Grant1d7367d2009-09-10 00:02:38 -070011import optparse, sys, os, marshal, subprocess, shelve
12import tempfile, getopt, os.path, time, platform
Han-Wen Nienhuysce6f33c2007-05-23 16:46:29 -030013import re
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -030014
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030015verbose = False
Simon Hausmann86949ee2007-03-19 20:59:12 +010016
Anand Kumria21a50752008-08-10 19:26:28 +010017
18def p4_build_cmd(cmd):
19 """Build a suitable p4 command line.
20
21 This consolidates building and returning a p4 command line into one
22 location. It means that hooking into the environment, or other configuration
23 can be done more easily.
24 """
Luke Diamand6de040d2011-10-16 10:47:52 -040025 real_cmd = ["p4"]
Anand Kumriaabcaf072008-08-10 19:26:31 +010026
27 user = gitConfig("git-p4.user")
28 if len(user) > 0:
Luke Diamand6de040d2011-10-16 10:47:52 -040029 real_cmd += ["-u",user]
Anand Kumriaabcaf072008-08-10 19:26:31 +010030
31 password = gitConfig("git-p4.password")
32 if len(password) > 0:
Luke Diamand6de040d2011-10-16 10:47:52 -040033 real_cmd += ["-P", password]
Anand Kumriaabcaf072008-08-10 19:26:31 +010034
35 port = gitConfig("git-p4.port")
36 if len(port) > 0:
Luke Diamand6de040d2011-10-16 10:47:52 -040037 real_cmd += ["-p", port]
Anand Kumriaabcaf072008-08-10 19:26:31 +010038
39 host = gitConfig("git-p4.host")
40 if len(host) > 0:
Luke Diamand6de040d2011-10-16 10:47:52 -040041 real_cmd += ["-h", host]
Anand Kumriaabcaf072008-08-10 19:26:31 +010042
43 client = gitConfig("git-p4.client")
44 if len(client) > 0:
Luke Diamand6de040d2011-10-16 10:47:52 -040045 real_cmd += ["-c", client]
Anand Kumriaabcaf072008-08-10 19:26:31 +010046
Luke Diamand6de040d2011-10-16 10:47:52 -040047
48 if isinstance(cmd,basestring):
49 real_cmd = ' '.join(real_cmd) + ' ' + cmd
50 else:
51 real_cmd += cmd
Anand Kumria21a50752008-08-10 19:26:28 +010052 return real_cmd
53
Robert Blum053fd0c2008-08-01 12:50:03 -070054def chdir(dir):
Luke Diamand6de040d2011-10-16 10:47:52 -040055 # P4 uses the PWD environment variable rather than getcwd(). Since we're
Gary Gibbonsbf1d68f2011-12-09 18:48:16 -050056 # not using the shell, we have to set it ourselves. This path could
57 # be relative, so go there first, then figure out where we ended up.
Robert Blum053fd0c2008-08-01 12:50:03 -070058 os.chdir(dir)
Gary Gibbonsbf1d68f2011-12-09 18:48:16 -050059 os.environ['PWD'] = os.getcwd()
Robert Blum053fd0c2008-08-01 12:50:03 -070060
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -030061def die(msg):
62 if verbose:
63 raise Exception(msg)
64 else:
65 sys.stderr.write(msg + "\n")
66 sys.exit(1)
67
Luke Diamand6de040d2011-10-16 10:47:52 -040068def write_pipe(c, stdin):
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030069 if verbose:
Luke Diamand6de040d2011-10-16 10:47:52 -040070 sys.stderr.write('Writing pipe: %s\n' % str(c))
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030071
Luke Diamand6de040d2011-10-16 10:47:52 -040072 expand = isinstance(c,basestring)
73 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
74 pipe = p.stdin
75 val = pipe.write(stdin)
76 pipe.close()
77 if p.wait():
78 die('Command failed: %s' % str(c))
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030079
80 return val
81
Luke Diamand6de040d2011-10-16 10:47:52 -040082def p4_write_pipe(c, stdin):
Anand Kumriad9429192008-08-14 23:40:38 +010083 real_cmd = p4_build_cmd(c)
Luke Diamand6de040d2011-10-16 10:47:52 -040084 return write_pipe(real_cmd, stdin)
Anand Kumriad9429192008-08-14 23:40:38 +010085
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -030086def read_pipe(c, ignore_error=False):
87 if verbose:
Luke Diamand6de040d2011-10-16 10:47:52 -040088 sys.stderr.write('Reading pipe: %s\n' % str(c))
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -030089
Luke Diamand6de040d2011-10-16 10:47:52 -040090 expand = isinstance(c,basestring)
91 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
92 pipe = p.stdout
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030093 val = pipe.read()
Luke Diamand6de040d2011-10-16 10:47:52 -040094 if p.wait() and not ignore_error:
95 die('Command failed: %s' % str(c))
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -030096
97 return val
98
Anand Kumriad9429192008-08-14 23:40:38 +010099def p4_read_pipe(c, ignore_error=False):
100 real_cmd = p4_build_cmd(c)
101 return read_pipe(real_cmd, ignore_error)
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300102
Han-Wen Nienhuysbce4c5f2007-05-23 17:14:33 -0300103def read_pipe_lines(c):
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300104 if verbose:
Luke Diamand6de040d2011-10-16 10:47:52 -0400105 sys.stderr.write('Reading pipe: %s\n' % str(c))
106
107 expand = isinstance(c, basestring)
108 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
109 pipe = p.stdout
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300110 val = pipe.readlines()
Luke Diamand6de040d2011-10-16 10:47:52 -0400111 if pipe.close() or p.wait():
112 die('Command failed: %s' % str(c))
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300113
114 return val
Simon Hausmanncaace112007-05-15 14:57:57 +0200115
Anand Kumria23181212008-08-10 19:26:24 +0100116def p4_read_pipe_lines(c):
117 """Specifically invoke p4 on the command supplied. """
Anand Kumria155af832008-08-10 19:26:30 +0100118 real_cmd = p4_build_cmd(c)
Anand Kumria23181212008-08-10 19:26:24 +0100119 return read_pipe_lines(real_cmd)
120
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -0300121def system(cmd):
Luke Diamand6de040d2011-10-16 10:47:52 -0400122 expand = isinstance(cmd,basestring)
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300123 if verbose:
Luke Diamand6de040d2011-10-16 10:47:52 -0400124 sys.stderr.write("executing %s\n" % str(cmd))
125 subprocess.check_call(cmd, shell=expand)
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -0300126
Anand Kumriabf9320f2008-08-10 19:26:26 +0100127def p4_system(cmd):
128 """Specifically invoke p4 as the system command. """
Anand Kumria155af832008-08-10 19:26:30 +0100129 real_cmd = p4_build_cmd(cmd)
Luke Diamand6de040d2011-10-16 10:47:52 -0400130 expand = isinstance(real_cmd, basestring)
131 subprocess.check_call(real_cmd, shell=expand)
132
133def p4_integrate(src, dest):
134 p4_system(["integrate", "-Dt", src, dest])
135
136def p4_sync(path):
137 p4_system(["sync", path])
138
139def p4_add(f):
140 p4_system(["add", f])
141
142def p4_delete(f):
143 p4_system(["delete", f])
144
145def p4_edit(f):
146 p4_system(["edit", f])
147
148def p4_revert(f):
149 p4_system(["revert", f])
150
151def p4_reopen(type, file):
152 p4_system(["reopen", "-t", type, file])
Anand Kumriabf9320f2008-08-10 19:26:26 +0100153
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -0400154#
155# Canonicalize the p4 type and return a tuple of the
156# base type, plus any modifiers. See "p4 help filetypes"
157# for a list and explanation.
158#
159def split_p4_type(p4type):
David Brownb9fc6ea2007-09-19 13:12:48 -0700160
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -0400161 p4_filetypes_historical = {
162 "ctempobj": "binary+Sw",
163 "ctext": "text+C",
164 "cxtext": "text+Cx",
165 "ktext": "text+k",
166 "kxtext": "text+kx",
167 "ltext": "text+F",
168 "tempobj": "binary+FSw",
169 "ubinary": "binary+F",
170 "uresource": "resource+F",
171 "uxbinary": "binary+Fx",
172 "xbinary": "binary+x",
173 "xltext": "text+Fx",
174 "xtempobj": "binary+Swx",
175 "xtext": "text+x",
176 "xunicode": "unicode+x",
177 "xutf16": "utf16+x",
178 }
179 if p4type in p4_filetypes_historical:
180 p4type = p4_filetypes_historical[p4type]
181 mods = ""
182 s = p4type.split("+")
183 base = s[0]
184 mods = ""
185 if len(s) > 1:
186 mods = s[1]
187 return (base, mods)
188
David Brownb9fc6ea2007-09-19 13:12:48 -0700189
Chris Pettittc65b6702007-11-01 20:43:14 -0700190def setP4ExecBit(file, mode):
191 # Reopens an already open file and changes the execute bit to match
192 # the execute bit setting in the passed in mode.
193
194 p4Type = "+x"
195
196 if not isModeExec(mode):
197 p4Type = getP4OpenedType(file)
198 p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
199 p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
200 if p4Type[-1] == "+":
201 p4Type = p4Type[0:-1]
202
Luke Diamand6de040d2011-10-16 10:47:52 -0400203 p4_reopen(p4Type, file)
Chris Pettittc65b6702007-11-01 20:43:14 -0700204
205def getP4OpenedType(file):
206 # Returns the perforce file type for the given file.
207
Luke Diamand6de040d2011-10-16 10:47:52 -0400208 result = p4_read_pipe(["opened", file])
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +0100209 match = re.match(".*\((.+)\)\r?$", result)
Chris Pettittc65b6702007-11-01 20:43:14 -0700210 if match:
211 return match.group(1)
212 else:
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +0100213 die("Could not determine file type for %s (result: '%s')" % (file, result))
Chris Pettittc65b6702007-11-01 20:43:14 -0700214
Chris Pettittb43b0a32007-11-01 20:43:13 -0700215def diffTreePattern():
216 # This is a simple generator for the diff tree regex pattern. This could be
217 # a class variable if this and parseDiffTreeEntry were a part of a class.
218 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
219 while True:
220 yield pattern
221
222def parseDiffTreeEntry(entry):
223 """Parses a single diff tree entry into its component elements.
224
225 See git-diff-tree(1) manpage for details about the format of the diff
226 output. This method returns a dictionary with the following elements:
227
228 src_mode - The mode of the source file
229 dst_mode - The mode of the destination file
230 src_sha1 - The sha1 for the source file
231 dst_sha1 - The sha1 fr the destination file
232 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
233 status_score - The score for the status (applicable for 'C' and 'R'
234 statuses). This is None if there is no score.
235 src - The path for the source file.
236 dst - The path for the destination file. This is only present for
237 copy or renames. If it is not present, this is None.
238
239 If the pattern is not matched, None is returned."""
240
241 match = diffTreePattern().next().match(entry)
242 if match:
243 return {
244 'src_mode': match.group(1),
245 'dst_mode': match.group(2),
246 'src_sha1': match.group(3),
247 'dst_sha1': match.group(4),
248 'status': match.group(5),
249 'status_score': match.group(6),
250 'src': match.group(7),
251 'dst': match.group(10)
252 }
253 return None
254
Chris Pettittc65b6702007-11-01 20:43:14 -0700255def isModeExec(mode):
256 # Returns True if the given git mode represents an executable file,
257 # otherwise False.
258 return mode[-3:] == "755"
259
260def isModeExecChanged(src_mode, dst_mode):
261 return isModeExec(src_mode) != isModeExec(dst_mode)
262
Luke Diamandb9327052009-07-30 00:13:46 +0100263def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None):
Luke Diamand6de040d2011-10-16 10:47:52 -0400264
265 if isinstance(cmd,basestring):
266 cmd = "-G " + cmd
267 expand = True
268 else:
269 cmd = ["-G"] + cmd
270 expand = False
271
272 cmd = p4_build_cmd(cmd)
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -0300273 if verbose:
Luke Diamand6de040d2011-10-16 10:47:52 -0400274 sys.stderr.write("Opening pipe: %s\n" % str(cmd))
Scott Lamb9f90c732007-07-15 20:58:10 -0700275
276 # Use a temporary file to avoid deadlocks without
277 # subprocess.communicate(), which would put another copy
278 # of stdout into memory.
279 stdin_file = None
280 if stdin is not None:
281 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
Luke Diamand6de040d2011-10-16 10:47:52 -0400282 if isinstance(stdin,basestring):
283 stdin_file.write(stdin)
284 else:
285 for i in stdin:
286 stdin_file.write(i + '\n')
Scott Lamb9f90c732007-07-15 20:58:10 -0700287 stdin_file.flush()
288 stdin_file.seek(0)
289
Luke Diamand6de040d2011-10-16 10:47:52 -0400290 p4 = subprocess.Popen(cmd,
291 shell=expand,
Scott Lamb9f90c732007-07-15 20:58:10 -0700292 stdin=stdin_file,
293 stdout=subprocess.PIPE)
Simon Hausmann86949ee2007-03-19 20:59:12 +0100294
295 result = []
296 try:
297 while True:
Scott Lamb9f90c732007-07-15 20:58:10 -0700298 entry = marshal.load(p4.stdout)
Andrew Garberc3f61632011-04-07 02:01:21 -0400299 if cb is not None:
300 cb(entry)
301 else:
302 result.append(entry)
Simon Hausmann86949ee2007-03-19 20:59:12 +0100303 except EOFError:
304 pass
Scott Lamb9f90c732007-07-15 20:58:10 -0700305 exitCode = p4.wait()
306 if exitCode != 0:
Simon Hausmannac3e0d72007-05-23 23:32:32 +0200307 entry = {}
308 entry["p4ExitCode"] = exitCode
309 result.append(entry)
Simon Hausmann86949ee2007-03-19 20:59:12 +0100310
311 return result
312
313def p4Cmd(cmd):
314 list = p4CmdList(cmd)
315 result = {}
316 for entry in list:
317 result.update(entry)
318 return result;
319
Simon Hausmanncb2c9db2007-03-24 09:15:11 +0100320def p4Where(depotPath):
321 if not depotPath.endswith("/"):
322 depotPath += "/"
Tor Arvid Lund7f705dc2008-12-04 14:37:33 +0100323 depotPath = depotPath + "..."
Luke Diamand6de040d2011-10-16 10:47:52 -0400324 outputList = p4CmdList(["where", depotPath])
Tor Arvid Lund7f705dc2008-12-04 14:37:33 +0100325 output = None
326 for entry in outputList:
Tor Arvid Lund75bc9572008-12-09 16:41:50 +0100327 if "depotFile" in entry:
328 if entry["depotFile"] == depotPath:
329 output = entry
330 break
331 elif "data" in entry:
332 data = entry.get("data")
333 space = data.find(" ")
334 if data[:space] == depotPath:
335 output = entry
336 break
Tor Arvid Lund7f705dc2008-12-04 14:37:33 +0100337 if output == None:
338 return ""
Simon Hausmanndc524032007-05-21 09:34:56 +0200339 if output["code"] == "error":
340 return ""
Simon Hausmanncb2c9db2007-03-24 09:15:11 +0100341 clientPath = ""
342 if "path" in output:
343 clientPath = output.get("path")
344 elif "data" in output:
345 data = output.get("data")
346 lastSpace = data.rfind(" ")
347 clientPath = data[lastSpace + 1:]
348
349 if clientPath.endswith("..."):
350 clientPath = clientPath[:-3]
351 return clientPath
352
Simon Hausmann86949ee2007-03-19 20:59:12 +0100353def currentGitBranch():
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300354 return read_pipe("git name-rev HEAD").split(" ")[1].strip()
Simon Hausmann86949ee2007-03-19 20:59:12 +0100355
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100356def isValidGitDir(path):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300357 if (os.path.exists(path + "/HEAD")
358 and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")):
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100359 return True;
360 return False
361
Simon Hausmann463e8af2007-05-17 09:13:54 +0200362def parseRevision(ref):
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300363 return read_pipe("git rev-parse %s" % ref).strip()
Simon Hausmann463e8af2007-05-17 09:13:54 +0200364
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100365def extractLogMessageFromGitCommit(commit):
366 logMessage = ""
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300367
368 ## fixme: title is first line of commit, not 1st paragraph.
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100369 foundTitle = False
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300370 for log in read_pipe_lines("git cat-file commit %s" % commit):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100371 if not foundTitle:
372 if len(log) == 1:
Simon Hausmann1c094182007-05-01 23:15:48 +0200373 foundTitle = True
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100374 continue
375
376 logMessage += log
377 return logMessage
378
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300379def extractSettingsGitLog(log):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100380 values = {}
381 for line in log.split("\n"):
382 line = line.strip()
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300383 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
384 if not m:
385 continue
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100386
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300387 assignments = m.group(1).split (':')
388 for a in assignments:
389 vals = a.split ('=')
390 key = vals[0].strip()
391 val = ('='.join (vals[1:])).strip()
392 if val.endswith ('\"') and val.startswith('"'):
393 val = val[1:-1]
394
395 values[key] = val
396
Simon Hausmann845b42c2007-06-07 09:19:34 +0200397 paths = values.get("depot-paths")
398 if not paths:
399 paths = values.get("depot-path")
Simon Hausmanna3fdd572007-06-07 22:54:32 +0200400 if paths:
401 values['depot-paths'] = paths.split(',')
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300402 return values
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100403
Simon Hausmann8136a632007-03-22 21:27:14 +0100404def gitBranchExists(branch):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300405 proc = subprocess.Popen(["git", "rev-parse", branch],
406 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
Simon Hausmanncaace112007-05-15 14:57:57 +0200407 return proc.wait() == 0;
Simon Hausmann8136a632007-03-22 21:27:14 +0100408
John Chapman36bd8442008-11-08 14:22:49 +1100409_gitConfig = {}
Tor Arvid Lund99f790f2011-03-15 13:08:01 +0100410def gitConfig(key, args = None): # set args to "--bool", for instance
John Chapman36bd8442008-11-08 14:22:49 +1100411 if not _gitConfig.has_key(key):
Tor Arvid Lund99f790f2011-03-15 13:08:01 +0100412 argsFilter = ""
413 if args != None:
414 argsFilter = "%s " % args
415 cmd = "git config %s%s" % (argsFilter, key)
416 _gitConfig[key] = read_pipe(cmd, ignore_error=True).strip()
John Chapman36bd8442008-11-08 14:22:49 +1100417 return _gitConfig[key]
Simon Hausmann01265102007-05-25 10:36:10 +0200418
Vitor Antunes7199cf12011-08-19 00:44:05 +0100419def gitConfigList(key):
420 if not _gitConfig.has_key(key):
421 _gitConfig[key] = read_pipe("git config --get-all %s" % key, ignore_error=True).strip().split(os.linesep)
422 return _gitConfig[key]
423
Simon Hausmann062410b2007-07-18 10:56:31 +0200424def p4BranchesInGit(branchesAreInRemotes = True):
425 branches = {}
426
427 cmdline = "git rev-parse --symbolic "
428 if branchesAreInRemotes:
429 cmdline += " --remotes"
430 else:
431 cmdline += " --branches"
432
433 for line in read_pipe_lines(cmdline):
434 line = line.strip()
435
436 ## only import to p4/
437 if not line.startswith('p4/') or line == "p4/HEAD":
438 continue
439 branch = line
440
441 # strip off p4
442 branch = re.sub ("^p4/", "", line)
443
444 branches[branch] = parseRevision(line)
445 return branches
446
Simon Hausmann9ceab362007-06-22 00:01:57 +0200447def findUpstreamBranchPoint(head = "HEAD"):
Simon Hausmann86506fe2007-07-18 12:40:12 +0200448 branches = p4BranchesInGit()
449 # map from depot-path to branch name
450 branchByDepotPath = {}
451 for branch in branches.keys():
452 tip = branches[branch]
453 log = extractLogMessageFromGitCommit(tip)
454 settings = extractSettingsGitLog(log)
455 if settings.has_key("depot-paths"):
456 paths = ",".join(settings["depot-paths"])
457 branchByDepotPath[paths] = "remotes/p4/" + branch
458
Simon Hausmann27d2d812007-06-12 14:31:59 +0200459 settings = None
Simon Hausmann27d2d812007-06-12 14:31:59 +0200460 parent = 0
461 while parent < 65535:
Simon Hausmann9ceab362007-06-22 00:01:57 +0200462 commit = head + "~%s" % parent
Simon Hausmann27d2d812007-06-12 14:31:59 +0200463 log = extractLogMessageFromGitCommit(commit)
464 settings = extractSettingsGitLog(log)
Simon Hausmann86506fe2007-07-18 12:40:12 +0200465 if settings.has_key("depot-paths"):
466 paths = ",".join(settings["depot-paths"])
467 if branchByDepotPath.has_key(paths):
468 return [branchByDepotPath[paths], settings]
Simon Hausmann27d2d812007-06-12 14:31:59 +0200469
Simon Hausmann86506fe2007-07-18 12:40:12 +0200470 parent = parent + 1
Simon Hausmann27d2d812007-06-12 14:31:59 +0200471
Simon Hausmann86506fe2007-07-18 12:40:12 +0200472 return ["", settings]
Simon Hausmann27d2d812007-06-12 14:31:59 +0200473
Simon Hausmann5ca44612007-08-24 17:44:16 +0200474def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
475 if not silent:
476 print ("Creating/updating branch(es) in %s based on origin branch(es)"
477 % localRefPrefix)
478
479 originPrefix = "origin/p4/"
480
481 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
482 line = line.strip()
483 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
484 continue
485
486 headName = line[len(originPrefix):]
487 remoteHead = localRefPrefix + headName
488 originHead = line
489
490 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
491 if (not original.has_key('depot-paths')
492 or not original.has_key('change')):
493 continue
494
495 update = False
496 if not gitBranchExists(remoteHead):
497 if verbose:
498 print "creating %s" % remoteHead
499 update = True
500 else:
501 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
502 if settings.has_key('change') > 0:
503 if settings['depot-paths'] == original['depot-paths']:
504 originP4Change = int(original['change'])
505 p4Change = int(settings['change'])
506 if originP4Change > p4Change:
507 print ("%s (%s) is newer than %s (%s). "
508 "Updating p4 branch from origin."
509 % (originHead, originP4Change,
510 remoteHead, p4Change))
511 update = True
512 else:
513 print ("Ignoring: %s was imported from %s while "
514 "%s was imported from %s"
515 % (originHead, ','.join(original['depot-paths']),
516 remoteHead, ','.join(settings['depot-paths'])))
517
518 if update:
519 system("git update-ref %s %s" % (remoteHead, originHead))
520
521def originP4BranchesExist():
522 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
523
Simon Hausmann4f6432d2007-08-26 15:56:36 +0200524def p4ChangesForPaths(depotPaths, changeRange):
525 assert depotPaths
Luke Diamand6de040d2011-10-16 10:47:52 -0400526 cmd = ['changes']
527 for p in depotPaths:
528 cmd += ["%s...%s" % (p, changeRange)]
529 output = p4_read_pipe_lines(cmd)
Simon Hausmann4f6432d2007-08-26 15:56:36 +0200530
Pete Wyckoffb4b0ba02009-02-18 13:12:14 -0500531 changes = {}
Simon Hausmann4f6432d2007-08-26 15:56:36 +0200532 for line in output:
Andrew Garberc3f61632011-04-07 02:01:21 -0400533 changeNum = int(line.split(" ")[1])
534 changes[changeNum] = True
Simon Hausmann4f6432d2007-08-26 15:56:36 +0200535
Pete Wyckoffb4b0ba02009-02-18 13:12:14 -0500536 changelist = changes.keys()
537 changelist.sort()
538 return changelist
Simon Hausmann4f6432d2007-08-26 15:56:36 +0200539
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +0100540def p4PathStartsWith(path, prefix):
541 # This method tries to remedy a potential mixed-case issue:
542 #
543 # If UserA adds //depot/DirA/file1
544 # and UserB adds //depot/dira/file2
545 #
546 # we may or may not have a problem. If you have core.ignorecase=true,
547 # we treat DirA and dira as the same directory
548 ignorecase = gitConfig("core.ignorecase", "--bool") == "true"
549 if ignorecase:
550 return path.lower().startswith(prefix.lower())
551 return path.startswith(prefix)
552
Simon Hausmannb9847332007-03-20 20:54:23 +0100553class Command:
554 def __init__(self):
555 self.usage = "usage: %prog [options]"
Simon Hausmann8910ac02007-03-26 08:18:55 +0200556 self.needsGit = True
Simon Hausmannb9847332007-03-20 20:54:23 +0100557
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100558class P4UserMap:
559 def __init__(self):
560 self.userMapFromPerforceServer = False
561
562 def getUserCacheFilename(self):
563 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
564 return home + "/.gitp4-usercache.txt"
565
566 def getUserMapFromPerforceServer(self):
567 if self.userMapFromPerforceServer:
568 return
569 self.users = {}
570 self.emails = {}
571
572 for output in p4CmdList("users"):
573 if not output.has_key("User"):
574 continue
575 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
576 self.emails[output["Email"]] = output["User"]
577
578
579 s = ''
580 for (key, val) in self.users.items():
581 s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
582
583 open(self.getUserCacheFilename(), "wb").write(s)
584 self.userMapFromPerforceServer = True
585
586 def loadUserMapFromCache(self):
587 self.users = {}
588 self.userMapFromPerforceServer = False
589 try:
590 cache = open(self.getUserCacheFilename(), "rb")
591 lines = cache.readlines()
592 cache.close()
593 for line in lines:
594 entry = line.strip().split("\t")
595 self.users[entry[0]] = entry[1]
596 except IOError:
597 self.getUserMapFromPerforceServer()
598
Simon Hausmannb9847332007-03-20 20:54:23 +0100599class P4Debug(Command):
Simon Hausmann86949ee2007-03-19 20:59:12 +0100600 def __init__(self):
Simon Hausmann6ae8de82007-03-22 21:10:25 +0100601 Command.__init__(self)
Simon Hausmann86949ee2007-03-19 20:59:12 +0100602 self.options = [
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300603 optparse.make_option("--verbose", dest="verbose", action="store_true",
604 default=False),
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300605 ]
Simon Hausmannc8c39112007-03-19 21:02:30 +0100606 self.description = "A tool to debug the output of p4 -G."
Simon Hausmann8910ac02007-03-26 08:18:55 +0200607 self.needsGit = False
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300608 self.verbose = False
Simon Hausmann86949ee2007-03-19 20:59:12 +0100609
610 def run(self, args):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300611 j = 0
Luke Diamand6de040d2011-10-16 10:47:52 -0400612 for output in p4CmdList(args):
Han-Wen Nienhuysb1ce9442007-05-23 18:49:35 -0300613 print 'Element: %d' % j
614 j += 1
Simon Hausmann86949ee2007-03-19 20:59:12 +0100615 print output
Simon Hausmannb9847332007-03-20 20:54:23 +0100616 return True
Simon Hausmann86949ee2007-03-19 20:59:12 +0100617
Simon Hausmann58346842007-05-21 22:57:06 +0200618class P4RollBack(Command):
619 def __init__(self):
620 Command.__init__(self)
621 self.options = [
Simon Hausmann0c66a782007-05-23 20:07:57 +0200622 optparse.make_option("--verbose", dest="verbose", action="store_true"),
623 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
Simon Hausmann58346842007-05-21 22:57:06 +0200624 ]
625 self.description = "A tool to debug the multi-branch import. Don't use :)"
Simon Hausmann52102d42007-05-21 23:44:24 +0200626 self.verbose = False
Simon Hausmann0c66a782007-05-23 20:07:57 +0200627 self.rollbackLocalBranches = False
Simon Hausmann58346842007-05-21 22:57:06 +0200628
629 def run(self, args):
630 if len(args) != 1:
631 return False
632 maxChange = int(args[0])
Simon Hausmann0c66a782007-05-23 20:07:57 +0200633
Simon Hausmannad192f22007-05-23 23:44:19 +0200634 if "p4ExitCode" in p4Cmd("changes -m 1"):
Simon Hausmann66a2f522007-05-23 23:40:48 +0200635 die("Problems executing p4");
636
Simon Hausmann0c66a782007-05-23 20:07:57 +0200637 if self.rollbackLocalBranches:
638 refPrefix = "refs/heads/"
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300639 lines = read_pipe_lines("git rev-parse --symbolic --branches")
Simon Hausmann0c66a782007-05-23 20:07:57 +0200640 else:
641 refPrefix = "refs/remotes/"
Han-Wen Nienhuysb016d392007-05-23 17:10:46 -0300642 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
Simon Hausmann0c66a782007-05-23 20:07:57 +0200643
644 for line in lines:
645 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -0300646 line = line.strip()
647 ref = refPrefix + line
Simon Hausmann58346842007-05-21 22:57:06 +0200648 log = extractLogMessageFromGitCommit(ref)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300649 settings = extractSettingsGitLog(log)
650
651 depotPaths = settings['depot-paths']
652 change = settings['change']
653
Simon Hausmann58346842007-05-21 22:57:06 +0200654 changed = False
Simon Hausmann52102d42007-05-21 23:44:24 +0200655
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -0300656 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
657 for p in depotPaths]))) == 0:
Simon Hausmann52102d42007-05-21 23:44:24 +0200658 print "Branch %s did not exist at change %s, deleting." % (ref, maxChange)
659 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
660 continue
661
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300662 while change and int(change) > maxChange:
Simon Hausmann58346842007-05-21 22:57:06 +0200663 changed = True
Simon Hausmann52102d42007-05-21 23:44:24 +0200664 if self.verbose:
665 print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange)
Simon Hausmann58346842007-05-21 22:57:06 +0200666 system("git update-ref %s \"%s^\"" % (ref, ref))
667 log = extractLogMessageFromGitCommit(ref)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -0300668 settings = extractSettingsGitLog(log)
669
670
671 depotPaths = settings['depot-paths']
672 change = settings['change']
Simon Hausmann58346842007-05-21 22:57:06 +0200673
674 if changed:
Simon Hausmann52102d42007-05-21 23:44:24 +0200675 print "%s rewound to %s" % (ref, change)
Simon Hausmann58346842007-05-21 22:57:06 +0200676
677 return True
678
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100679class P4Submit(Command, P4UserMap):
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100680 def __init__(self):
Simon Hausmannb9847332007-03-20 20:54:23 +0100681 Command.__init__(self)
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100682 P4UserMap.__init__(self)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100683 self.options = [
Han-Wen Nienhuys4addad22007-05-23 18:49:35 -0300684 optparse.make_option("--verbose", dest="verbose", action="store_true"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100685 optparse.make_option("--origin", dest="origin"),
Vitor Antunesae901092011-02-20 01:18:24 +0000686 optparse.make_option("-M", dest="detectRenames", action="store_true"),
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100687 # preserve the user, requires relevant p4 permissions
688 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100689 ]
690 self.description = "Submit changes from git to the perforce depot."
Simon Hausmannc9b50e62007-03-29 19:15:24 +0200691 self.usage += " [name of git branch to submit into perforce depot]"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100692 self.interactive = True
Simon Hausmann95124972007-03-23 09:16:07 +0100693 self.origin = ""
Vitor Antunesae901092011-02-20 01:18:24 +0000694 self.detectRenames = False
Simon Hausmannb0d10df2007-06-07 13:09:14 +0200695 self.verbose = False
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100696 self.preserveUser = gitConfig("git-p4.preserveUser").lower() == "true"
Marius Storm-Olsenf7baba82007-06-07 14:07:01 +0200697 self.isWindows = (platform.system() == "Windows")
Luke Diamand848de9c2011-05-13 20:46:00 +0100698 self.myP4UserId = None
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100699
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100700 def check(self):
701 if len(p4CmdList("opened ...")) > 0:
702 die("You have files opened with perforce! Close them before starting the sync.")
703
Simon Hausmannedae1e22008-02-19 09:29:06 +0100704 # replaces everything between 'Description:' and the next P4 submit template field with the
705 # commit message
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100706 def prepareLogMessage(self, template, message):
707 result = ""
708
Simon Hausmannedae1e22008-02-19 09:29:06 +0100709 inDescriptionSection = False
710
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100711 for line in template.split("\n"):
712 if line.startswith("#"):
713 result += line + "\n"
714 continue
715
Simon Hausmannedae1e22008-02-19 09:29:06 +0100716 if inDescriptionSection:
Michael Horowitzc9dbab02011-02-25 21:31:13 -0500717 if line.startswith("Files:") or line.startswith("Jobs:"):
Simon Hausmannedae1e22008-02-19 09:29:06 +0100718 inDescriptionSection = False
719 else:
720 continue
721 else:
722 if line.startswith("Description:"):
723 inDescriptionSection = True
724 line += "\n"
725 for messageLine in message.split("\n"):
726 line += "\t" + messageLine + "\n"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100727
Simon Hausmannedae1e22008-02-19 09:29:06 +0100728 result += line + "\n"
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100729
730 return result
731
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100732 def p4UserForCommit(self,id):
733 # Return the tuple (perforce user,git email) for a given git commit id
734 self.getUserMapFromPerforceServer()
735 gitEmail = read_pipe("git log --max-count=1 --format='%%ae' %s" % id)
736 gitEmail = gitEmail.strip()
737 if not self.emails.has_key(gitEmail):
738 return (None,gitEmail)
739 else:
740 return (self.emails[gitEmail],gitEmail)
741
742 def checkValidP4Users(self,commits):
743 # check if any git authors cannot be mapped to p4 users
744 for id in commits:
745 (user,email) = self.p4UserForCommit(id)
746 if not user:
747 msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
748 if gitConfig('git-p4.allowMissingP4Users').lower() == "true":
749 print "%s" % msg
750 else:
751 die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
752
753 def lastP4Changelist(self):
754 # Get back the last changelist number submitted in this client spec. This
755 # then gets used to patch up the username in the change. If the same
756 # client spec is being used by multiple processes then this might go
757 # wrong.
758 results = p4CmdList("client -o") # find the current client
759 client = None
760 for r in results:
761 if r.has_key('Client'):
762 client = r['Client']
763 break
764 if not client:
765 die("could not get client spec")
Luke Diamand6de040d2011-10-16 10:47:52 -0400766 results = p4CmdList(["changes", "-c", client, "-m", "1"])
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100767 for r in results:
768 if r.has_key('change'):
769 return r['change']
770 die("Could not get changelist number for last submit - cannot patch up user details")
771
772 def modifyChangelistUser(self, changelist, newUser):
773 # fixup the user field of a changelist after it has been submitted.
774 changes = p4CmdList("change -o %s" % changelist)
Luke Diamandecdba362011-05-07 11:19:43 +0100775 if len(changes) != 1:
776 die("Bad output from p4 change modifying %s to user %s" %
777 (changelist, newUser))
778
779 c = changes[0]
780 if c['User'] == newUser: return # nothing to do
781 c['User'] = newUser
782 input = marshal.dumps(c)
783
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100784 result = p4CmdList("change -f -i", stdin=input)
785 for r in result:
786 if r.has_key('code'):
787 if r['code'] == 'error':
788 die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
789 if r.has_key('data'):
790 print("Updated user field for changelist %s to %s" % (changelist, newUser))
791 return
792 die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
793
794 def canChangeChangelists(self):
795 # check to see if we have p4 admin or super-user permissions, either of
796 # which are required to modify changelists.
Luke Diamandecdba362011-05-07 11:19:43 +0100797 results = p4CmdList("protects %s" % self.depotPath)
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100798 for r in results:
799 if r.has_key('perm'):
800 if r['perm'] == 'admin':
801 return 1
802 if r['perm'] == 'super':
803 return 1
804 return 0
805
Luke Diamand848de9c2011-05-13 20:46:00 +0100806 def p4UserId(self):
807 if self.myP4UserId:
808 return self.myP4UserId
809
810 results = p4CmdList("user -o")
811 for r in results:
812 if r.has_key('User'):
813 self.myP4UserId = r['User']
814 return r['User']
815 die("Could not find your p4 user id")
816
817 def p4UserIsMe(self, p4User):
818 # return True if the given p4 user is actually me
819 me = self.p4UserId()
820 if not p4User or p4User != me:
821 return False
822 else:
823 return True
824
Simon Hausmannea99c3a2007-08-08 17:06:55 +0200825 def prepareSubmitTemplate(self):
826 # remove lines in the Files section that show changes to files outside the depot path we're committing into
827 template = ""
828 inFilesSection = False
Luke Diamand6de040d2011-10-16 10:47:52 -0400829 for line in p4_read_pipe_lines(['change', '-o']):
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +0100830 if line.endswith("\r\n"):
831 line = line[:-2] + "\n"
Simon Hausmannea99c3a2007-08-08 17:06:55 +0200832 if inFilesSection:
833 if line.startswith("\t"):
834 # path starts and ends with a tab
835 path = line[1:]
836 lastTab = path.rfind("\t")
837 if lastTab != -1:
838 path = path[:lastTab]
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +0100839 if not p4PathStartsWith(path, self.depotPath):
Simon Hausmannea99c3a2007-08-08 17:06:55 +0200840 continue
841 else:
842 inFilesSection = False
843 else:
844 if line.startswith("Files:"):
845 inFilesSection = True
846
847 template += line
848
849 return template
850
Pete Wyckoff7c766e52011-12-04 19:22:45 -0500851 def edit_template(self, template_file):
852 """Invoke the editor to let the user change the submission
853 message. Return true if okay to continue with the submit."""
854
855 # if configured to skip the editing part, just submit
856 if gitConfig("git-p4.skipSubmitEdit") == "true":
857 return True
858
859 # look at the modification time, to check later if the user saved
860 # the file
861 mtime = os.stat(template_file).st_mtime
862
863 # invoke the editor
864 if os.environ.has_key("P4EDITOR"):
865 editor = os.environ.get("P4EDITOR")
866 else:
867 editor = read_pipe("git var GIT_EDITOR").strip()
868 system(editor + " " + template_file)
869
870 # If the file was not saved, prompt to see if this patch should
871 # be skipped. But skip this verification step if configured so.
872 if gitConfig("git-p4.skipSubmitEditCheck") == "true":
873 return True
874
Pete Wyckoffd1652042011-12-17 12:39:03 -0500875 # modification time updated means user saved the file
876 if os.stat(template_file).st_mtime > mtime:
877 return True
878
879 while True:
880 response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
881 if response == 'y':
882 return True
883 if response == 'n':
884 return False
Pete Wyckoff7c766e52011-12-04 19:22:45 -0500885
Han-Wen Nienhuys7cb5cbe2007-05-23 16:55:48 -0300886 def applyCommit(self, id):
Simon Hausmann0e36f2d2008-02-19 09:33:08 +0100887 print "Applying %s" % (read_pipe("git log --max-count=1 --pretty=oneline %s" % id))
Vitor Antunesae901092011-02-20 01:18:24 +0000888
Luke Diamand848de9c2011-05-13 20:46:00 +0100889 (p4User, gitEmail) = self.p4UserForCommit(id)
Luke Diamand3ea2cfd2011-04-21 20:50:23 +0100890
Vitor Antunesae901092011-02-20 01:18:24 +0000891 if not self.detectRenames:
892 # If not explicitly set check the config variable
Vitor Antunes0a9feff2011-08-22 09:33:05 +0100893 self.detectRenames = gitConfig("git-p4.detectRenames")
Vitor Antunesae901092011-02-20 01:18:24 +0000894
Vitor Antunes0a9feff2011-08-22 09:33:05 +0100895 if self.detectRenames.lower() == "false" or self.detectRenames == "":
896 diffOpts = ""
897 elif self.detectRenames.lower() == "true":
Vitor Antunesae901092011-02-20 01:18:24 +0000898 diffOpts = "-M"
899 else:
Vitor Antunes0a9feff2011-08-22 09:33:05 +0100900 diffOpts = "-M%s" % self.detectRenames
Vitor Antunesae901092011-02-20 01:18:24 +0000901
Vitor Antunes0a9feff2011-08-22 09:33:05 +0100902 detectCopies = gitConfig("git-p4.detectCopies")
903 if detectCopies.lower() == "true":
Vitor Antunes4fddb412011-02-20 01:18:25 +0000904 diffOpts += " -C"
Vitor Antunes0a9feff2011-08-22 09:33:05 +0100905 elif detectCopies != "" and detectCopies.lower() != "false":
906 diffOpts += " -C%s" % detectCopies
Vitor Antunes4fddb412011-02-20 01:18:25 +0000907
Vitor Antunes68cbcf12011-08-22 09:33:09 +0100908 if gitConfig("git-p4.detectCopiesHarder", "--bool") == "true":
Vitor Antunes4fddb412011-02-20 01:18:25 +0000909 diffOpts += " --find-copies-harder"
910
Simon Hausmann0e36f2d2008-02-19 09:33:08 +0100911 diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (diffOpts, id, id))
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100912 filesToAdd = set()
913 filesToDelete = set()
Simon Hausmannd336c152007-05-16 09:41:26 +0200914 editedFiles = set()
Chris Pettittc65b6702007-11-01 20:43:14 -0700915 filesToChangeExecBit = {}
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100916 for line in diff:
Chris Pettittb43b0a32007-11-01 20:43:13 -0700917 diff = parseDiffTreeEntry(line)
918 modifier = diff['status']
919 path = diff['src']
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100920 if modifier == "M":
Luke Diamand6de040d2011-10-16 10:47:52 -0400921 p4_edit(path)
Chris Pettittc65b6702007-11-01 20:43:14 -0700922 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
923 filesToChangeExecBit[path] = diff['dst_mode']
Simon Hausmannd336c152007-05-16 09:41:26 +0200924 editedFiles.add(path)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100925 elif modifier == "A":
926 filesToAdd.add(path)
Chris Pettittc65b6702007-11-01 20:43:14 -0700927 filesToChangeExecBit[path] = diff['dst_mode']
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100928 if path in filesToDelete:
929 filesToDelete.remove(path)
930 elif modifier == "D":
931 filesToDelete.add(path)
932 if path in filesToAdd:
933 filesToAdd.remove(path)
Vitor Antunes4fddb412011-02-20 01:18:25 +0000934 elif modifier == "C":
935 src, dest = diff['src'], diff['dst']
Luke Diamand6de040d2011-10-16 10:47:52 -0400936 p4_integrate(src, dest)
Vitor Antunes4fddb412011-02-20 01:18:25 +0000937 if diff['src_sha1'] != diff['dst_sha1']:
Luke Diamand6de040d2011-10-16 10:47:52 -0400938 p4_edit(dest)
Vitor Antunes4fddb412011-02-20 01:18:25 +0000939 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
Luke Diamand6de040d2011-10-16 10:47:52 -0400940 p4_edit(dest)
Vitor Antunes4fddb412011-02-20 01:18:25 +0000941 filesToChangeExecBit[dest] = diff['dst_mode']
942 os.unlink(dest)
943 editedFiles.add(dest)
Chris Pettittd9a5f252007-10-15 22:15:06 -0700944 elif modifier == "R":
Chris Pettittb43b0a32007-11-01 20:43:13 -0700945 src, dest = diff['src'], diff['dst']
Luke Diamand6de040d2011-10-16 10:47:52 -0400946 p4_integrate(src, dest)
Vitor Antunesae901092011-02-20 01:18:24 +0000947 if diff['src_sha1'] != diff['dst_sha1']:
Luke Diamand6de040d2011-10-16 10:47:52 -0400948 p4_edit(dest)
Chris Pettittc65b6702007-11-01 20:43:14 -0700949 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
Luke Diamand6de040d2011-10-16 10:47:52 -0400950 p4_edit(dest)
Chris Pettittc65b6702007-11-01 20:43:14 -0700951 filesToChangeExecBit[dest] = diff['dst_mode']
Chris Pettittd9a5f252007-10-15 22:15:06 -0700952 os.unlink(dest)
953 editedFiles.add(dest)
954 filesToDelete.add(src)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100955 else:
956 die("unknown modifier %s for %s" % (modifier, path))
957
Simon Hausmann0e36f2d2008-02-19 09:33:08 +0100958 diffcmd = "git format-patch -k --stdout \"%s^\"..\"%s\"" % (id, id)
Simon Hausmann47a130b2007-05-20 16:33:21 +0200959 patchcmd = diffcmd + " | git apply "
Simon Hausmannc1b296b2007-05-20 16:55:05 +0200960 tryPatchCmd = patchcmd + "--check -"
961 applyPatchCmd = patchcmd + "--check --apply -"
Simon Hausmann51a26402007-04-15 09:59:56 +0200962
Simon Hausmann47a130b2007-05-20 16:33:21 +0200963 if os.system(tryPatchCmd) != 0:
Simon Hausmann51a26402007-04-15 09:59:56 +0200964 print "Unfortunately applying the change failed!"
965 print "What do you want to do?"
966 response = "x"
967 while response != "s" and response != "a" and response != "w":
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300968 response = raw_input("[s]kip this patch / [a]pply the patch forcibly "
969 "and with .rej files / [w]rite the patch to a file (patch.txt) ")
Simon Hausmann51a26402007-04-15 09:59:56 +0200970 if response == "s":
971 print "Skipping! Good luck with the next patches..."
Simon Hausmann20947142007-09-13 22:10:18 +0200972 for f in editedFiles:
Luke Diamand6de040d2011-10-16 10:47:52 -0400973 p4_revert(f)
Simon Hausmann20947142007-09-13 22:10:18 +0200974 for f in filesToAdd:
Luke Diamand6de040d2011-10-16 10:47:52 -0400975 os.remove(f)
Simon Hausmann51a26402007-04-15 09:59:56 +0200976 return
977 elif response == "a":
Simon Hausmann47a130b2007-05-20 16:33:21 +0200978 os.system(applyPatchCmd)
Simon Hausmann51a26402007-04-15 09:59:56 +0200979 if len(filesToAdd) > 0:
980 print "You may also want to call p4 add on the following files:"
981 print " ".join(filesToAdd)
982 if len(filesToDelete):
983 print "The following files should be scheduled for deletion with p4 delete:"
984 print " ".join(filesToDelete)
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300985 die("Please resolve and submit the conflict manually and "
986 + "continue afterwards with git-p4 submit --continue")
Simon Hausmann51a26402007-04-15 09:59:56 +0200987 elif response == "w":
988 system(diffcmd + " > patch.txt")
989 print "Patch saved to patch.txt in %s !" % self.clientPath
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -0300990 die("Please resolve and submit the conflict manually and "
991 "continue afterwards with git-p4 submit --continue")
Simon Hausmann51a26402007-04-15 09:59:56 +0200992
Simon Hausmann47a130b2007-05-20 16:33:21 +0200993 system(applyPatchCmd)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100994
995 for f in filesToAdd:
Luke Diamand6de040d2011-10-16 10:47:52 -0400996 p4_add(f)
Simon Hausmann4f5cf762007-03-19 22:25:17 +0100997 for f in filesToDelete:
Luke Diamand6de040d2011-10-16 10:47:52 -0400998 p4_revert(f)
999 p4_delete(f)
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001000
Chris Pettittc65b6702007-11-01 20:43:14 -07001001 # Set/clear executable bits
1002 for f in filesToChangeExecBit.keys():
1003 mode = filesToChangeExecBit[f]
1004 setP4ExecBit(f, mode)
1005
Simon Hausmann0e36f2d2008-02-19 09:33:08 +01001006 logMessage = extractLogMessageFromGitCommit(id)
Simon Hausmann0e36f2d2008-02-19 09:33:08 +01001007 logMessage = logMessage.strip()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001008
Simon Hausmannea99c3a2007-08-08 17:06:55 +02001009 template = self.prepareSubmitTemplate()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001010
1011 if self.interactive:
1012 submitTemplate = self.prepareLogMessage(template, logMessage)
Luke Diamandecdba362011-05-07 11:19:43 +01001013
1014 if self.preserveUser:
1015 submitTemplate = submitTemplate + ("\n######## Actual user %s, modified after commit\n" % p4User)
1016
Shawn Bohrer67abd412008-03-12 19:03:23 -05001017 if os.environ.has_key("P4DIFF"):
1018 del(os.environ["P4DIFF"])
Andrew Waters8b130262010-10-22 13:26:02 +01001019 diff = ""
1020 for editedFile in editedFiles:
Luke Diamand6de040d2011-10-16 10:47:52 -04001021 diff += p4_read_pipe(['diff', '-du', editedFile])
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001022
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +01001023 newdiff = ""
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001024 for newFile in filesToAdd:
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +01001025 newdiff += "==== new file ====\n"
1026 newdiff += "--- /dev/null\n"
1027 newdiff += "+++ %s\n" % newFile
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001028 f = open(newFile, "r")
1029 for line in f.readlines():
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +01001030 newdiff += "+" + line
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001031 f.close()
1032
Luke Diamand848de9c2011-05-13 20:46:00 +01001033 if self.checkAuthorship and not self.p4UserIsMe(p4User):
1034 submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
1035 submitTemplate += "######## Use git-p4 option --preserve-user to modify authorship\n"
1036 submitTemplate += "######## Use git-p4 config git-p4.skipUserNameCheck hides this message.\n"
1037
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +01001038 separatorLine = "######## everything below this line is just the diff #######\n"
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001039
Pete Wyckoff7c766e52011-12-04 19:22:45 -05001040 (handle, fileName) = tempfile.mkstemp()
Simon Hausmanne96e4002008-01-04 14:27:55 +01001041 tmpFile = os.fdopen(handle, "w+")
Marius Storm-Olsenf3e5ae42008-03-28 15:40:40 +01001042 if self.isWindows:
1043 submitTemplate = submitTemplate.replace("\n", "\r\n")
1044 separatorLine = separatorLine.replace("\n", "\r\n")
1045 newdiff = newdiff.replace("\n", "\r\n")
1046 tmpFile.write(submitTemplate + separatorLine + diff + newdiff)
Simon Hausmanne96e4002008-01-04 14:27:55 +01001047 tmpFile.close()
Simon Hausmanncb4f1282007-05-25 22:34:30 +02001048
Pete Wyckoff7c766e52011-12-04 19:22:45 -05001049 if self.edit_template(fileName):
1050 # read the edited message and submit
Simon Hausmanncdc7e382008-08-27 09:30:29 +02001051 tmpFile = open(fileName, "rb")
1052 message = tmpFile.read()
1053 tmpFile.close()
1054 submitTemplate = message[:message.index(separatorLine)]
1055 if self.isWindows:
1056 submitTemplate = submitTemplate.replace("\r\n", "\n")
Luke Diamand6de040d2011-10-16 10:47:52 -04001057 p4_write_pipe(['submit', '-i'], submitTemplate)
Luke Diamand3ea2cfd2011-04-21 20:50:23 +01001058
1059 if self.preserveUser:
1060 if p4User:
1061 # Get last changelist number. Cannot easily get it from
Pete Wyckoff7c766e52011-12-04 19:22:45 -05001062 # the submit command output as the output is
1063 # unmarshalled.
Luke Diamand3ea2cfd2011-04-21 20:50:23 +01001064 changelist = self.lastP4Changelist()
1065 self.modifyChangelistUser(changelist, p4User)
Simon Hausmanncdc7e382008-08-27 09:30:29 +02001066 else:
Pete Wyckoff7c766e52011-12-04 19:22:45 -05001067 # skip this patch
Pete Wyckoffd1652042011-12-17 12:39:03 -05001068 print "Submission cancelled, undoing p4 changes."
Simon Hausmanncdc7e382008-08-27 09:30:29 +02001069 for f in editedFiles:
Luke Diamand6de040d2011-10-16 10:47:52 -04001070 p4_revert(f)
Simon Hausmanncdc7e382008-08-27 09:30:29 +02001071 for f in filesToAdd:
Luke Diamand6de040d2011-10-16 10:47:52 -04001072 p4_revert(f)
1073 os.remove(f)
Simon Hausmanncdc7e382008-08-27 09:30:29 +02001074
1075 os.remove(fileName)
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001076 else:
1077 fileName = "submit.txt"
1078 file = open(fileName, "w+")
1079 file.write(self.prepareLogMessage(template, logMessage))
1080 file.close()
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001081 print ("Perforce submit template written as %s. "
1082 + "Please review/edit and then use p4 submit -i < %s to submit directly!"
1083 % (fileName, fileName))
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001084
1085 def run(self, args):
Simon Hausmannc9b50e62007-03-29 19:15:24 +02001086 if len(args) == 0:
1087 self.master = currentGitBranch()
Simon Hausmann4280e532007-05-25 08:49:18 +02001088 if len(self.master) == 0 or not gitBranchExists("refs/heads/%s" % self.master):
Simon Hausmannc9b50e62007-03-29 19:15:24 +02001089 die("Detecting current git branch failed!")
1090 elif len(args) == 1:
1091 self.master = args[0]
1092 else:
1093 return False
1094
Jing Xue4c2d5d72008-06-22 14:12:39 -04001095 allowSubmit = gitConfig("git-p4.allowSubmit")
1096 if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
1097 die("%s is not in git-p4.allowSubmit" % self.master)
1098
Simon Hausmann27d2d812007-06-12 14:31:59 +02001099 [upstream, settings] = findUpstreamBranchPoint()
Simon Hausmannea99c3a2007-08-08 17:06:55 +02001100 self.depotPath = settings['depot-paths'][0]
Simon Hausmann27d2d812007-06-12 14:31:59 +02001101 if len(self.origin) == 0:
1102 self.origin = upstream
Simon Hausmanna3fdd572007-06-07 22:54:32 +02001103
Luke Diamand3ea2cfd2011-04-21 20:50:23 +01001104 if self.preserveUser:
1105 if not self.canChangeChangelists():
1106 die("Cannot preserve user names without p4 super-user or admin permissions")
1107
Simon Hausmanna3fdd572007-06-07 22:54:32 +02001108 if self.verbose:
1109 print "Origin branch is " + self.origin
Simon Hausmann95124972007-03-23 09:16:07 +01001110
Simon Hausmannea99c3a2007-08-08 17:06:55 +02001111 if len(self.depotPath) == 0:
Simon Hausmann95124972007-03-23 09:16:07 +01001112 print "Internal error: cannot locate perforce depot path from existing branches"
1113 sys.exit(128)
1114
Simon Hausmannea99c3a2007-08-08 17:06:55 +02001115 self.clientPath = p4Where(self.depotPath)
Simon Hausmann95124972007-03-23 09:16:07 +01001116
Simon Hausmann51a26402007-04-15 09:59:56 +02001117 if len(self.clientPath) == 0:
Simon Hausmannea99c3a2007-08-08 17:06:55 +02001118 print "Error: Cannot locate perforce checkout of %s in client view" % self.depotPath
Simon Hausmann95124972007-03-23 09:16:07 +01001119 sys.exit(128)
1120
Simon Hausmannea99c3a2007-08-08 17:06:55 +02001121 print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath)
Simon Hausmann7944f142007-05-21 11:04:26 +02001122 self.oldWorkingDirectory = os.getcwd()
Simon Hausmannc1b296b2007-05-20 16:55:05 +02001123
Gary Gibbons0591cfa2011-12-09 18:48:14 -05001124 # ensure the clientPath exists
1125 if not os.path.exists(self.clientPath):
1126 os.makedirs(self.clientPath)
1127
Robert Blum053fd0c2008-08-01 12:50:03 -07001128 chdir(self.clientPath)
Benjamin C Meyer6a012982010-03-19 00:39:10 -04001129 print "Synchronizing p4 checkout..."
Luke Diamand6de040d2011-10-16 10:47:52 -04001130 p4_sync("...")
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001131 self.check()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001132
Simon Hausmann4c750c02008-02-19 09:37:16 +01001133 commits = []
1134 for line in read_pipe_lines("git rev-list --no-merges %s..%s" % (self.origin, self.master)):
1135 commits.append(line.strip())
1136 commits.reverse()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001137
Luke Diamand848de9c2011-05-13 20:46:00 +01001138 if self.preserveUser or (gitConfig("git-p4.skipUserNameCheck") == "true"):
1139 self.checkAuthorship = False
1140 else:
1141 self.checkAuthorship = True
1142
Luke Diamand3ea2cfd2011-04-21 20:50:23 +01001143 if self.preserveUser:
1144 self.checkValidP4Users(commits)
1145
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001146 while len(commits) > 0:
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001147 commit = commits[0]
1148 commits = commits[1:]
Han-Wen Nienhuys7cb5cbe2007-05-23 16:55:48 -03001149 self.applyCommit(commit)
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001150 if not self.interactive:
1151 break
1152
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001153 if len(commits) == 0:
Simon Hausmann4c750c02008-02-19 09:37:16 +01001154 print "All changes applied!"
Robert Blum053fd0c2008-08-01 12:50:03 -07001155 chdir(self.oldWorkingDirectory)
Simon Hausmann14594f42007-08-22 09:07:15 +02001156
Simon Hausmann4c750c02008-02-19 09:37:16 +01001157 sync = P4Sync()
1158 sync.run([])
Simon Hausmann14594f42007-08-22 09:07:15 +02001159
Simon Hausmann4c750c02008-02-19 09:37:16 +01001160 rebase = P4Rebase()
1161 rebase.rebase()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01001162
Simon Hausmannb9847332007-03-20 20:54:23 +01001163 return True
1164
Luke Diamand3ea2cfd2011-04-21 20:50:23 +01001165class P4Sync(Command, P4UserMap):
Pete Wyckoff56c09342011-02-19 08:17:57 -05001166 delete_actions = ( "delete", "move/delete", "purge" )
1167
Simon Hausmannb9847332007-03-20 20:54:23 +01001168 def __init__(self):
1169 Command.__init__(self)
Luke Diamand3ea2cfd2011-04-21 20:50:23 +01001170 P4UserMap.__init__(self)
Simon Hausmannb9847332007-03-20 20:54:23 +01001171 self.options = [
1172 optparse.make_option("--branch", dest="branch"),
1173 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
1174 optparse.make_option("--changesfile", dest="changesFile"),
1175 optparse.make_option("--silent", dest="silent", action="store_true"),
Simon Hausmannef48f902007-05-17 22:17:49 +02001176 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
Simon Hausmanna028a982007-05-23 00:03:08 +02001177 optparse.make_option("--verbose", dest="verbose", action="store_true"),
Han-Wen Nienhuysd2c6dd32007-05-23 18:49:35 -03001178 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
1179 help="Import into refs/heads/ , not refs/remotes"),
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -03001180 optparse.make_option("--max-changes", dest="maxChanges"),
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001181 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001182 help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
1183 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
1184 help="Only sync files that are included in the Perforce Client Spec")
Simon Hausmannb9847332007-03-20 20:54:23 +01001185 ]
1186 self.description = """Imports from Perforce into a git repository.\n
1187 example:
1188 //depot/my/project/ -- to import the current head
1189 //depot/my/project/@all -- to import everything
1190 //depot/my/project/@1,6 -- to import only from revision 1 to 6
1191
1192 (a ... is not needed in the path p4 specification, it's added implicitly)"""
1193
1194 self.usage += " //depot/path[@revRange]"
Simon Hausmannb9847332007-03-20 20:54:23 +01001195 self.silent = False
Reilly Grant1d7367d2009-09-10 00:02:38 -07001196 self.createdBranches = set()
1197 self.committedChanges = set()
Simon Hausmann569d1bd2007-03-22 21:34:16 +01001198 self.branch = ""
Simon Hausmannb9847332007-03-20 20:54:23 +01001199 self.detectBranches = False
Simon Hausmanncb53e1f2007-04-08 00:12:02 +02001200 self.detectLabels = False
Simon Hausmannb9847332007-03-20 20:54:23 +01001201 self.changesFile = ""
Simon Hausmann01265102007-05-25 10:36:10 +02001202 self.syncWithOrigin = True
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001203 self.verbose = False
Simon Hausmanna028a982007-05-23 00:03:08 +02001204 self.importIntoRemotes = True
Simon Hausmann01a9c9c2007-05-23 00:07:35 +02001205 self.maxChanges = ""
Marius Storm-Olsenc1f91972007-05-24 14:07:55 +02001206 self.isWindows = (platform.system() == "Windows")
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -03001207 self.keepRepoPath = False
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001208 self.depotPaths = None
Simon Hausmann3c699642007-06-16 13:09:21 +02001209 self.p4BranchesInGit = []
Tommy Thorn354081d2008-02-03 10:38:51 -08001210 self.cloneExclude = []
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001211 self.useClientSpec = False
1212 self.clientSpecDirs = []
Simon Hausmannb9847332007-03-20 20:54:23 +01001213
Simon Hausmann01265102007-05-25 10:36:10 +02001214 if gitConfig("git-p4.syncFromOrigin") == "false":
1215 self.syncWithOrigin = False
1216
Pete Wyckoff084f6302011-02-19 08:18:00 -05001217 #
1218 # P4 wildcards are not allowed in filenames. P4 complains
1219 # if you simply add them, but you can force it with "-f", in
1220 # which case it translates them into %xx encoding internally.
1221 # Search for and fix just these four characters. Do % last so
1222 # that fixing it does not inadvertently create new %-escapes.
1223 #
1224 def wildcard_decode(self, path):
1225 # Cannot have * in a filename in windows; untested as to
1226 # what p4 would do in such a case.
1227 if not self.isWindows:
1228 path = path.replace("%2A", "*")
1229 path = path.replace("%23", "#") \
1230 .replace("%40", "@") \
1231 .replace("%25", "%")
1232 return path
1233
Simon Hausmannb9847332007-03-20 20:54:23 +01001234 def extractFilesFromCommit(self, commit):
Tommy Thorn354081d2008-02-03 10:38:51 -08001235 self.cloneExclude = [re.sub(r"\.\.\.$", "", path)
1236 for path in self.cloneExclude]
Simon Hausmannb9847332007-03-20 20:54:23 +01001237 files = []
1238 fnum = 0
1239 while commit.has_key("depotFile%s" % fnum):
1240 path = commit["depotFile%s" % fnum]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001241
Tommy Thorn354081d2008-02-03 10:38:51 -08001242 if [p for p in self.cloneExclude
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +01001243 if p4PathStartsWith(path, p)]:
Tommy Thorn354081d2008-02-03 10:38:51 -08001244 found = False
1245 else:
1246 found = [p for p in self.depotPaths
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +01001247 if p4PathStartsWith(path, p)]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001248 if not found:
Simon Hausmannb9847332007-03-20 20:54:23 +01001249 fnum = fnum + 1
1250 continue
1251
1252 file = {}
1253 file["path"] = path
1254 file["rev"] = commit["rev%s" % fnum]
1255 file["action"] = commit["action%s" % fnum]
1256 file["type"] = commit["type%s" % fnum]
1257 files.append(file)
1258 fnum = fnum + 1
1259 return files
1260
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001261 def stripRepoPath(self, path, prefixes):
Ian Wienand39527102011-02-11 16:33:48 -08001262 if self.useClientSpec:
1263
1264 # if using the client spec, we use the output directory
1265 # specified in the client. For example, a view
1266 # //depot/foo/branch/... //client/branch/foo/...
1267 # will end up putting all foo/branch files into
1268 # branch/foo/
1269 for val in self.clientSpecDirs:
1270 if path.startswith(val[0]):
1271 # replace the depot path with the client path
1272 path = path.replace(val[0], val[1][1])
1273 # now strip out the client (//client/...)
1274 path = re.sub("^(//[^/]+/)", '', path)
1275 # the rest is all path
1276 return path
1277
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -03001278 if self.keepRepoPath:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001279 prefixes = [re.sub("^(//[^/]+/).*", r'\1', prefixes[0])]
Han-Wen Nienhuys8b41a972007-05-23 18:20:53 -03001280
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001281 for p in prefixes:
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +01001282 if p4PathStartsWith(path, p):
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001283 path = path[len(p):]
1284
1285 return path
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -03001286
Simon Hausmann71b112d2007-05-19 11:54:11 +02001287 def splitFilesIntoBranches(self, commit):
Simon Hausmannd5904672007-05-19 11:07:32 +02001288 branches = {}
Simon Hausmann71b112d2007-05-19 11:54:11 +02001289 fnum = 0
1290 while commit.has_key("depotFile%s" % fnum):
1291 path = commit["depotFile%s" % fnum]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001292 found = [p for p in self.depotPaths
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +01001293 if p4PathStartsWith(path, p)]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001294 if not found:
Simon Hausmann71b112d2007-05-19 11:54:11 +02001295 fnum = fnum + 1
1296 continue
1297
1298 file = {}
1299 file["path"] = path
1300 file["rev"] = commit["rev%s" % fnum]
1301 file["action"] = commit["action%s" % fnum]
1302 file["type"] = commit["type%s" % fnum]
1303 fnum = fnum + 1
1304
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001305 relPath = self.stripRepoPath(path, self.depotPaths)
Simon Hausmannb9847332007-03-20 20:54:23 +01001306
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001307 for branch in self.knownBranches.keys():
Han-Wen Nienhuys6754a292007-05-23 17:41:50 -03001308
1309 # add a trailing slash so that a commit into qt/4.2foo doesn't end up in qt/4.2
1310 if relPath.startswith(branch + "/"):
Simon Hausmannd5904672007-05-19 11:07:32 +02001311 if branch not in branches:
1312 branches[branch] = []
Simon Hausmann71b112d2007-05-19 11:54:11 +02001313 branches[branch].append(file)
Simon Hausmann6555b2c2007-06-17 11:25:34 +02001314 break
Simon Hausmannb9847332007-03-20 20:54:23 +01001315
1316 return branches
1317
Luke Diamandb9327052009-07-30 00:13:46 +01001318 # output one file from the P4 stream
1319 # - helper for streamP4Files
1320
1321 def streamOneP4File(self, file, contents):
Luke Diamandb9327052009-07-30 00:13:46 +01001322 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
Pete Wyckoff084f6302011-02-19 08:18:00 -05001323 relPath = self.wildcard_decode(relPath)
Luke Diamandb9327052009-07-30 00:13:46 +01001324 if verbose:
1325 sys.stderr.write("%s\n" % relPath)
1326
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -04001327 (type_base, type_mods) = split_p4_type(file["type"])
1328
1329 git_mode = "100644"
1330 if "x" in type_mods:
1331 git_mode = "100755"
1332 if type_base == "symlink":
1333 git_mode = "120000"
1334 # p4 print on a symlink contains "target\n"; remove the newline
Evan Powersb39c3612010-02-16 00:44:08 -08001335 data = ''.join(contents)
1336 contents = [data[:-1]]
Luke Diamandb9327052009-07-30 00:13:46 +01001337
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -04001338 if type_base == "utf16":
Pete Wyckoff55aa5712011-09-17 19:16:14 -04001339 # p4 delivers different text in the python output to -G
1340 # than it does when using "print -o", or normal p4 client
1341 # operations. utf16 is converted to ascii or utf8, perhaps.
1342 # But ascii text saved as -t utf16 is completely mangled.
1343 # Invoke print -o to get the real contents.
Luke Diamand6de040d2011-10-16 10:47:52 -04001344 text = p4_read_pipe(['print', '-q', '-o', '-', file['depotFile']])
Pete Wyckoff55aa5712011-09-17 19:16:14 -04001345 contents = [ text ]
1346
Pete Wyckoff9f7ef0e2011-11-05 13:36:07 -04001347 if type_base == "apple":
1348 # Apple filetype files will be streamed as a concatenation of
1349 # its appledouble header and the contents. This is useless
1350 # on both macs and non-macs. If using "print -q -o xx", it
1351 # will create "xx" with the data, and "%xx" with the header.
1352 # This is also not very useful.
1353 #
1354 # Ideally, someday, this script can learn how to generate
1355 # appledouble files directly and import those to git, but
1356 # non-mac machines can never find a use for apple filetype.
1357 print "\nIgnoring apple filetype file %s" % file['depotFile']
1358 return
1359
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -04001360 # Perhaps windows wants unicode, utf16 newlines translated too;
1361 # but this is not doing it.
1362 if self.isWindows and type_base == "text":
Luke Diamandb9327052009-07-30 00:13:46 +01001363 mangled = []
1364 for data in contents:
1365 data = data.replace("\r\n", "\n")
1366 mangled.append(data)
1367 contents = mangled
1368
Pete Wyckoff55aa5712011-09-17 19:16:14 -04001369 # Note that we do not try to de-mangle keywords on utf16 files,
1370 # even though in theory somebody may want that.
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -04001371 if type_base in ("text", "unicode", "binary"):
1372 if "ko" in type_mods:
Pete Wyckoffcb585a92011-10-16 10:46:52 -04001373 text = ''.join(contents)
1374 text = re.sub(r'\$(Id|Header):[^$]*\$', r'$\1$', text)
1375 contents = [ text ]
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -04001376 elif "k" in type_mods:
Pete Wyckoffcb585a92011-10-16 10:46:52 -04001377 text = ''.join(contents)
1378 text = re.sub(r'\$(Id|Header|Author|Date|DateTime|Change|File|Revision):[^$]*\$', r'$\1$', text)
1379 contents = [ text ]
Luke Diamandb9327052009-07-30 00:13:46 +01001380
Pete Wyckoff9cffb8c2011-10-16 10:45:01 -04001381 self.gitStream.write("M %s inline %s\n" % (git_mode, relPath))
Luke Diamandb9327052009-07-30 00:13:46 +01001382
1383 # total length...
1384 length = 0
1385 for d in contents:
1386 length = length + len(d)
1387
1388 self.gitStream.write("data %d\n" % length)
1389 for d in contents:
1390 self.gitStream.write(d)
1391 self.gitStream.write("\n")
1392
1393 def streamOneP4Deletion(self, file):
1394 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
1395 if verbose:
1396 sys.stderr.write("delete %s\n" % relPath)
1397 self.gitStream.write("D %s\n" % relPath)
1398
1399 # handle another chunk of streaming data
1400 def streamP4FilesCb(self, marshalled):
1401
Andrew Garberc3f61632011-04-07 02:01:21 -04001402 if marshalled.has_key('depotFile') and self.stream_have_file_info:
1403 # start of a new file - output the old one first
1404 self.streamOneP4File(self.stream_file, self.stream_contents)
1405 self.stream_file = {}
1406 self.stream_contents = []
1407 self.stream_have_file_info = False
Luke Diamandb9327052009-07-30 00:13:46 +01001408
Andrew Garberc3f61632011-04-07 02:01:21 -04001409 # pick up the new file information... for the
1410 # 'data' field we need to append to our array
1411 for k in marshalled.keys():
1412 if k == 'data':
1413 self.stream_contents.append(marshalled['data'])
1414 else:
1415 self.stream_file[k] = marshalled[k]
Luke Diamandb9327052009-07-30 00:13:46 +01001416
Andrew Garberc3f61632011-04-07 02:01:21 -04001417 self.stream_have_file_info = True
Luke Diamandb9327052009-07-30 00:13:46 +01001418
1419 # Stream directly from "p4 files" into "git fast-import"
1420 def streamP4Files(self, files):
Simon Hausmann30b59402008-03-03 11:55:48 +01001421 filesForCommit = []
1422 filesToRead = []
Luke Diamandb9327052009-07-30 00:13:46 +01001423 filesToDelete = []
Simon Hausmann30b59402008-03-03 11:55:48 +01001424
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001425 for f in files:
Simon Hausmann30b59402008-03-03 11:55:48 +01001426 includeFile = True
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001427 for val in self.clientSpecDirs:
1428 if f['path'].startswith(val[0]):
Ian Wienand39527102011-02-11 16:33:48 -08001429 if val[1][0] <= 0:
Simon Hausmann30b59402008-03-03 11:55:48 +01001430 includeFile = False
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001431 break
1432
Simon Hausmann30b59402008-03-03 11:55:48 +01001433 if includeFile:
1434 filesForCommit.append(f)
Pete Wyckoff56c09342011-02-19 08:17:57 -05001435 if f['action'] in self.delete_actions:
Luke Diamandb9327052009-07-30 00:13:46 +01001436 filesToDelete.append(f)
Pete Wyckoff56c09342011-02-19 08:17:57 -05001437 else:
1438 filesToRead.append(f)
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001439
Luke Diamandb9327052009-07-30 00:13:46 +01001440 # deleted files...
1441 for f in filesToDelete:
1442 self.streamOneP4Deletion(f)
1443
Simon Hausmann30b59402008-03-03 11:55:48 +01001444 if len(filesToRead) > 0:
Luke Diamandb9327052009-07-30 00:13:46 +01001445 self.stream_file = {}
1446 self.stream_contents = []
1447 self.stream_have_file_info = False
1448
Andrew Garberc3f61632011-04-07 02:01:21 -04001449 # curry self argument
1450 def streamP4FilesCbSelf(entry):
1451 self.streamP4FilesCb(entry)
Luke Diamandb9327052009-07-30 00:13:46 +01001452
Luke Diamand6de040d2011-10-16 10:47:52 -04001453 fileArgs = ['%s#%s' % (f['path'], f['rev']) for f in filesToRead]
1454
1455 p4CmdList(["-x", "-", "print"],
1456 stdin=fileArgs,
1457 cb=streamP4FilesCbSelf)
Han-Wen Nienhuysf2eda792007-05-23 18:49:35 -03001458
Luke Diamandb9327052009-07-30 00:13:46 +01001459 # do the last chunk
1460 if self.stream_file.has_key('depotFile'):
1461 self.streamOneP4File(self.stream_file, self.stream_contents)
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001462
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001463 def commit(self, details, files, branch, branchPrefixes, parent = ""):
Simon Hausmannb9847332007-03-20 20:54:23 +01001464 epoch = details["time"]
1465 author = details["user"]
Andrew Garberc3f61632011-04-07 02:01:21 -04001466 self.branchPrefixes = branchPrefixes
Simon Hausmannb9847332007-03-20 20:54:23 +01001467
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001468 if self.verbose:
1469 print "commit into %s" % branch
1470
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -03001471 # start with reading files; if that fails, we should not
1472 # create a commit.
1473 new_files = []
1474 for f in files:
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +01001475 if [p for p in branchPrefixes if p4PathStartsWith(f['path'], p)]:
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -03001476 new_files.append (f)
1477 else:
Tor Arvid Lundafa1dd92011-03-15 13:08:03 +01001478 sys.stderr.write("Ignoring file outside of prefix: %s\n" % f['path'])
Han-Wen Nienhuys96e07dd2007-05-23 18:49:35 -03001479
Simon Hausmannb9847332007-03-20 20:54:23 +01001480 self.gitStream.write("commit %s\n" % branch)
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001481# gitStream.write("mark :%s\n" % details["change"])
Simon Hausmannb9847332007-03-20 20:54:23 +01001482 self.committedChanges.add(int(details["change"]))
1483 committer = ""
Simon Hausmannb607e712007-05-20 10:55:54 +02001484 if author not in self.users:
1485 self.getUserMapFromPerforceServer()
Simon Hausmannb9847332007-03-20 20:54:23 +01001486 if author in self.users:
Simon Hausmann0828ab12007-03-20 20:59:30 +01001487 committer = "%s %s %s" % (self.users[author], epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +01001488 else:
Simon Hausmann0828ab12007-03-20 20:59:30 +01001489 committer = "%s <a@b> %s %s" % (author, epoch, self.tz)
Simon Hausmannb9847332007-03-20 20:54:23 +01001490
1491 self.gitStream.write("committer %s\n" % committer)
1492
1493 self.gitStream.write("data <<EOT\n")
1494 self.gitStream.write(details["desc"])
Simon Hausmann6581de02007-06-11 10:01:58 +02001495 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s"
1496 % (','.join (branchPrefixes), details["change"]))
1497 if len(details['options']) > 0:
1498 self.gitStream.write(": options = %s" % details['options'])
1499 self.gitStream.write("]\nEOT\n\n")
Simon Hausmannb9847332007-03-20 20:54:23 +01001500
1501 if len(parent) > 0:
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001502 if self.verbose:
1503 print "parent %s" % parent
Simon Hausmannb9847332007-03-20 20:54:23 +01001504 self.gitStream.write("from %s\n" % parent)
1505
Luke Diamandb9327052009-07-30 00:13:46 +01001506 self.streamP4Files(new_files)
Simon Hausmannb9847332007-03-20 20:54:23 +01001507 self.gitStream.write("\n")
1508
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001509 change = int(details["change"])
1510
Simon Hausmann9bda3a82007-05-19 12:05:40 +02001511 if self.labels.has_key(change):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001512 label = self.labels[change]
1513 labelDetails = label[0]
1514 labelRevisions = label[1]
Simon Hausmann71b112d2007-05-19 11:54:11 +02001515 if self.verbose:
1516 print "Change %s is labelled %s" % (change, labelDetails)
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001517
Luke Diamand6de040d2011-10-16 10:47:52 -04001518 files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
1519 for p in branchPrefixes])
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001520
1521 if len(files) == len(labelRevisions):
1522
1523 cleanedFiles = {}
1524 for info in files:
Pete Wyckoff56c09342011-02-19 08:17:57 -05001525 if info["action"] in self.delete_actions:
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001526 continue
1527 cleanedFiles[info["depotFile"]] = info["rev"]
1528
1529 if cleanedFiles == labelRevisions:
1530 self.gitStream.write("tag tag_%s\n" % labelDetails["label"])
1531 self.gitStream.write("from %s\n" % branch)
1532
1533 owner = labelDetails["Owner"]
1534 tagger = ""
1535 if author in self.users:
1536 tagger = "%s %s %s" % (self.users[owner], epoch, self.tz)
1537 else:
1538 tagger = "%s <a@b> %s %s" % (owner, epoch, self.tz)
1539 self.gitStream.write("tagger %s\n" % tagger)
1540 self.gitStream.write("data <<EOT\n")
1541 self.gitStream.write(labelDetails["Description"])
1542 self.gitStream.write("EOT\n\n")
1543
1544 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +02001545 if not self.silent:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001546 print ("Tag %s does not match with change %s: files do not match."
1547 % (labelDetails["label"], change))
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001548
1549 else:
Simon Hausmanna46668f2007-03-28 17:05:38 +02001550 if not self.silent:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001551 print ("Tag %s does not match with change %s: file count is different."
1552 % (labelDetails["label"], change))
Simon Hausmannb9847332007-03-20 20:54:23 +01001553
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001554 def getLabels(self):
1555 self.labels = {}
1556
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001557 l = p4CmdList("labels %s..." % ' '.join (self.depotPaths))
Simon Hausmann10c32112007-04-08 10:15:47 +02001558 if len(l) > 0 and not self.silent:
Shun Kei Leung183f8432007-11-21 11:01:19 +08001559 print "Finding files belonging to labels in %s" % `self.depotPaths`
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02001560
1561 for output in l:
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001562 label = output["label"]
1563 revisions = {}
1564 newestChange = 0
Simon Hausmann71b112d2007-05-19 11:54:11 +02001565 if self.verbose:
1566 print "Querying files for label %s" % label
Luke Diamand6de040d2011-10-16 10:47:52 -04001567 for file in p4CmdList(["files"] +
1568 ["%s...@%s" % (p, label)
1569 for p in self.depotPaths]):
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001570 revisions[file["depotFile"]] = file["rev"]
1571 change = int(file["change"])
1572 if change > newestChange:
1573 newestChange = change
1574
Simon Hausmann9bda3a82007-05-19 12:05:40 +02001575 self.labels[newestChange] = [output, revisions]
1576
1577 if self.verbose:
1578 print "Label changes: %s" % self.labels.keys()
Simon Hausmann1f4ba1c2007-03-26 22:34:34 +02001579
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001580 def guessProjectName(self):
1581 for p in self.depotPaths:
Simon Hausmann6e5295c2007-06-11 08:50:57 +02001582 if p.endswith("/"):
1583 p = p[:-1]
1584 p = p[p.strip().rfind("/") + 1:]
1585 if not p.endswith("/"):
1586 p += "/"
1587 return p
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03001588
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001589 def getBranchMapping(self):
Simon Hausmann6555b2c2007-06-17 11:25:34 +02001590 lostAndFoundBranches = set()
1591
Vitor Antunes8ace74c2011-08-19 00:44:04 +01001592 user = gitConfig("git-p4.branchUser")
1593 if len(user) > 0:
1594 command = "branches -u %s" % user
1595 else:
1596 command = "branches"
1597
1598 for info in p4CmdList(command):
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001599 details = p4Cmd("branch -o %s" % info["branch"])
1600 viewIdx = 0
1601 while details.has_key("View%s" % viewIdx):
1602 paths = details["View%s" % viewIdx].split(" ")
1603 viewIdx = viewIdx + 1
1604 # require standard //depot/foo/... //depot/bar/... mapping
1605 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
1606 continue
1607 source = paths[0]
1608 destination = paths[1]
Simon Hausmann6509e192007-06-07 09:41:53 +02001609 ## HACK
Tor Arvid Lundd53de8b2011-03-15 13:08:02 +01001610 if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
Simon Hausmann6509e192007-06-07 09:41:53 +02001611 source = source[len(self.depotPaths[0]):-4]
1612 destination = destination[len(self.depotPaths[0]):-4]
Simon Hausmann6555b2c2007-06-17 11:25:34 +02001613
Simon Hausmann1a2edf42007-06-17 15:10:24 +02001614 if destination in self.knownBranches:
1615 if not self.silent:
1616 print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination)
1617 print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination)
1618 continue
1619
Simon Hausmann6555b2c2007-06-17 11:25:34 +02001620 self.knownBranches[destination] = source
1621
1622 lostAndFoundBranches.discard(destination)
1623
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001624 if source not in self.knownBranches:
Simon Hausmann6555b2c2007-06-17 11:25:34 +02001625 lostAndFoundBranches.add(source)
1626
Vitor Antunes7199cf12011-08-19 00:44:05 +01001627 # Perforce does not strictly require branches to be defined, so we also
1628 # check git config for a branch list.
1629 #
1630 # Example of branch definition in git config file:
1631 # [git-p4]
1632 # branchList=main:branchA
1633 # branchList=main:branchB
1634 # branchList=branchA:branchC
1635 configBranches = gitConfigList("git-p4.branchList")
1636 for branch in configBranches:
1637 if branch:
1638 (source, destination) = branch.split(":")
1639 self.knownBranches[destination] = source
1640
1641 lostAndFoundBranches.discard(destination)
1642
1643 if source not in self.knownBranches:
1644 lostAndFoundBranches.add(source)
1645
Simon Hausmann6555b2c2007-06-17 11:25:34 +02001646
1647 for branch in lostAndFoundBranches:
1648 self.knownBranches[branch] = branch
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001649
Simon Hausmann38f9f5e2007-11-15 10:38:45 +01001650 def getBranchMappingFromGitBranches(self):
1651 branches = p4BranchesInGit(self.importIntoRemotes)
1652 for branch in branches.keys():
1653 if branch == "master":
1654 branch = "main"
1655 else:
1656 branch = branch[len(self.projectName):]
1657 self.knownBranches[branch] = branch
1658
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001659 def listExistingP4GitBranches(self):
Simon Hausmann144ff462007-07-18 17:27:50 +02001660 # branches holds mapping from name to commit
1661 branches = p4BranchesInGit(self.importIntoRemotes)
1662 self.p4BranchesInGit = branches.keys()
1663 for branch in branches.keys():
1664 self.initialParents[self.refPrefix + branch] = branches[branch]
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02001665
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001666 def updateOptionDict(self, d):
1667 option_keys = {}
1668 if self.keepRepoPath:
1669 option_keys['keepRepoPath'] = 1
1670
1671 d["options"] = ' '.join(sorted(option_keys.keys()))
1672
1673 def readOptions(self, d):
1674 self.keepRepoPath = (d.has_key('options')
1675 and ('keepRepoPath' in d['options']))
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001676
Simon Hausmann8134f692007-08-26 16:44:55 +02001677 def gitRefForBranch(self, branch):
1678 if branch == "main":
1679 return self.refPrefix + "master"
1680
1681 if len(branch) <= 0:
1682 return branch
1683
1684 return self.refPrefix + self.projectName + branch
1685
Simon Hausmann1ca3d712007-08-26 17:36:55 +02001686 def gitCommitByP4Change(self, ref, change):
1687 if self.verbose:
1688 print "looking in ref " + ref + " for change %s using bisect..." % change
1689
1690 earliestCommit = ""
1691 latestCommit = parseRevision(ref)
1692
1693 while True:
1694 if self.verbose:
1695 print "trying: earliest %s latest %s" % (earliestCommit, latestCommit)
1696 next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
1697 if len(next) == 0:
1698 if self.verbose:
1699 print "argh"
1700 return ""
1701 log = extractLogMessageFromGitCommit(next)
1702 settings = extractSettingsGitLog(log)
1703 currentChange = int(settings['change'])
1704 if self.verbose:
1705 print "current change %s" % currentChange
1706
1707 if currentChange == change:
1708 if self.verbose:
1709 print "found %s" % next
1710 return next
1711
1712 if currentChange < change:
1713 earliestCommit = "^%s" % next
1714 else:
1715 latestCommit = "%s" % next
1716
1717 return ""
1718
1719 def importNewBranch(self, branch, maxChange):
1720 # make fast-import flush all changes to disk and update the refs using the checkpoint
1721 # command so that we can try to find the branch parent in the git history
1722 self.gitStream.write("checkpoint\n\n");
1723 self.gitStream.flush();
1724 branchPrefix = self.depotPaths[0] + branch + "/"
1725 range = "@1,%s" % maxChange
1726 #print "prefix" + branchPrefix
1727 changes = p4ChangesForPaths([branchPrefix], range)
1728 if len(changes) <= 0:
1729 return False
1730 firstChange = changes[0]
1731 #print "first change in branch: %s" % firstChange
1732 sourceBranch = self.knownBranches[branch]
1733 sourceDepotPath = self.depotPaths[0] + sourceBranch
1734 sourceRef = self.gitRefForBranch(sourceBranch)
1735 #print "source " + sourceBranch
1736
1737 branchParentChange = int(p4Cmd("changes -m 1 %s...@1,%s" % (sourceDepotPath, firstChange))["change"])
1738 #print "branch parent: %s" % branchParentChange
1739 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
1740 if len(gitParent) > 0:
1741 self.initialParents[self.gitRefForBranch(branch)] = gitParent
1742 #print "parent git commit: %s" % gitParent
1743
1744 self.importChanges(changes)
1745 return True
1746
Simon Hausmanne87f37a2007-08-26 16:00:52 +02001747 def importChanges(self, changes):
1748 cnt = 1
1749 for change in changes:
1750 description = p4Cmd("describe %s" % change)
1751 self.updateOptionDict(description)
1752
1753 if not self.silent:
1754 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
1755 sys.stdout.flush()
1756 cnt = cnt + 1
1757
1758 try:
1759 if self.detectBranches:
1760 branches = self.splitFilesIntoBranches(description)
1761 for branch in branches.keys():
1762 ## HACK --hwn
1763 branchPrefix = self.depotPaths[0] + branch + "/"
1764
1765 parent = ""
1766
1767 filesForCommit = branches[branch]
1768
1769 if self.verbose:
1770 print "branch is %s" % branch
1771
1772 self.updatedBranches.add(branch)
1773
1774 if branch not in self.createdBranches:
1775 self.createdBranches.add(branch)
1776 parent = self.knownBranches[branch]
1777 if parent == branch:
1778 parent = ""
Simon Hausmann1ca3d712007-08-26 17:36:55 +02001779 else:
1780 fullBranch = self.projectName + branch
1781 if fullBranch not in self.p4BranchesInGit:
1782 if not self.silent:
1783 print("\n Importing new branch %s" % fullBranch);
1784 if self.importNewBranch(branch, change - 1):
1785 parent = ""
1786 self.p4BranchesInGit.append(fullBranch)
1787 if not self.silent:
1788 print("\n Resuming with change %s" % change);
1789
1790 if self.verbose:
1791 print "parent determined through known branches: %s" % parent
Simon Hausmanne87f37a2007-08-26 16:00:52 +02001792
Simon Hausmann8134f692007-08-26 16:44:55 +02001793 branch = self.gitRefForBranch(branch)
1794 parent = self.gitRefForBranch(parent)
Simon Hausmanne87f37a2007-08-26 16:00:52 +02001795
1796 if self.verbose:
1797 print "looking for initial parent for %s; current parent is %s" % (branch, parent)
1798
1799 if len(parent) == 0 and branch in self.initialParents:
1800 parent = self.initialParents[branch]
1801 del self.initialParents[branch]
1802
1803 self.commit(description, filesForCommit, branch, [branchPrefix], parent)
1804 else:
1805 files = self.extractFilesFromCommit(description)
1806 self.commit(description, files, self.branch, self.depotPaths,
1807 self.initialParent)
1808 self.initialParent = ""
1809 except IOError:
1810 print self.gitError.read()
1811 sys.exit(1)
1812
Simon Hausmannc208a242007-08-26 16:07:18 +02001813 def importHeadRevision(self, revision):
1814 print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch)
1815
Pete Wyckoff4e2e6ce2011-07-31 09:45:55 -04001816 details = {}
1817 details["user"] = "git perforce import user"
Pete Wyckoff1494fcb2011-02-19 08:17:56 -05001818 details["desc"] = ("Initial import of %s from the state at revision %s\n"
Simon Hausmannc208a242007-08-26 16:07:18 +02001819 % (' '.join(self.depotPaths), revision))
1820 details["change"] = revision
1821 newestRevision = 0
1822
1823 fileCnt = 0
Luke Diamand6de040d2011-10-16 10:47:52 -04001824 fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
1825
1826 for info in p4CmdList(["files"] + fileArgs):
Simon Hausmannc208a242007-08-26 16:07:18 +02001827
Pete Wyckoff68b28592011-02-19 08:17:55 -05001828 if 'code' in info and info['code'] == 'error':
Simon Hausmannc208a242007-08-26 16:07:18 +02001829 sys.stderr.write("p4 returned an error: %s\n"
1830 % info['data'])
Pete Wyckoffd88e7072011-02-19 08:17:58 -05001831 if info['data'].find("must refer to client") >= 0:
1832 sys.stderr.write("This particular p4 error is misleading.\n")
1833 sys.stderr.write("Perhaps the depot path was misspelled.\n");
1834 sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
Simon Hausmannc208a242007-08-26 16:07:18 +02001835 sys.exit(1)
Pete Wyckoff68b28592011-02-19 08:17:55 -05001836 if 'p4ExitCode' in info:
1837 sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
Simon Hausmannc208a242007-08-26 16:07:18 +02001838 sys.exit(1)
1839
1840
1841 change = int(info["change"])
1842 if change > newestRevision:
1843 newestRevision = change
1844
Pete Wyckoff56c09342011-02-19 08:17:57 -05001845 if info["action"] in self.delete_actions:
Simon Hausmannc208a242007-08-26 16:07:18 +02001846 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
1847 #fileCnt = fileCnt + 1
1848 continue
1849
1850 for prop in ["depotFile", "rev", "action", "type" ]:
1851 details["%s%s" % (prop, fileCnt)] = info[prop]
1852
1853 fileCnt = fileCnt + 1
1854
1855 details["change"] = newestRevision
Pete Wyckoff4e2e6ce2011-07-31 09:45:55 -04001856
1857 # Use time from top-most change so that all git-p4 clones of
1858 # the same p4 repo have the same commit SHA1s.
1859 res = p4CmdList("describe -s %d" % newestRevision)
1860 newestTime = None
1861 for r in res:
1862 if r.has_key('time'):
1863 newestTime = int(r['time'])
1864 if newestTime is None:
1865 die("\"describe -s\" on newest change %d did not give a time")
1866 details["time"] = newestTime
1867
Simon Hausmannc208a242007-08-26 16:07:18 +02001868 self.updateOptionDict(details)
1869 try:
1870 self.commit(details, self.extractFilesFromCommit(details), self.branch, self.depotPaths)
1871 except IOError:
1872 print "IO error with git fast-import. Is your git version recent enough?"
1873 print self.gitError.read()
1874
1875
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001876 def getClientSpec(self):
1877 specList = p4CmdList( "client -o" )
1878 temp = {}
1879 for entry in specList:
1880 for k,v in entry.iteritems():
1881 if k.startswith("View"):
Ian Wienand39527102011-02-11 16:33:48 -08001882
1883 # p4 has these %%1 to %%9 arguments in specs to
1884 # reorder paths; which we can't handle (yet :)
1885 if re.match('%%\d', v) != None:
1886 print "Sorry, can't handle %%n arguments in client specs"
1887 sys.exit(1)
1888
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001889 if v.startswith('"'):
1890 start = 1
1891 else:
1892 start = 0
1893 index = v.find("...")
Ian Wienand39527102011-02-11 16:33:48 -08001894
1895 # save the "client view"; i.e the RHS of the view
1896 # line that tells the client where to put the
1897 # files for this view.
1898 cv = v[index+3:].strip() # +3 to remove previous '...'
1899
1900 # if the client view doesn't end with a
1901 # ... wildcard, then we're going to mess up the
1902 # output directory, so fail gracefully.
1903 if not cv.endswith('...'):
1904 print 'Sorry, client view in "%s" needs to end with wildcard' % (k)
1905 sys.exit(1)
1906 cv=cv[:-3]
1907
1908 # now save the view; +index means included, -index
1909 # means it should be filtered out.
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001910 v = v[start:index]
1911 if v.startswith("-"):
1912 v = v[1:]
Ian Wienand39527102011-02-11 16:33:48 -08001913 include = -len(v)
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001914 else:
Ian Wienand39527102011-02-11 16:33:48 -08001915 include = len(v)
1916
1917 temp[v] = (include, cv)
1918
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001919 self.clientSpecDirs = temp.items()
Ian Wienand39527102011-02-11 16:33:48 -08001920 self.clientSpecDirs.sort( lambda x, y: abs( y[1][0] ) - abs( x[1][0] ) )
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001921
Simon Hausmannb9847332007-03-20 20:54:23 +01001922 def run(self, args):
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001923 self.depotPaths = []
Simon Hausmann179caeb2007-03-22 22:17:42 +01001924 self.changeRange = ""
1925 self.initialParent = ""
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001926 self.previousDepotPaths = []
Han-Wen Nienhuysce6f33c2007-05-23 16:46:29 -03001927
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001928 # map from branch depot path to parent branch
1929 self.knownBranches = {}
1930 self.initialParents = {}
Simon Hausmann5ca44612007-08-24 17:44:16 +02001931 self.hasOrigin = originP4BranchesExist()
Simon Hausmanna43ff002007-06-11 09:59:27 +02001932 if not self.syncWithOrigin:
1933 self.hasOrigin = False
Simon Hausmann179caeb2007-03-22 22:17:42 +01001934
Simon Hausmanna028a982007-05-23 00:03:08 +02001935 if self.importIntoRemotes:
1936 self.refPrefix = "refs/remotes/p4/"
1937 else:
Marius Storm-Olsendb775552007-06-07 15:13:59 +02001938 self.refPrefix = "refs/heads/p4/"
Simon Hausmanna028a982007-05-23 00:03:08 +02001939
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001940 if self.syncWithOrigin and self.hasOrigin:
1941 if not self.silent:
1942 print "Syncing with origin first by calling git fetch origin"
1943 system("git fetch origin")
Simon Hausmann10f880f2007-05-24 22:28:28 +02001944
Simon Hausmann569d1bd2007-03-22 21:34:16 +01001945 if len(self.branch) == 0:
Marius Storm-Olsendb775552007-06-07 15:13:59 +02001946 self.branch = self.refPrefix + "master"
Simon Hausmanna028a982007-05-23 00:03:08 +02001947 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
Simon Hausmann48df6fd2007-05-17 21:18:53 +02001948 system("git update-ref %s refs/heads/p4" % self.branch)
Simon Hausmann48df6fd2007-05-17 21:18:53 +02001949 system("git branch -D p4");
Simon Hausmannfaf1bd22007-05-21 10:05:30 +02001950 # create it /after/ importing, when master exists
Simon Hausmann0058a332007-08-24 17:46:16 +02001951 if not gitBranchExists(self.refPrefix + "HEAD") and self.importIntoRemotes and gitBranchExists(self.branch):
Simon Hausmanna3c55c02007-05-27 15:48:01 +02001952 system("git symbolic-ref %sHEAD %s" % (self.refPrefix, self.branch))
Simon Hausmann179caeb2007-03-22 22:17:42 +01001953
Anand Kumria3cafb7d2008-08-10 19:26:32 +01001954 if self.useClientSpec or gitConfig("git-p4.useclientspec") == "true":
Tor Arvid Lund3a70cdf2008-02-18 15:22:08 +01001955 self.getClientSpec()
1956
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03001957 # TODO: should always look at previous commits,
1958 # merge with previous imports, if possible.
1959 if args == []:
Simon Hausmannd414c742007-05-25 11:36:42 +02001960 if self.hasOrigin:
Simon Hausmann5ca44612007-08-24 17:44:16 +02001961 createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
Simon Hausmannabcd7902007-05-24 22:25:36 +02001962 self.listExistingP4GitBranches()
1963
1964 if len(self.p4BranchesInGit) > 1:
1965 if not self.silent:
1966 print "Importing from/into multiple branches"
1967 self.detectBranches = True
Simon Hausmann967f72e2007-03-23 09:30:41 +01001968
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001969 if self.verbose:
1970 print "branches: %s" % self.p4BranchesInGit
1971
1972 p4Change = 0
1973 for branch in self.p4BranchesInGit:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03001974 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001975
1976 settings = extractSettingsGitLog(logMsg)
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001977
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001978 self.readOptions(settings)
1979 if (settings.has_key('depot-paths')
1980 and settings.has_key ('change')):
1981 change = int(settings['change']) + 1
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001982 p4Change = max(p4Change, change)
1983
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03001984 depotPaths = sorted(settings['depot-paths'])
1985 if self.previousDepotPaths == []:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001986 self.previousDepotPaths = depotPaths
Simon Hausmann29bdbac2007-05-19 10:23:12 +02001987 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001988 paths = []
1989 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
Vitor Antunes04d277b2011-08-19 00:44:03 +01001990 prev_list = prev.split("/")
1991 cur_list = cur.split("/")
1992 for i in range(0, min(len(cur_list), len(prev_list))):
1993 if cur_list[i] <> prev_list[i]:
Simon Hausmann583e1702007-06-07 09:37:13 +02001994 i = i - 1
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001995 break
1996
Vitor Antunes04d277b2011-08-19 00:44:03 +01001997 paths.append ("/".join(cur_list[:i + 1]))
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03001998
1999 self.previousDepotPaths = paths
Simon Hausmann29bdbac2007-05-19 10:23:12 +02002000
2001 if p4Change > 0:
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002002 self.depotPaths = sorted(self.previousDepotPaths)
Simon Hausmannd5904672007-05-19 11:07:32 +02002003 self.changeRange = "@%s,#head" % p4Change
Simon Hausmann330f53b2007-06-07 09:39:51 +02002004 if not self.detectBranches:
2005 self.initialParent = parseRevision(self.branch)
Simon Hausmann341dc1c2007-05-21 00:39:16 +02002006 if not self.silent and not self.detectBranches:
Simon Hausmann967f72e2007-03-23 09:30:41 +01002007 print "Performing incremental import into %s git branch" % self.branch
Simon Hausmann569d1bd2007-03-22 21:34:16 +01002008
Simon Hausmannf9162f62007-05-17 09:02:45 +02002009 if not self.branch.startswith("refs/"):
2010 self.branch = "refs/heads/" + self.branch
Simon Hausmann179caeb2007-03-22 22:17:42 +01002011
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002012 if len(args) == 0 and self.depotPaths:
Simon Hausmannb9847332007-03-20 20:54:23 +01002013 if not self.silent:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002014 print "Depot paths: %s" % ' '.join(self.depotPaths)
Simon Hausmannb9847332007-03-20 20:54:23 +01002015 else:
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002016 if self.depotPaths and self.depotPaths != args:
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03002017 print ("previous import used depot path %s and now %s was specified. "
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002018 "This doesn't work!" % (' '.join (self.depotPaths),
2019 ' '.join (args)))
Simon Hausmannb9847332007-03-20 20:54:23 +01002020 sys.exit(1)
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002021
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002022 self.depotPaths = sorted(args)
Simon Hausmannb9847332007-03-20 20:54:23 +01002023
Simon Hausmann1c49fc12007-08-26 16:04:34 +02002024 revision = ""
Simon Hausmannb9847332007-03-20 20:54:23 +01002025 self.users = {}
Simon Hausmannb9847332007-03-20 20:54:23 +01002026
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002027 newPaths = []
2028 for p in self.depotPaths:
2029 if p.find("@") != -1:
2030 atIdx = p.index("@")
2031 self.changeRange = p[atIdx:]
2032 if self.changeRange == "@all":
2033 self.changeRange = ""
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03002034 elif ',' not in self.changeRange:
Simon Hausmann1c49fc12007-08-26 16:04:34 +02002035 revision = self.changeRange
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002036 self.changeRange = ""
Han-Wen Nienhuys7fcff9d2007-07-23 15:56:37 -07002037 p = p[:atIdx]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002038 elif p.find("#") != -1:
2039 hashIdx = p.index("#")
Simon Hausmann1c49fc12007-08-26 16:04:34 +02002040 revision = p[hashIdx:]
Han-Wen Nienhuys7fcff9d2007-07-23 15:56:37 -07002041 p = p[:hashIdx]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002042 elif self.previousDepotPaths == []:
Simon Hausmann1c49fc12007-08-26 16:04:34 +02002043 revision = "#head"
Simon Hausmannb9847332007-03-20 20:54:23 +01002044
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002045 p = re.sub ("\.\.\.$", "", p)
2046 if not p.endswith("/"):
2047 p += "/"
2048
2049 newPaths.append(p)
2050
2051 self.depotPaths = newPaths
2052
Simon Hausmannb9847332007-03-20 20:54:23 +01002053
Simon Hausmannb607e712007-05-20 10:55:54 +02002054 self.loadUserMapFromCache()
Simon Hausmanncb53e1f2007-04-08 00:12:02 +02002055 self.labels = {}
2056 if self.detectLabels:
2057 self.getLabels();
Simon Hausmannb9847332007-03-20 20:54:23 +01002058
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02002059 if self.detectBranches:
Simon Hausmanndf450922007-06-08 08:49:22 +02002060 ## FIXME - what's a P4 projectName ?
2061 self.projectName = self.guessProjectName()
2062
Simon Hausmann38f9f5e2007-11-15 10:38:45 +01002063 if self.hasOrigin:
2064 self.getBranchMappingFromGitBranches()
2065 else:
2066 self.getBranchMapping()
Simon Hausmann29bdbac2007-05-19 10:23:12 +02002067 if self.verbose:
2068 print "p4-git branches: %s" % self.p4BranchesInGit
2069 print "initial parents: %s" % self.initialParents
2070 for b in self.p4BranchesInGit:
2071 if b != "master":
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002072
2073 ## FIXME
Simon Hausmann29bdbac2007-05-19 10:23:12 +02002074 b = b[len(self.projectName):]
2075 self.createdBranches.add(b)
Simon Hausmann4b97ffb2007-05-18 21:45:23 +02002076
Simon Hausmannf291b4e2007-04-14 11:21:50 +02002077 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
Simon Hausmannb9847332007-03-20 20:54:23 +01002078
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03002079 importProcess = subprocess.Popen(["git", "fast-import"],
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002080 stdin=subprocess.PIPE, stdout=subprocess.PIPE,
2081 stderr=subprocess.PIPE);
Simon Hausmann08483582007-05-15 14:31:06 +02002082 self.gitOutput = importProcess.stdout
2083 self.gitStream = importProcess.stdin
2084 self.gitError = importProcess.stderr
Simon Hausmannb9847332007-03-20 20:54:23 +01002085
Simon Hausmann1c49fc12007-08-26 16:04:34 +02002086 if revision:
Simon Hausmannc208a242007-08-26 16:07:18 +02002087 self.importHeadRevision(revision)
Simon Hausmannb9847332007-03-20 20:54:23 +01002088 else:
2089 changes = []
2090
Simon Hausmann0828ab12007-03-20 20:59:30 +01002091 if len(self.changesFile) > 0:
Simon Hausmannb9847332007-03-20 20:54:23 +01002092 output = open(self.changesFile).readlines()
Reilly Grant1d7367d2009-09-10 00:02:38 -07002093 changeSet = set()
Simon Hausmannb9847332007-03-20 20:54:23 +01002094 for line in output:
2095 changeSet.add(int(line))
2096
2097 for change in changeSet:
2098 changes.append(change)
2099
2100 changes.sort()
2101 else:
Pete Wyckoffaccad8e2011-03-16 16:52:46 -04002102 # catch "git-p4 sync" with no new branches, in a repo that
2103 # does not have any existing git-p4 branches
2104 if len(args) == 0 and not self.p4BranchesInGit:
Pete Wyckoffe32e00d2011-02-19 08:17:59 -05002105 die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.");
Simon Hausmann29bdbac2007-05-19 10:23:12 +02002106 if self.verbose:
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03002107 print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002108 self.changeRange)
Simon Hausmann4f6432d2007-08-26 15:56:36 +02002109 changes = p4ChangesForPaths(self.depotPaths, self.changeRange)
Simon Hausmannb9847332007-03-20 20:54:23 +01002110
Simon Hausmann01a9c9c2007-05-23 00:07:35 +02002111 if len(self.maxChanges) > 0:
Han-Wen Nienhuys7fcff9d2007-07-23 15:56:37 -07002112 changes = changes[:min(int(self.maxChanges), len(changes))]
Simon Hausmann01a9c9c2007-05-23 00:07:35 +02002113
Simon Hausmannb9847332007-03-20 20:54:23 +01002114 if len(changes) == 0:
Simon Hausmann0828ab12007-03-20 20:59:30 +01002115 if not self.silent:
Simon Hausmann341dc1c2007-05-21 00:39:16 +02002116 print "No changes to import!"
Simon Hausmann1f52af62007-04-08 00:07:02 +02002117 return True
Simon Hausmannb9847332007-03-20 20:54:23 +01002118
Simon Hausmanna9d1a272007-06-11 23:28:03 +02002119 if not self.silent and not self.detectBranches:
2120 print "Import destination: %s" % self.branch
2121
Simon Hausmann341dc1c2007-05-21 00:39:16 +02002122 self.updatedBranches = set()
2123
Simon Hausmanne87f37a2007-08-26 16:00:52 +02002124 self.importChanges(changes)
Simon Hausmannb9847332007-03-20 20:54:23 +01002125
Simon Hausmann341dc1c2007-05-21 00:39:16 +02002126 if not self.silent:
2127 print ""
2128 if len(self.updatedBranches) > 0:
2129 sys.stdout.write("Updated branches: ")
2130 for b in self.updatedBranches:
2131 sys.stdout.write("%s " % b)
2132 sys.stdout.write("\n")
Simon Hausmannb9847332007-03-20 20:54:23 +01002133
Simon Hausmannb9847332007-03-20 20:54:23 +01002134 self.gitStream.close()
Simon Hausmann29bdbac2007-05-19 10:23:12 +02002135 if importProcess.wait() != 0:
2136 die("fast-import failed: %s" % self.gitError.read())
Simon Hausmannb9847332007-03-20 20:54:23 +01002137 self.gitOutput.close()
2138 self.gitError.close()
2139
Simon Hausmannb9847332007-03-20 20:54:23 +01002140 return True
2141
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02002142class P4Rebase(Command):
2143 def __init__(self):
2144 Command.__init__(self)
Simon Hausmann01265102007-05-25 10:36:10 +02002145 self.options = [ ]
Han-Wen Nienhuyscebdf5a2007-05-23 16:53:11 -03002146 self.description = ("Fetches the latest revision from perforce and "
2147 + "rebases the current work (branch) against it")
Simon Hausmann68c42152007-06-07 12:51:03 +02002148 self.verbose = False
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02002149
2150 def run(self, args):
2151 sync = P4Sync()
2152 sync.run([])
Simon Hausmannd7e38682007-06-12 14:34:46 +02002153
Simon Hausmann14594f42007-08-22 09:07:15 +02002154 return self.rebase()
2155
2156 def rebase(self):
Simon Hausmann36ee4ee2008-01-07 14:21:45 +01002157 if os.system("git update-index --refresh") != 0:
2158 die("Some files in your working directory are modified and different than what is in your index. You can use git update-index <filename> to bring the index up-to-date or stash away all your changes with git stash.");
2159 if len(read_pipe("git diff-index HEAD --")) > 0:
2160 die("You have uncommited changes. Please commit them before rebasing or stash them away with git stash.");
2161
Simon Hausmannd7e38682007-06-12 14:34:46 +02002162 [upstream, settings] = findUpstreamBranchPoint()
2163 if len(upstream) == 0:
2164 die("Cannot find upstream branchpoint for rebase")
2165
2166 # the branchpoint may be p4/foo~3, so strip off the parent
2167 upstream = re.sub("~[0-9]+$", "", upstream)
2168
2169 print "Rebasing the current branch onto %s" % upstream
Han-Wen Nienhuysb25b2062007-05-23 18:49:35 -03002170 oldHead = read_pipe("git rev-parse HEAD").strip()
Simon Hausmannd7e38682007-06-12 14:34:46 +02002171 system("git rebase %s" % upstream)
Simon Hausmann1f52af62007-04-08 00:07:02 +02002172 system("git diff-tree --stat --summary -M %s HEAD" % oldHead)
Simon Hausmann01ce1fe2007-04-07 23:46:50 +02002173 return True
2174
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002175class P4Clone(P4Sync):
2176 def __init__(self):
2177 P4Sync.__init__(self)
2178 self.description = "Creates a new git repository and imports from Perforce into it"
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002179 self.usage = "usage: %prog [options] //depot/path[@revRange]"
Tommy Thorn354081d2008-02-03 10:38:51 -08002180 self.options += [
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002181 optparse.make_option("--destination", dest="cloneDestination",
2182 action='store', default=None,
Tommy Thorn354081d2008-02-03 10:38:51 -08002183 help="where to leave result of the clone"),
2184 optparse.make_option("-/", dest="cloneExclude",
2185 action="append", type="string",
Pete Wyckoff38200072011-02-19 08:18:01 -05002186 help="exclude depot path"),
2187 optparse.make_option("--bare", dest="cloneBare",
2188 action="store_true", default=False),
Tommy Thorn354081d2008-02-03 10:38:51 -08002189 ]
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002190 self.cloneDestination = None
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002191 self.needsGit = False
Pete Wyckoff38200072011-02-19 08:18:01 -05002192 self.cloneBare = False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002193
Tommy Thorn354081d2008-02-03 10:38:51 -08002194 # This is required for the "append" cloneExclude action
2195 def ensure_value(self, attr, value):
2196 if not hasattr(self, attr) or getattr(self, attr) is None:
2197 setattr(self, attr, value)
2198 return getattr(self, attr)
2199
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03002200 def defaultDestination(self, args):
2201 ## TODO: use common prefix of args?
2202 depotPath = args[0]
2203 depotDir = re.sub("(@[^@]*)$", "", depotPath)
2204 depotDir = re.sub("(#[^#]*)$", "", depotDir)
Toby Allsopp053d9e42008-02-05 09:41:43 +13002205 depotDir = re.sub(r"\.\.\.$", "", depotDir)
Han-Wen Nienhuys6a49f8e2007-05-23 18:49:35 -03002206 depotDir = re.sub(r"/$", "", depotDir)
2207 return os.path.split(depotDir)[1]
2208
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002209 def run(self, args):
2210 if len(args) < 1:
2211 return False
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002212
2213 if self.keepRepoPath and not self.cloneDestination:
2214 sys.stderr.write("Must specify destination for --keep-path\n")
2215 sys.exit(1)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002216
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002217 depotPaths = args
Simon Hausmann5e100b52007-06-07 21:12:25 +02002218
2219 if not self.cloneDestination and len(depotPaths) > 1:
2220 self.cloneDestination = depotPaths[-1]
2221 depotPaths = depotPaths[:-1]
2222
Tommy Thorn354081d2008-02-03 10:38:51 -08002223 self.cloneExclude = ["/"+p for p in self.cloneExclude]
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002224 for p in depotPaths:
2225 if not p.startswith("//"):
2226 return False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002227
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002228 if not self.cloneDestination:
Marius Storm-Olsen98ad4fa2007-06-07 15:08:33 +02002229 self.cloneDestination = self.defaultDestination(args)
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002230
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03002231 print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination)
Pete Wyckoff38200072011-02-19 08:18:01 -05002232
Kevin Greenc3bf3f12007-06-11 16:48:07 -04002233 if not os.path.exists(self.cloneDestination):
2234 os.makedirs(self.cloneDestination)
Robert Blum053fd0c2008-08-01 12:50:03 -07002235 chdir(self.cloneDestination)
Pete Wyckoff38200072011-02-19 08:18:01 -05002236
2237 init_cmd = [ "git", "init" ]
2238 if self.cloneBare:
2239 init_cmd.append("--bare")
2240 subprocess.check_call(init_cmd)
2241
Han-Wen Nienhuys6326aa52007-05-23 18:49:35 -03002242 if not P4Sync.run(self, depotPaths):
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002243 return False
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002244 if self.branch != "master":
Tor Arvid Lunde9905012008-08-28 00:36:12 +02002245 if self.importIntoRemotes:
2246 masterbranch = "refs/remotes/p4/master"
2247 else:
2248 masterbranch = "refs/heads/p4/master"
2249 if gitBranchExists(masterbranch):
2250 system("git branch master %s" % masterbranch)
Pete Wyckoff38200072011-02-19 08:18:01 -05002251 if not self.cloneBare:
2252 system("git checkout -f")
Simon Hausmann8f9b2e02007-05-18 22:13:26 +02002253 else:
2254 print "Could not detect main branch. No checkout/master branch created."
Han-Wen Nienhuys86dff6b2007-05-23 18:49:35 -03002255
Simon Hausmannf9a3a4f2007-04-08 10:08:26 +02002256 return True
2257
Simon Hausmann09d89de2007-06-20 23:10:28 +02002258class P4Branches(Command):
2259 def __init__(self):
2260 Command.__init__(self)
2261 self.options = [ ]
2262 self.description = ("Shows the git branches that hold imports and their "
2263 + "corresponding perforce depot paths")
2264 self.verbose = False
2265
2266 def run(self, args):
Simon Hausmann5ca44612007-08-24 17:44:16 +02002267 if originP4BranchesExist():
2268 createOrUpdateBranchesFromOrigin()
2269
Simon Hausmann09d89de2007-06-20 23:10:28 +02002270 cmdline = "git rev-parse --symbolic "
2271 cmdline += " --remotes"
2272
2273 for line in read_pipe_lines(cmdline):
2274 line = line.strip()
2275
2276 if not line.startswith('p4/') or line == "p4/HEAD":
2277 continue
2278 branch = line
2279
2280 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
2281 settings = extractSettingsGitLog(log)
2282
2283 print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"])
2284 return True
2285
Simon Hausmannb9847332007-03-20 20:54:23 +01002286class HelpFormatter(optparse.IndentedHelpFormatter):
2287 def __init__(self):
2288 optparse.IndentedHelpFormatter.__init__(self)
2289
2290 def format_description(self, description):
2291 if description:
2292 return description + "\n"
2293 else:
2294 return ""
Simon Hausmann4f5cf762007-03-19 22:25:17 +01002295
Simon Hausmann86949ee2007-03-19 20:59:12 +01002296def printUsage(commands):
2297 print "usage: %s <command> [options]" % sys.argv[0]
2298 print ""
2299 print "valid commands: %s" % ", ".join(commands)
2300 print ""
2301 print "Try %s <command> --help for command specific help." % sys.argv[0]
2302 print ""
2303
2304commands = {
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002305 "debug" : P4Debug,
2306 "submit" : P4Submit,
Marius Storm-Olsena9834f52007-10-09 16:16:09 +02002307 "commit" : P4Submit,
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002308 "sync" : P4Sync,
2309 "rebase" : P4Rebase,
2310 "clone" : P4Clone,
Simon Hausmann09d89de2007-06-20 23:10:28 +02002311 "rollback" : P4RollBack,
2312 "branches" : P4Branches
Simon Hausmann86949ee2007-03-19 20:59:12 +01002313}
2314
Simon Hausmann86949ee2007-03-19 20:59:12 +01002315
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002316def main():
2317 if len(sys.argv[1:]) == 0:
2318 printUsage(commands.keys())
2319 sys.exit(2)
Simon Hausmann86949ee2007-03-19 20:59:12 +01002320
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002321 cmd = ""
2322 cmdName = sys.argv[1]
2323 try:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002324 klass = commands[cmdName]
2325 cmd = klass()
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002326 except KeyError:
2327 print "unknown command %s" % cmdName
2328 print ""
2329 printUsage(commands.keys())
2330 sys.exit(2)
Simon Hausmann4f5cf762007-03-19 22:25:17 +01002331
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002332 options = cmd.options
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002333 cmd.gitdir = os.environ.get("GIT_DIR", None)
Simon Hausmann86949ee2007-03-19 20:59:12 +01002334
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002335 args = sys.argv[2:]
Simon Hausmanne20a9e52007-03-26 00:13:51 +02002336
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002337 if len(options) > 0:
Pete Wyckoffef868902011-12-24 21:07:32 -05002338 if cmd.needsGit:
2339 options.append(optparse.make_option("--git-dir", dest="gitdir"))
Simon Hausmanne20a9e52007-03-26 00:13:51 +02002340
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002341 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
2342 options,
2343 description = cmd.description,
2344 formatter = HelpFormatter())
Simon Hausmann86949ee2007-03-19 20:59:12 +01002345
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002346 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
2347 global verbose
2348 verbose = cmd.verbose
2349 if cmd.needsGit:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002350 if cmd.gitdir == None:
2351 cmd.gitdir = os.path.abspath(".git")
2352 if not isValidGitDir(cmd.gitdir):
2353 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
2354 if os.path.exists(cmd.gitdir):
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002355 cdup = read_pipe("git rev-parse --show-cdup").strip()
2356 if len(cdup) > 0:
Robert Blum053fd0c2008-08-01 12:50:03 -07002357 chdir(cdup);
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002358
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002359 if not isValidGitDir(cmd.gitdir):
2360 if isValidGitDir(cmd.gitdir + "/.git"):
2361 cmd.gitdir += "/.git"
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002362 else:
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002363 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
Simon Hausmann8910ac02007-03-26 08:18:55 +02002364
Han-Wen Nienhuysb86f7372007-05-23 18:49:35 -03002365 os.environ["GIT_DIR"] = cmd.gitdir
Simon Hausmann4f5cf762007-03-19 22:25:17 +01002366
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002367 if not cmd.run(args):
2368 parser.print_help()
Simon Hausmann4f5cf762007-03-19 22:25:17 +01002369
Han-Wen Nienhuysbb6e09b2007-05-23 18:49:35 -03002370
2371if __name__ == '__main__':
2372 main()