]>
Commit | Line | Data |
---|---|---|
86949eef SH |
1 | #!/usr/bin/env python |
2 | # | |
3 | # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git. | |
4 | # | |
c8cbbee9 SH |
5 | # Author: Simon Hausmann <simon@lst.de> |
6 | # Copyright: 2007 Simon Hausmann <simon@lst.de> | |
83dce55a | 7 | # 2007 Trolltech ASA |
86949eef SH |
8 | # License: MIT <http://www.opensource.org/licenses/mit-license.php> |
9 | # | |
a33faf28 ER |
10 | import sys |
11 | if sys.hexversion < 0x02040000: | |
12 | # The limiter is the subprocess module | |
13 | sys.stderr.write("git-p4: requires Python 2.4 or later.\n") | |
14 | sys.exit(1) | |
f629fa59 PW |
15 | import os |
16 | import optparse | |
17 | import marshal | |
18 | import subprocess | |
19 | import tempfile | |
20 | import time | |
21 | import platform | |
22 | import re | |
23 | import shutil | |
d20f0f8e | 24 | import stat |
a5db4b12 LS |
25 | import zipfile |
26 | import zlib | |
4b07cd23 | 27 | import ctypes |
8b41a97f | 28 | |
a235e85c BC |
29 | try: |
30 | from subprocess import CalledProcessError | |
31 | except ImportError: | |
32 | # from python2.7:subprocess.py | |
33 | # Exception classes used by this module. | |
34 | class CalledProcessError(Exception): | |
35 | """This exception is raised when a process run by check_call() returns | |
36 | a non-zero exit status. The exit status will be stored in the | |
37 | returncode attribute.""" | |
38 | def __init__(self, returncode, cmd): | |
39 | self.returncode = returncode | |
40 | self.cmd = cmd | |
41 | def __str__(self): | |
42 | return "Command '%s' returned non-zero exit status %d" % (self.cmd, self.returncode) | |
43 | ||
4addad22 | 44 | verbose = False |
86949eef | 45 | |
06804c76 | 46 | # Only labels/tags matching this will be imported/exported |
c8942a22 | 47 | defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$' |
21a50753 | 48 | |
1051ef00 LD |
49 | # Grab changes in blocks of this many revisions, unless otherwise requested |
50 | defaultBlockSize = 512 | |
51 | ||
21a50753 AK |
52 | def p4_build_cmd(cmd): |
53 | """Build a suitable p4 command line. | |
54 | ||
55 | This consolidates building and returning a p4 command line into one | |
56 | location. It means that hooking into the environment, or other configuration | |
57 | can be done more easily. | |
58 | """ | |
6de040df | 59 | real_cmd = ["p4"] |
abcaf073 AK |
60 | |
61 | user = gitConfig("git-p4.user") | |
62 | if len(user) > 0: | |
6de040df | 63 | real_cmd += ["-u",user] |
abcaf073 AK |
64 | |
65 | password = gitConfig("git-p4.password") | |
66 | if len(password) > 0: | |
6de040df | 67 | real_cmd += ["-P", password] |
abcaf073 AK |
68 | |
69 | port = gitConfig("git-p4.port") | |
70 | if len(port) > 0: | |
6de040df | 71 | real_cmd += ["-p", port] |
abcaf073 AK |
72 | |
73 | host = gitConfig("git-p4.host") | |
74 | if len(host) > 0: | |
41799aa2 | 75 | real_cmd += ["-H", host] |
abcaf073 AK |
76 | |
77 | client = gitConfig("git-p4.client") | |
78 | if len(client) > 0: | |
6de040df | 79 | real_cmd += ["-c", client] |
abcaf073 | 80 | |
6de040df LD |
81 | |
82 | if isinstance(cmd,basestring): | |
83 | real_cmd = ' '.join(real_cmd) + ' ' + cmd | |
84 | else: | |
85 | real_cmd += cmd | |
21a50753 AK |
86 | return real_cmd |
87 | ||
bbd84863 MF |
88 | def chdir(path, is_client_path=False): |
89 | """Do chdir to the given path, and set the PWD environment | |
90 | variable for use by P4. It does not look at getcwd() output. | |
91 | Since we're not using the shell, it is necessary to set the | |
92 | PWD environment variable explicitly. | |
93 | ||
94 | Normally, expand the path to force it to be absolute. This | |
95 | addresses the use of relative path names inside P4 settings, | |
96 | e.g. P4CONFIG=.p4config. P4 does not simply open the filename | |
97 | as given; it looks for .p4config using PWD. | |
98 | ||
99 | If is_client_path, the path was handed to us directly by p4, | |
100 | and may be a symbolic link. Do not call os.getcwd() in this | |
101 | case, because it will cause p4 to think that PWD is not inside | |
102 | the client path. | |
103 | """ | |
104 | ||
105 | os.chdir(path) | |
106 | if not is_client_path: | |
107 | path = os.getcwd() | |
108 | os.environ['PWD'] = path | |
053fd0c1 | 109 | |
4d25dc44 LS |
110 | def calcDiskFree(): |
111 | """Return free space in bytes on the disk of the given dirname.""" | |
112 | if platform.system() == 'Windows': | |
113 | free_bytes = ctypes.c_ulonglong(0) | |
114 | ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()), None, None, ctypes.pointer(free_bytes)) | |
115 | return free_bytes.value | |
116 | else: | |
117 | st = os.statvfs(os.getcwd()) | |
118 | return st.f_bavail * st.f_frsize | |
119 | ||
86dff6b6 HWN |
120 | def die(msg): |
121 | if verbose: | |
122 | raise Exception(msg) | |
123 | else: | |
124 | sys.stderr.write(msg + "\n") | |
125 | sys.exit(1) | |
126 | ||
6de040df | 127 | def write_pipe(c, stdin): |
4addad22 | 128 | if verbose: |
6de040df | 129 | sys.stderr.write('Writing pipe: %s\n' % str(c)) |
b016d397 | 130 | |
6de040df LD |
131 | expand = isinstance(c,basestring) |
132 | p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand) | |
133 | pipe = p.stdin | |
134 | val = pipe.write(stdin) | |
135 | pipe.close() | |
136 | if p.wait(): | |
137 | die('Command failed: %s' % str(c)) | |
b016d397 HWN |
138 | |
139 | return val | |
140 | ||
6de040df | 141 | def p4_write_pipe(c, stdin): |
d9429194 | 142 | real_cmd = p4_build_cmd(c) |
6de040df | 143 | return write_pipe(real_cmd, stdin) |
d9429194 | 144 | |
4addad22 HWN |
145 | def read_pipe(c, ignore_error=False): |
146 | if verbose: | |
6de040df | 147 | sys.stderr.write('Reading pipe: %s\n' % str(c)) |
8b41a97f | 148 | |
6de040df | 149 | expand = isinstance(c,basestring) |
1f5f3907 LS |
150 | p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand) |
151 | (out, err) = p.communicate() | |
152 | if p.returncode != 0 and not ignore_error: | |
153 | die('Command failed: %s\nError: %s' % (str(c), err)) | |
154 | return out | |
b016d397 | 155 | |
d9429194 AK |
156 | def p4_read_pipe(c, ignore_error=False): |
157 | real_cmd = p4_build_cmd(c) | |
158 | return read_pipe(real_cmd, ignore_error) | |
b016d397 | 159 | |
bce4c5fc | 160 | def read_pipe_lines(c): |
4addad22 | 161 | if verbose: |
6de040df LD |
162 | sys.stderr.write('Reading pipe: %s\n' % str(c)) |
163 | ||
164 | expand = isinstance(c, basestring) | |
165 | p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand) | |
166 | pipe = p.stdout | |
b016d397 | 167 | val = pipe.readlines() |
6de040df LD |
168 | if pipe.close() or p.wait(): |
169 | die('Command failed: %s' % str(c)) | |
b016d397 HWN |
170 | |
171 | return val | |
caace111 | 172 | |
2318121b AK |
173 | def p4_read_pipe_lines(c): |
174 | """Specifically invoke p4 on the command supplied. """ | |
155af834 | 175 | real_cmd = p4_build_cmd(c) |
2318121b AK |
176 | return read_pipe_lines(real_cmd) |
177 | ||
8e9497c2 GG |
178 | def p4_has_command(cmd): |
179 | """Ask p4 for help on this command. If it returns an error, the | |
180 | command does not exist in this version of p4.""" | |
181 | real_cmd = p4_build_cmd(["help", cmd]) | |
182 | p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE, | |
183 | stderr=subprocess.PIPE) | |
184 | p.communicate() | |
185 | return p.returncode == 0 | |
186 | ||
249da4c0 PW |
187 | def p4_has_move_command(): |
188 | """See if the move command exists, that it supports -k, and that | |
189 | it has not been administratively disabled. The arguments | |
190 | must be correct, but the filenames do not have to exist. Use | |
191 | ones with wildcards so even if they exist, it will fail.""" | |
192 | ||
193 | if not p4_has_command("move"): | |
194 | return False | |
195 | cmd = p4_build_cmd(["move", "-k", "@from", "@to"]) | |
196 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
197 | (out, err) = p.communicate() | |
198 | # return code will be 1 in either case | |
199 | if err.find("Invalid option") >= 0: | |
200 | return False | |
201 | if err.find("disabled") >= 0: | |
202 | return False | |
203 | # assume it failed because @... was invalid changelist | |
204 | return True | |
205 | ||
cbff4b25 | 206 | def system(cmd, ignore_error=False): |
6de040df | 207 | expand = isinstance(cmd,basestring) |
4addad22 | 208 | if verbose: |
6de040df | 209 | sys.stderr.write("executing %s\n" % str(cmd)) |
a235e85c | 210 | retcode = subprocess.call(cmd, shell=expand) |
cbff4b25 | 211 | if retcode and not ignore_error: |
a235e85c | 212 | raise CalledProcessError(retcode, cmd) |
6754a299 | 213 | |
cbff4b25 LD |
214 | return retcode |
215 | ||
bf9320f1 AK |
216 | def p4_system(cmd): |
217 | """Specifically invoke p4 as the system command. """ | |
155af834 | 218 | real_cmd = p4_build_cmd(cmd) |
6de040df | 219 | expand = isinstance(real_cmd, basestring) |
a235e85c BC |
220 | retcode = subprocess.call(real_cmd, shell=expand) |
221 | if retcode: | |
222 | raise CalledProcessError(retcode, real_cmd) | |
6de040df | 223 | |
7f0e5962 PW |
224 | _p4_version_string = None |
225 | def p4_version_string(): | |
226 | """Read the version string, showing just the last line, which | |
227 | hopefully is the interesting version bit. | |
228 | ||
229 | $ p4 -V | |
230 | Perforce - The Fast Software Configuration Management System. | |
231 | Copyright 1995-2011 Perforce Software. All rights reserved. | |
232 | Rev. P4/NTX86/2011.1/393975 (2011/12/16). | |
233 | """ | |
234 | global _p4_version_string | |
235 | if not _p4_version_string: | |
236 | a = p4_read_pipe_lines(["-V"]) | |
237 | _p4_version_string = a[-1].rstrip() | |
238 | return _p4_version_string | |
239 | ||
6de040df | 240 | def p4_integrate(src, dest): |
9d7d446a | 241 | p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)]) |
6de040df | 242 | |
8d7ec362 | 243 | def p4_sync(f, *options): |
9d7d446a | 244 | p4_system(["sync"] + list(options) + [wildcard_encode(f)]) |
6de040df LD |
245 | |
246 | def p4_add(f): | |
9d7d446a PW |
247 | # forcibly add file names with wildcards |
248 | if wildcard_present(f): | |
249 | p4_system(["add", "-f", f]) | |
250 | else: | |
251 | p4_system(["add", f]) | |
6de040df LD |
252 | |
253 | def p4_delete(f): | |
9d7d446a | 254 | p4_system(["delete", wildcard_encode(f)]) |
6de040df | 255 | |
a02b8bc4 RP |
256 | def p4_edit(f, *options): |
257 | p4_system(["edit"] + list(options) + [wildcard_encode(f)]) | |
6de040df LD |
258 | |
259 | def p4_revert(f): | |
9d7d446a | 260 | p4_system(["revert", wildcard_encode(f)]) |
6de040df | 261 | |
9d7d446a PW |
262 | def p4_reopen(type, f): |
263 | p4_system(["reopen", "-t", type, wildcard_encode(f)]) | |
bf9320f1 | 264 | |
8e9497c2 GG |
265 | def p4_move(src, dest): |
266 | p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)]) | |
267 | ||
1051ef00 LD |
268 | def p4_last_change(): |
269 | results = p4CmdList(["changes", "-m", "1"]) | |
270 | return int(results[0]['change']) | |
271 | ||
18fa13d0 PW |
272 | def p4_describe(change): |
273 | """Make sure it returns a valid result by checking for | |
274 | the presence of field "time". Return a dict of the | |
275 | results.""" | |
276 | ||
277 | ds = p4CmdList(["describe", "-s", str(change)]) | |
278 | if len(ds) != 1: | |
279 | die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds))) | |
280 | ||
281 | d = ds[0] | |
282 | ||
283 | if "p4ExitCode" in d: | |
284 | die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"], | |
285 | str(d))) | |
286 | if "code" in d: | |
287 | if d["code"] == "error": | |
288 | die("p4 describe -s %d returned error code: %s" % (change, str(d))) | |
289 | ||
290 | if "time" not in d: | |
291 | die("p4 describe -s %d returned no \"time\": %s" % (change, str(d))) | |
292 | ||
293 | return d | |
294 | ||
9cffb8c8 PW |
295 | # |
296 | # Canonicalize the p4 type and return a tuple of the | |
297 | # base type, plus any modifiers. See "p4 help filetypes" | |
298 | # for a list and explanation. | |
299 | # | |
300 | def split_p4_type(p4type): | |
301 | ||
302 | p4_filetypes_historical = { | |
303 | "ctempobj": "binary+Sw", | |
304 | "ctext": "text+C", | |
305 | "cxtext": "text+Cx", | |
306 | "ktext": "text+k", | |
307 | "kxtext": "text+kx", | |
308 | "ltext": "text+F", | |
309 | "tempobj": "binary+FSw", | |
310 | "ubinary": "binary+F", | |
311 | "uresource": "resource+F", | |
312 | "uxbinary": "binary+Fx", | |
313 | "xbinary": "binary+x", | |
314 | "xltext": "text+Fx", | |
315 | "xtempobj": "binary+Swx", | |
316 | "xtext": "text+x", | |
317 | "xunicode": "unicode+x", | |
318 | "xutf16": "utf16+x", | |
319 | } | |
320 | if p4type in p4_filetypes_historical: | |
321 | p4type = p4_filetypes_historical[p4type] | |
322 | mods = "" | |
323 | s = p4type.split("+") | |
324 | base = s[0] | |
325 | mods = "" | |
326 | if len(s) > 1: | |
327 | mods = s[1] | |
328 | return (base, mods) | |
b9fc6ea9 | 329 | |
60df071c LD |
330 | # |
331 | # return the raw p4 type of a file (text, text+ko, etc) | |
332 | # | |
79467e61 PW |
333 | def p4_type(f): |
334 | results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)]) | |
60df071c LD |
335 | return results[0]['headType'] |
336 | ||
337 | # | |
338 | # Given a type base and modifier, return a regexp matching | |
339 | # the keywords that can be expanded in the file | |
340 | # | |
341 | def p4_keywords_regexp_for_type(base, type_mods): | |
342 | if base in ("text", "unicode", "binary"): | |
343 | kwords = None | |
344 | if "ko" in type_mods: | |
345 | kwords = 'Id|Header' | |
346 | elif "k" in type_mods: | |
347 | kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision' | |
348 | else: | |
349 | return None | |
350 | pattern = r""" | |
351 | \$ # Starts with a dollar, followed by... | |
352 | (%s) # one of the keywords, followed by... | |
6b2bf41e | 353 | (:[^$\n]+)? # possibly an old expansion, followed by... |
60df071c LD |
354 | \$ # another dollar |
355 | """ % kwords | |
356 | return pattern | |
357 | else: | |
358 | return None | |
359 | ||
360 | # | |
361 | # Given a file, return a regexp matching the possible | |
362 | # RCS keywords that will be expanded, or None for files | |
363 | # with kw expansion turned off. | |
364 | # | |
365 | def p4_keywords_regexp_for_file(file): | |
366 | if not os.path.exists(file): | |
367 | return None | |
368 | else: | |
369 | (type_base, type_mods) = split_p4_type(p4_type(file)) | |
370 | return p4_keywords_regexp_for_type(type_base, type_mods) | |
b9fc6ea9 | 371 | |
c65b670e CP |
372 | def setP4ExecBit(file, mode): |
373 | # Reopens an already open file and changes the execute bit to match | |
374 | # the execute bit setting in the passed in mode. | |
375 | ||
376 | p4Type = "+x" | |
377 | ||
378 | if not isModeExec(mode): | |
379 | p4Type = getP4OpenedType(file) | |
380 | p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type) | |
381 | p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type) | |
382 | if p4Type[-1] == "+": | |
383 | p4Type = p4Type[0:-1] | |
384 | ||
6de040df | 385 | p4_reopen(p4Type, file) |
c65b670e CP |
386 | |
387 | def getP4OpenedType(file): | |
388 | # Returns the perforce file type for the given file. | |
389 | ||
9d7d446a | 390 | result = p4_read_pipe(["opened", wildcard_encode(file)]) |
34a0dbfc | 391 | match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result) |
c65b670e CP |
392 | if match: |
393 | return match.group(1) | |
394 | else: | |
f3e5ae4f | 395 | die("Could not determine file type for %s (result: '%s')" % (file, result)) |
c65b670e | 396 | |
06804c76 LD |
397 | # Return the set of all p4 labels |
398 | def getP4Labels(depotPaths): | |
399 | labels = set() | |
400 | if isinstance(depotPaths,basestring): | |
401 | depotPaths = [depotPaths] | |
402 | ||
403 | for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]): | |
404 | label = l['label'] | |
405 | labels.add(label) | |
406 | ||
407 | return labels | |
408 | ||
409 | # Return the set of all git tags | |
410 | def getGitTags(): | |
411 | gitTags = set() | |
412 | for line in read_pipe_lines(["git", "tag"]): | |
413 | tag = line.strip() | |
414 | gitTags.add(tag) | |
415 | return gitTags | |
416 | ||
b43b0a3c CP |
417 | def diffTreePattern(): |
418 | # This is a simple generator for the diff tree regex pattern. This could be | |
419 | # a class variable if this and parseDiffTreeEntry were a part of a class. | |
420 | pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)') | |
421 | while True: | |
422 | yield pattern | |
423 | ||
424 | def parseDiffTreeEntry(entry): | |
425 | """Parses a single diff tree entry into its component elements. | |
426 | ||
427 | See git-diff-tree(1) manpage for details about the format of the diff | |
428 | output. This method returns a dictionary with the following elements: | |
429 | ||
430 | src_mode - The mode of the source file | |
431 | dst_mode - The mode of the destination file | |
432 | src_sha1 - The sha1 for the source file | |
433 | dst_sha1 - The sha1 fr the destination file | |
434 | status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc) | |
435 | status_score - The score for the status (applicable for 'C' and 'R' | |
436 | statuses). This is None if there is no score. | |
437 | src - The path for the source file. | |
438 | dst - The path for the destination file. This is only present for | |
439 | copy or renames. If it is not present, this is None. | |
440 | ||
441 | If the pattern is not matched, None is returned.""" | |
442 | ||
443 | match = diffTreePattern().next().match(entry) | |
444 | if match: | |
445 | return { | |
446 | 'src_mode': match.group(1), | |
447 | 'dst_mode': match.group(2), | |
448 | 'src_sha1': match.group(3), | |
449 | 'dst_sha1': match.group(4), | |
450 | 'status': match.group(5), | |
451 | 'status_score': match.group(6), | |
452 | 'src': match.group(7), | |
453 | 'dst': match.group(10) | |
454 | } | |
455 | return None | |
456 | ||
c65b670e CP |
457 | def isModeExec(mode): |
458 | # Returns True if the given git mode represents an executable file, | |
459 | # otherwise False. | |
460 | return mode[-3:] == "755" | |
461 | ||
462 | def isModeExecChanged(src_mode, dst_mode): | |
463 | return isModeExec(src_mode) != isModeExec(dst_mode) | |
464 | ||
b932705b | 465 | def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None): |
6de040df LD |
466 | |
467 | if isinstance(cmd,basestring): | |
468 | cmd = "-G " + cmd | |
469 | expand = True | |
470 | else: | |
471 | cmd = ["-G"] + cmd | |
472 | expand = False | |
473 | ||
474 | cmd = p4_build_cmd(cmd) | |
6a49f8e2 | 475 | if verbose: |
6de040df | 476 | sys.stderr.write("Opening pipe: %s\n" % str(cmd)) |
9f90c733 SL |
477 | |
478 | # Use a temporary file to avoid deadlocks without | |
479 | # subprocess.communicate(), which would put another copy | |
480 | # of stdout into memory. | |
481 | stdin_file = None | |
482 | if stdin is not None: | |
483 | stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode) | |
6de040df LD |
484 | if isinstance(stdin,basestring): |
485 | stdin_file.write(stdin) | |
486 | else: | |
487 | for i in stdin: | |
488 | stdin_file.write(i + '\n') | |
9f90c733 SL |
489 | stdin_file.flush() |
490 | stdin_file.seek(0) | |
491 | ||
6de040df LD |
492 | p4 = subprocess.Popen(cmd, |
493 | shell=expand, | |
9f90c733 SL |
494 | stdin=stdin_file, |
495 | stdout=subprocess.PIPE) | |
86949eef SH |
496 | |
497 | result = [] | |
498 | try: | |
499 | while True: | |
9f90c733 | 500 | entry = marshal.load(p4.stdout) |
c3f6163b AG |
501 | if cb is not None: |
502 | cb(entry) | |
503 | else: | |
504 | result.append(entry) | |
86949eef SH |
505 | except EOFError: |
506 | pass | |
9f90c733 SL |
507 | exitCode = p4.wait() |
508 | if exitCode != 0: | |
ac3e0d79 SH |
509 | entry = {} |
510 | entry["p4ExitCode"] = exitCode | |
511 | result.append(entry) | |
86949eef SH |
512 | |
513 | return result | |
514 | ||
515 | def p4Cmd(cmd): | |
516 | list = p4CmdList(cmd) | |
517 | result = {} | |
518 | for entry in list: | |
519 | result.update(entry) | |
520 | return result; | |
521 | ||
cb2c9db5 SH |
522 | def p4Where(depotPath): |
523 | if not depotPath.endswith("/"): | |
524 | depotPath += "/" | |
cd884106 VA |
525 | depotPathLong = depotPath + "..." |
526 | outputList = p4CmdList(["where", depotPathLong]) | |
7f705dc3 TAL |
527 | output = None |
528 | for entry in outputList: | |
75bc9573 | 529 | if "depotFile" in entry: |
cd884106 VA |
530 | # Search for the base client side depot path, as long as it starts with the branch's P4 path. |
531 | # The base path always ends with "/...". | |
532 | if entry["depotFile"].find(depotPath) == 0 and entry["depotFile"][-4:] == "/...": | |
75bc9573 TAL |
533 | output = entry |
534 | break | |
535 | elif "data" in entry: | |
536 | data = entry.get("data") | |
537 | space = data.find(" ") | |
538 | if data[:space] == depotPath: | |
539 | output = entry | |
540 | break | |
7f705dc3 TAL |
541 | if output == None: |
542 | return "" | |
dc524036 SH |
543 | if output["code"] == "error": |
544 | return "" | |
cb2c9db5 SH |
545 | clientPath = "" |
546 | if "path" in output: | |
547 | clientPath = output.get("path") | |
548 | elif "data" in output: | |
549 | data = output.get("data") | |
550 | lastSpace = data.rfind(" ") | |
551 | clientPath = data[lastSpace + 1:] | |
552 | ||
553 | if clientPath.endswith("..."): | |
554 | clientPath = clientPath[:-3] | |
555 | return clientPath | |
556 | ||
86949eef | 557 | def currentGitBranch(): |
00ad6e31 LD |
558 | retcode = system(["git", "symbolic-ref", "-q", "HEAD"], ignore_error=True) |
559 | if retcode != 0: | |
560 | # on a detached head | |
561 | return None | |
562 | else: | |
563 | return read_pipe(["git", "name-rev", "HEAD"]).split(" ")[1].strip() | |
86949eef | 564 | |
4f5cf76a | 565 | def isValidGitDir(path): |
bb6e09b2 HWN |
566 | if (os.path.exists(path + "/HEAD") |
567 | and os.path.exists(path + "/refs") and os.path.exists(path + "/objects")): | |
4f5cf76a SH |
568 | return True; |
569 | return False | |
570 | ||
463e8af6 | 571 | def parseRevision(ref): |
b25b2065 | 572 | return read_pipe("git rev-parse %s" % ref).strip() |
463e8af6 | 573 | |
28755dba PW |
574 | def branchExists(ref): |
575 | rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref], | |
576 | ignore_error=True) | |
577 | return len(rev) > 0 | |
578 | ||
6ae8de88 SH |
579 | def extractLogMessageFromGitCommit(commit): |
580 | logMessage = "" | |
b016d397 HWN |
581 | |
582 | ## fixme: title is first line of commit, not 1st paragraph. | |
6ae8de88 | 583 | foundTitle = False |
b016d397 | 584 | for log in read_pipe_lines("git cat-file commit %s" % commit): |
6ae8de88 SH |
585 | if not foundTitle: |
586 | if len(log) == 1: | |
1c094184 | 587 | foundTitle = True |
6ae8de88 SH |
588 | continue |
589 | ||
590 | logMessage += log | |
591 | return logMessage | |
592 | ||
bb6e09b2 | 593 | def extractSettingsGitLog(log): |
6ae8de88 SH |
594 | values = {} |
595 | for line in log.split("\n"): | |
596 | line = line.strip() | |
6326aa58 HWN |
597 | m = re.search (r"^ *\[git-p4: (.*)\]$", line) |
598 | if not m: | |
599 | continue | |
600 | ||
601 | assignments = m.group(1).split (':') | |
602 | for a in assignments: | |
603 | vals = a.split ('=') | |
604 | key = vals[0].strip() | |
605 | val = ('='.join (vals[1:])).strip() | |
606 | if val.endswith ('\"') and val.startswith('"'): | |
607 | val = val[1:-1] | |
608 | ||
609 | values[key] = val | |
610 | ||
845b42cb SH |
611 | paths = values.get("depot-paths") |
612 | if not paths: | |
613 | paths = values.get("depot-path") | |
a3fdd579 SH |
614 | if paths: |
615 | values['depot-paths'] = paths.split(',') | |
bb6e09b2 | 616 | return values |
6ae8de88 | 617 | |
8136a639 | 618 | def gitBranchExists(branch): |
bb6e09b2 HWN |
619 | proc = subprocess.Popen(["git", "rev-parse", branch], |
620 | stderr=subprocess.PIPE, stdout=subprocess.PIPE); | |
caace111 | 621 | return proc.wait() == 0; |
8136a639 | 622 | |
36bd8446 | 623 | _gitConfig = {} |
b345d6c3 | 624 | |
692e1796 | 625 | def gitConfig(key, typeSpecifier=None): |
36bd8446 | 626 | if not _gitConfig.has_key(key): |
692e1796 LS |
627 | cmd = [ "git", "config" ] |
628 | if typeSpecifier: | |
629 | cmd += [ typeSpecifier ] | |
630 | cmd += [ key ] | |
b345d6c3 PW |
631 | s = read_pipe(cmd, ignore_error=True) |
632 | _gitConfig[key] = s.strip() | |
36bd8446 | 633 | return _gitConfig[key] |
01265103 | 634 | |
0d609032 PW |
635 | def gitConfigBool(key): |
636 | """Return a bool, using git config --bool. It is True only if the | |
637 | variable is set to true, and False if set to false or not present | |
638 | in the config.""" | |
639 | ||
36bd8446 | 640 | if not _gitConfig.has_key(key): |
692e1796 | 641 | _gitConfig[key] = gitConfig(key, '--bool') == "true" |
36bd8446 | 642 | return _gitConfig[key] |
01265103 | 643 | |
cb1dafdf LS |
644 | def gitConfigInt(key): |
645 | if not _gitConfig.has_key(key): | |
646 | cmd = [ "git", "config", "--int", key ] | |
0d609032 PW |
647 | s = read_pipe(cmd, ignore_error=True) |
648 | v = s.strip() | |
cb1dafdf LS |
649 | try: |
650 | _gitConfig[key] = int(gitConfig(key, '--int')) | |
651 | except ValueError: | |
652 | _gitConfig[key] = None | |
36bd8446 | 653 | return _gitConfig[key] |
01265103 | 654 | |
7199cf13 VA |
655 | def gitConfigList(key): |
656 | if not _gitConfig.has_key(key): | |
2abba301 PW |
657 | s = read_pipe(["git", "config", "--get-all", key], ignore_error=True) |
658 | _gitConfig[key] = s.strip().split(os.linesep) | |
7960e707 LS |
659 | if _gitConfig[key] == ['']: |
660 | _gitConfig[key] = [] | |
7199cf13 VA |
661 | return _gitConfig[key] |
662 | ||
2c8037ed PW |
663 | def p4BranchesInGit(branchesAreInRemotes=True): |
664 | """Find all the branches whose names start with "p4/", looking | |
665 | in remotes or heads as specified by the argument. Return | |
666 | a dictionary of { branch: revision } for each one found. | |
667 | The branch names are the short names, without any | |
668 | "p4/" prefix.""" | |
669 | ||
062410bb SH |
670 | branches = {} |
671 | ||
672 | cmdline = "git rev-parse --symbolic " | |
673 | if branchesAreInRemotes: | |
2c8037ed | 674 | cmdline += "--remotes" |
062410bb | 675 | else: |
2c8037ed | 676 | cmdline += "--branches" |
062410bb SH |
677 | |
678 | for line in read_pipe_lines(cmdline): | |
679 | line = line.strip() | |
680 | ||
2c8037ed PW |
681 | # only import to p4/ |
682 | if not line.startswith('p4/'): | |
683 | continue | |
684 | # special symbolic ref to p4/master | |
685 | if line == "p4/HEAD": | |
062410bb | 686 | continue |
062410bb | 687 | |
2c8037ed PW |
688 | # strip off p4/ prefix |
689 | branch = line[len("p4/"):] | |
062410bb SH |
690 | |
691 | branches[branch] = parseRevision(line) | |
2c8037ed | 692 | |
062410bb SH |
693 | return branches |
694 | ||
5a8e84cd PW |
695 | def branch_exists(branch): |
696 | """Make sure that the given ref name really exists.""" | |
697 | ||
698 | cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ] | |
699 | p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) | |
700 | out, _ = p.communicate() | |
701 | if p.returncode: | |
702 | return False | |
703 | # expect exactly one line of output: the branch name | |
704 | return out.rstrip() == branch | |
705 | ||
9ceab363 | 706 | def findUpstreamBranchPoint(head = "HEAD"): |
86506fe5 SH |
707 | branches = p4BranchesInGit() |
708 | # map from depot-path to branch name | |
709 | branchByDepotPath = {} | |
710 | for branch in branches.keys(): | |
711 | tip = branches[branch] | |
712 | log = extractLogMessageFromGitCommit(tip) | |
713 | settings = extractSettingsGitLog(log) | |
714 | if settings.has_key("depot-paths"): | |
715 | paths = ",".join(settings["depot-paths"]) | |
716 | branchByDepotPath[paths] = "remotes/p4/" + branch | |
717 | ||
27d2d811 | 718 | settings = None |
27d2d811 SH |
719 | parent = 0 |
720 | while parent < 65535: | |
9ceab363 | 721 | commit = head + "~%s" % parent |
27d2d811 SH |
722 | log = extractLogMessageFromGitCommit(commit) |
723 | settings = extractSettingsGitLog(log) | |
86506fe5 SH |
724 | if settings.has_key("depot-paths"): |
725 | paths = ",".join(settings["depot-paths"]) | |
726 | if branchByDepotPath.has_key(paths): | |
727 | return [branchByDepotPath[paths], settings] | |
27d2d811 | 728 | |
86506fe5 | 729 | parent = parent + 1 |
27d2d811 | 730 | |
86506fe5 | 731 | return ["", settings] |
27d2d811 | 732 | |
5ca44617 SH |
733 | def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True): |
734 | if not silent: | |
735 | print ("Creating/updating branch(es) in %s based on origin branch(es)" | |
736 | % localRefPrefix) | |
737 | ||
738 | originPrefix = "origin/p4/" | |
739 | ||
740 | for line in read_pipe_lines("git rev-parse --symbolic --remotes"): | |
741 | line = line.strip() | |
742 | if (not line.startswith(originPrefix)) or line.endswith("HEAD"): | |
743 | continue | |
744 | ||
745 | headName = line[len(originPrefix):] | |
746 | remoteHead = localRefPrefix + headName | |
747 | originHead = line | |
748 | ||
749 | original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead)) | |
750 | if (not original.has_key('depot-paths') | |
751 | or not original.has_key('change')): | |
752 | continue | |
753 | ||
754 | update = False | |
755 | if not gitBranchExists(remoteHead): | |
756 | if verbose: | |
757 | print "creating %s" % remoteHead | |
758 | update = True | |
759 | else: | |
760 | settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead)) | |
761 | if settings.has_key('change') > 0: | |
762 | if settings['depot-paths'] == original['depot-paths']: | |
763 | originP4Change = int(original['change']) | |
764 | p4Change = int(settings['change']) | |
765 | if originP4Change > p4Change: | |
766 | print ("%s (%s) is newer than %s (%s). " | |
767 | "Updating p4 branch from origin." | |
768 | % (originHead, originP4Change, | |
769 | remoteHead, p4Change)) | |
770 | update = True | |
771 | else: | |
772 | print ("Ignoring: %s was imported from %s while " | |
773 | "%s was imported from %s" | |
774 | % (originHead, ','.join(original['depot-paths']), | |
775 | remoteHead, ','.join(settings['depot-paths']))) | |
776 | ||
777 | if update: | |
778 | system("git update-ref %s %s" % (remoteHead, originHead)) | |
779 | ||
780 | def originP4BranchesExist(): | |
781 | return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master") | |
782 | ||
1051ef00 LD |
783 | |
784 | def p4ParseNumericChangeRange(parts): | |
785 | changeStart = int(parts[0][1:]) | |
786 | if parts[1] == '#head': | |
787 | changeEnd = p4_last_change() | |
788 | else: | |
789 | changeEnd = int(parts[1]) | |
790 | ||
791 | return (changeStart, changeEnd) | |
792 | ||
793 | def chooseBlockSize(blockSize): | |
794 | if blockSize: | |
795 | return blockSize | |
796 | else: | |
797 | return defaultBlockSize | |
798 | ||
799 | def p4ChangesForPaths(depotPaths, changeRange, requestedBlockSize): | |
4f6432d8 | 800 | assert depotPaths |
96b2d54a | 801 | |
1051ef00 LD |
802 | # Parse the change range into start and end. Try to find integer |
803 | # revision ranges as these can be broken up into blocks to avoid | |
804 | # hitting server-side limits (maxrows, maxscanresults). But if | |
805 | # that doesn't work, fall back to using the raw revision specifier | |
806 | # strings, without using block mode. | |
807 | ||
96b2d54a | 808 | if changeRange is None or changeRange == '': |
1051ef00 LD |
809 | changeStart = 1 |
810 | changeEnd = p4_last_change() | |
811 | block_size = chooseBlockSize(requestedBlockSize) | |
96b2d54a LS |
812 | else: |
813 | parts = changeRange.split(',') | |
814 | assert len(parts) == 2 | |
1051ef00 LD |
815 | try: |
816 | (changeStart, changeEnd) = p4ParseNumericChangeRange(parts) | |
817 | block_size = chooseBlockSize(requestedBlockSize) | |
818 | except: | |
819 | changeStart = parts[0][1:] | |
820 | changeEnd = parts[1] | |
821 | if requestedBlockSize: | |
822 | die("cannot use --changes-block-size with non-numeric revisions") | |
823 | block_size = None | |
4f6432d8 | 824 | |
1f90a648 | 825 | changes = [] |
96b2d54a | 826 | |
1f90a648 SH |
827 | # Retrieve changes a block at a time, to prevent running |
828 | # into a MaxResults/MaxScanRows error from the server. | |
1051ef00 | 829 | |
1f90a648 SH |
830 | while True: |
831 | cmd = ['changes'] | |
1051ef00 | 832 | |
1f90a648 SH |
833 | if block_size: |
834 | end = min(changeEnd, changeStart + block_size) | |
835 | revisionRange = "%d,%d" % (changeStart, end) | |
836 | else: | |
837 | revisionRange = "%s,%s" % (changeStart, changeEnd) | |
1051ef00 | 838 | |
1f90a648 | 839 | for p in depotPaths: |
1051ef00 LD |
840 | cmd += ["%s...@%s" % (p, revisionRange)] |
841 | ||
1f90a648 SH |
842 | # Insert changes in chronological order |
843 | for line in reversed(p4_read_pipe_lines(cmd)): | |
844 | changes.append(int(line.split(" ")[1])) | |
1051ef00 | 845 | |
1f90a648 SH |
846 | if not block_size: |
847 | break | |
1051ef00 | 848 | |
1f90a648 SH |
849 | if end >= changeEnd: |
850 | break | |
1051ef00 | 851 | |
1f90a648 | 852 | changeStart = end + 1 |
4f6432d8 | 853 | |
1f90a648 SH |
854 | changes = sorted(changes) |
855 | return changes | |
4f6432d8 | 856 | |
d53de8b9 TAL |
857 | def p4PathStartsWith(path, prefix): |
858 | # This method tries to remedy a potential mixed-case issue: | |
859 | # | |
860 | # If UserA adds //depot/DirA/file1 | |
861 | # and UserB adds //depot/dira/file2 | |
862 | # | |
863 | # we may or may not have a problem. If you have core.ignorecase=true, | |
864 | # we treat DirA and dira as the same directory | |
0d609032 | 865 | if gitConfigBool("core.ignorecase"): |
d53de8b9 TAL |
866 | return path.lower().startswith(prefix.lower()) |
867 | return path.startswith(prefix) | |
868 | ||
543987bd PW |
869 | def getClientSpec(): |
870 | """Look at the p4 client spec, create a View() object that contains | |
871 | all the mappings, and return it.""" | |
872 | ||
873 | specList = p4CmdList("client -o") | |
874 | if len(specList) != 1: | |
875 | die('Output from "client -o" is %d lines, expecting 1' % | |
876 | len(specList)) | |
877 | ||
878 | # dictionary of all client parameters | |
879 | entry = specList[0] | |
880 | ||
9d57c4a6 KS |
881 | # the //client/ name |
882 | client_name = entry["Client"] | |
883 | ||
543987bd PW |
884 | # just the keys that start with "View" |
885 | view_keys = [ k for k in entry.keys() if k.startswith("View") ] | |
886 | ||
887 | # hold this new View | |
9d57c4a6 | 888 | view = View(client_name) |
543987bd PW |
889 | |
890 | # append the lines, in order, to the view | |
891 | for view_num in range(len(view_keys)): | |
892 | k = "View%d" % view_num | |
893 | if k not in view_keys: | |
894 | die("Expected view key %s missing" % k) | |
895 | view.append(entry[k]) | |
896 | ||
897 | return view | |
898 | ||
899 | def getClientRoot(): | |
900 | """Grab the client directory.""" | |
901 | ||
902 | output = p4CmdList("client -o") | |
903 | if len(output) != 1: | |
904 | die('Output from "client -o" is %d lines, expecting 1' % len(output)) | |
905 | ||
906 | entry = output[0] | |
907 | if "Root" not in entry: | |
908 | die('Client has no "Root"') | |
909 | ||
910 | return entry["Root"] | |
911 | ||
9d7d446a PW |
912 | # |
913 | # P4 wildcards are not allowed in filenames. P4 complains | |
914 | # if you simply add them, but you can force it with "-f", in | |
915 | # which case it translates them into %xx encoding internally. | |
916 | # | |
917 | def wildcard_decode(path): | |
918 | # Search for and fix just these four characters. Do % last so | |
919 | # that fixing it does not inadvertently create new %-escapes. | |
920 | # Cannot have * in a filename in windows; untested as to | |
921 | # what p4 would do in such a case. | |
922 | if not platform.system() == "Windows": | |
923 | path = path.replace("%2A", "*") | |
924 | path = path.replace("%23", "#") \ | |
925 | .replace("%40", "@") \ | |
926 | .replace("%25", "%") | |
927 | return path | |
928 | ||
929 | def wildcard_encode(path): | |
930 | # do % first to avoid double-encoding the %s introduced here | |
931 | path = path.replace("%", "%25") \ | |
932 | .replace("*", "%2A") \ | |
933 | .replace("#", "%23") \ | |
934 | .replace("@", "%40") | |
935 | return path | |
936 | ||
937 | def wildcard_present(path): | |
598354c0 BC |
938 | m = re.search("[*#@%]", path) |
939 | return m is not None | |
9d7d446a | 940 | |
a5db4b12 LS |
941 | class LargeFileSystem(object): |
942 | """Base class for large file system support.""" | |
943 | ||
944 | def __init__(self, writeToGitStream): | |
945 | self.largeFiles = set() | |
946 | self.writeToGitStream = writeToGitStream | |
947 | ||
948 | def generatePointer(self, cloneDestination, contentFile): | |
949 | """Return the content of a pointer file that is stored in Git instead of | |
950 | the actual content.""" | |
951 | assert False, "Method 'generatePointer' required in " + self.__class__.__name__ | |
952 | ||
953 | def pushFile(self, localLargeFile): | |
954 | """Push the actual content which is not stored in the Git repository to | |
955 | a server.""" | |
956 | assert False, "Method 'pushFile' required in " + self.__class__.__name__ | |
957 | ||
958 | def hasLargeFileExtension(self, relPath): | |
959 | return reduce( | |
960 | lambda a, b: a or b, | |
961 | [relPath.endswith('.' + e) for e in gitConfigList('git-p4.largeFileExtensions')], | |
962 | False | |
963 | ) | |
964 | ||
965 | def generateTempFile(self, contents): | |
966 | contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) | |
967 | for d in contents: | |
968 | contentFile.write(d) | |
969 | contentFile.close() | |
970 | return contentFile.name | |
971 | ||
972 | def exceedsLargeFileThreshold(self, relPath, contents): | |
973 | if gitConfigInt('git-p4.largeFileThreshold'): | |
974 | contentsSize = sum(len(d) for d in contents) | |
975 | if contentsSize > gitConfigInt('git-p4.largeFileThreshold'): | |
976 | return True | |
977 | if gitConfigInt('git-p4.largeFileCompressedThreshold'): | |
978 | contentsSize = sum(len(d) for d in contents) | |
979 | if contentsSize <= gitConfigInt('git-p4.largeFileCompressedThreshold'): | |
980 | return False | |
981 | contentTempFile = self.generateTempFile(contents) | |
982 | compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False) | |
983 | zf = zipfile.ZipFile(compressedContentFile.name, mode='w') | |
984 | zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED) | |
985 | zf.close() | |
986 | compressedContentsSize = zf.infolist()[0].compress_size | |
987 | os.remove(contentTempFile) | |
988 | os.remove(compressedContentFile.name) | |
989 | if compressedContentsSize > gitConfigInt('git-p4.largeFileCompressedThreshold'): | |
990 | return True | |
991 | return False | |
992 | ||
993 | def addLargeFile(self, relPath): | |
994 | self.largeFiles.add(relPath) | |
995 | ||
996 | def removeLargeFile(self, relPath): | |
997 | self.largeFiles.remove(relPath) | |
998 | ||
999 | def isLargeFile(self, relPath): | |
1000 | return relPath in self.largeFiles | |
1001 | ||
1002 | def processContent(self, git_mode, relPath, contents): | |
1003 | """Processes the content of git fast import. This method decides if a | |
1004 | file is stored in the large file system and handles all necessary | |
1005 | steps.""" | |
1006 | if self.exceedsLargeFileThreshold(relPath, contents) or self.hasLargeFileExtension(relPath): | |
1007 | contentTempFile = self.generateTempFile(contents) | |
1008 | (git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile) | |
1009 | ||
1010 | # Move temp file to final location in large file system | |
1011 | largeFileDir = os.path.dirname(localLargeFile) | |
1012 | if not os.path.isdir(largeFileDir): | |
1013 | os.makedirs(largeFileDir) | |
1014 | shutil.move(contentTempFile, localLargeFile) | |
1015 | self.addLargeFile(relPath) | |
1016 | if gitConfigBool('git-p4.largeFilePush'): | |
1017 | self.pushFile(localLargeFile) | |
1018 | if verbose: | |
1019 | sys.stderr.write("%s moved to large file system (%s)\n" % (relPath, localLargeFile)) | |
1020 | return (git_mode, contents) | |
1021 | ||
1022 | class MockLFS(LargeFileSystem): | |
1023 | """Mock large file system for testing.""" | |
1024 | ||
1025 | def generatePointer(self, contentFile): | |
1026 | """The pointer content is the original content prefixed with "pointer-". | |
1027 | The local filename of the large file storage is derived from the file content. | |
1028 | """ | |
1029 | with open(contentFile, 'r') as f: | |
1030 | content = next(f) | |
1031 | gitMode = '100644' | |
1032 | pointerContents = 'pointer-' + content | |
1033 | localLargeFile = os.path.join(os.getcwd(), '.git', 'mock-storage', 'local', content[:-1]) | |
1034 | return (gitMode, pointerContents, localLargeFile) | |
1035 | ||
1036 | def pushFile(self, localLargeFile): | |
1037 | """The remote filename of the large file storage is the same as the local | |
1038 | one but in a different directory. | |
1039 | """ | |
1040 | remotePath = os.path.join(os.path.dirname(localLargeFile), '..', 'remote') | |
1041 | if not os.path.exists(remotePath): | |
1042 | os.makedirs(remotePath) | |
1043 | shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile))) | |
1044 | ||
b47d807d LS |
1045 | class GitLFS(LargeFileSystem): |
1046 | """Git LFS as backend for the git-p4 large file system. | |
1047 | See https://git-lfs.github.com/ for details.""" | |
1048 | ||
1049 | def __init__(self, *args): | |
1050 | LargeFileSystem.__init__(self, *args) | |
1051 | self.baseGitAttributes = [] | |
1052 | ||
1053 | def generatePointer(self, contentFile): | |
1054 | """Generate a Git LFS pointer for the content. Return LFS Pointer file | |
1055 | mode and content which is stored in the Git repository instead of | |
1056 | the actual content. Return also the new location of the actual | |
1057 | content. | |
1058 | """ | |
1059 | pointerProcess = subprocess.Popen( | |
1060 | ['git', 'lfs', 'pointer', '--file=' + contentFile], | |
1061 | stdout=subprocess.PIPE | |
1062 | ) | |
1063 | pointerFile = pointerProcess.stdout.read() | |
1064 | if pointerProcess.wait(): | |
1065 | os.remove(contentFile) | |
1066 | die('git-lfs pointer command failed. Did you install the extension?') | |
1067 | pointerContents = [i+'\n' for i in pointerFile.split('\n')[2:][:-1]] | |
1068 | oid = pointerContents[1].split(' ')[1].split(':')[1][:-1] | |
1069 | localLargeFile = os.path.join( | |
1070 | os.getcwd(), | |
1071 | '.git', 'lfs', 'objects', oid[:2], oid[2:4], | |
1072 | oid, | |
1073 | ) | |
1074 | # LFS Spec states that pointer files should not have the executable bit set. | |
1075 | gitMode = '100644' | |
1076 | return (gitMode, pointerContents, localLargeFile) | |
1077 | ||
1078 | def pushFile(self, localLargeFile): | |
1079 | uploadProcess = subprocess.Popen( | |
1080 | ['git', 'lfs', 'push', '--object-id', 'origin', os.path.basename(localLargeFile)] | |
1081 | ) | |
1082 | if uploadProcess.wait(): | |
1083 | die('git-lfs push command failed. Did you define a remote?') | |
1084 | ||
1085 | def generateGitAttributes(self): | |
1086 | return ( | |
1087 | self.baseGitAttributes + | |
1088 | [ | |
1089 | '\n', | |
1090 | '#\n', | |
1091 | '# Git LFS (see https://git-lfs.github.com/)\n', | |
1092 | '#\n', | |
1093 | ] + | |
1094 | ['*.' + f.replace(' ', '[[:space:]]') + ' filter=lfs -text\n' | |
1095 | for f in sorted(gitConfigList('git-p4.largeFileExtensions')) | |
1096 | ] + | |
1097 | ['/' + f.replace(' ', '[[:space:]]') + ' filter=lfs -text\n' | |
1098 | for f in sorted(self.largeFiles) if not self.hasLargeFileExtension(f) | |
1099 | ] | |
1100 | ) | |
1101 | ||
1102 | def addLargeFile(self, relPath): | |
1103 | LargeFileSystem.addLargeFile(self, relPath) | |
1104 | self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes()) | |
1105 | ||
1106 | def removeLargeFile(self, relPath): | |
1107 | LargeFileSystem.removeLargeFile(self, relPath) | |
1108 | self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes()) | |
1109 | ||
1110 | def processContent(self, git_mode, relPath, contents): | |
1111 | if relPath == '.gitattributes': | |
1112 | self.baseGitAttributes = contents | |
1113 | return (git_mode, self.generateGitAttributes()) | |
1114 | else: | |
1115 | return LargeFileSystem.processContent(self, git_mode, relPath, contents) | |
1116 | ||
b984733c SH |
1117 | class Command: |
1118 | def __init__(self): | |
1119 | self.usage = "usage: %prog [options]" | |
8910ac0e | 1120 | self.needsGit = True |
6a10b6aa | 1121 | self.verbose = False |
b984733c | 1122 | |
3ea2cfd4 LD |
1123 | class P4UserMap: |
1124 | def __init__(self): | |
1125 | self.userMapFromPerforceServer = False | |
affb474f LD |
1126 | self.myP4UserId = None |
1127 | ||
1128 | def p4UserId(self): | |
1129 | if self.myP4UserId: | |
1130 | return self.myP4UserId | |
1131 | ||
1132 | results = p4CmdList("user -o") | |
1133 | for r in results: | |
1134 | if r.has_key('User'): | |
1135 | self.myP4UserId = r['User'] | |
1136 | return r['User'] | |
1137 | die("Could not find your p4 user id") | |
1138 | ||
1139 | def p4UserIsMe(self, p4User): | |
1140 | # return True if the given p4 user is actually me | |
1141 | me = self.p4UserId() | |
1142 | if not p4User or p4User != me: | |
1143 | return False | |
1144 | else: | |
1145 | return True | |
3ea2cfd4 LD |
1146 | |
1147 | def getUserCacheFilename(self): | |
1148 | home = os.environ.get("HOME", os.environ.get("USERPROFILE")) | |
1149 | return home + "/.gitp4-usercache.txt" | |
1150 | ||
1151 | def getUserMapFromPerforceServer(self): | |
1152 | if self.userMapFromPerforceServer: | |
1153 | return | |
1154 | self.users = {} | |
1155 | self.emails = {} | |
1156 | ||
1157 | for output in p4CmdList("users"): | |
1158 | if not output.has_key("User"): | |
1159 | continue | |
1160 | self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">" | |
1161 | self.emails[output["Email"]] = output["User"] | |
1162 | ||
10d08a14 LS |
1163 | mapUserConfigRegex = re.compile(r"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE) |
1164 | for mapUserConfig in gitConfigList("git-p4.mapUser"): | |
1165 | mapUser = mapUserConfigRegex.findall(mapUserConfig) | |
1166 | if mapUser and len(mapUser[0]) == 3: | |
1167 | user = mapUser[0][0] | |
1168 | fullname = mapUser[0][1] | |
1169 | email = mapUser[0][2] | |
1170 | self.users[user] = fullname + " <" + email + ">" | |
1171 | self.emails[email] = user | |
3ea2cfd4 LD |
1172 | |
1173 | s = '' | |
1174 | for (key, val) in self.users.items(): | |
1175 | s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1)) | |
1176 | ||
1177 | open(self.getUserCacheFilename(), "wb").write(s) | |
1178 | self.userMapFromPerforceServer = True | |
1179 | ||
1180 | def loadUserMapFromCache(self): | |
1181 | self.users = {} | |
1182 | self.userMapFromPerforceServer = False | |
1183 | try: | |
1184 | cache = open(self.getUserCacheFilename(), "rb") | |
1185 | lines = cache.readlines() | |
1186 | cache.close() | |
1187 | for line in lines: | |
1188 | entry = line.strip().split("\t") | |
1189 | self.users[entry[0]] = entry[1] | |
1190 | except IOError: | |
1191 | self.getUserMapFromPerforceServer() | |
1192 | ||
b984733c | 1193 | class P4Debug(Command): |
86949eef | 1194 | def __init__(self): |
6ae8de88 | 1195 | Command.__init__(self) |
6a10b6aa | 1196 | self.options = [] |
c8c39116 | 1197 | self.description = "A tool to debug the output of p4 -G." |
8910ac0e | 1198 | self.needsGit = False |
86949eef SH |
1199 | |
1200 | def run(self, args): | |
b1ce9447 | 1201 | j = 0 |
6de040df | 1202 | for output in p4CmdList(args): |
b1ce9447 HWN |
1203 | print 'Element: %d' % j |
1204 | j += 1 | |
86949eef | 1205 | print output |
b984733c | 1206 | return True |
86949eef | 1207 | |
5834684d SH |
1208 | class P4RollBack(Command): |
1209 | def __init__(self): | |
1210 | Command.__init__(self) | |
1211 | self.options = [ | |
0c66a783 | 1212 | optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true") |
5834684d SH |
1213 | ] |
1214 | self.description = "A tool to debug the multi-branch import. Don't use :)" | |
0c66a783 | 1215 | self.rollbackLocalBranches = False |
5834684d SH |
1216 | |
1217 | def run(self, args): | |
1218 | if len(args) != 1: | |
1219 | return False | |
1220 | maxChange = int(args[0]) | |
0c66a783 | 1221 | |
ad192f28 | 1222 | if "p4ExitCode" in p4Cmd("changes -m 1"): |
66a2f523 SH |
1223 | die("Problems executing p4"); |
1224 | ||
0c66a783 SH |
1225 | if self.rollbackLocalBranches: |
1226 | refPrefix = "refs/heads/" | |
b016d397 | 1227 | lines = read_pipe_lines("git rev-parse --symbolic --branches") |
0c66a783 SH |
1228 | else: |
1229 | refPrefix = "refs/remotes/" | |
b016d397 | 1230 | lines = read_pipe_lines("git rev-parse --symbolic --remotes") |
0c66a783 SH |
1231 | |
1232 | for line in lines: | |
1233 | if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"): | |
b25b2065 HWN |
1234 | line = line.strip() |
1235 | ref = refPrefix + line | |
5834684d | 1236 | log = extractLogMessageFromGitCommit(ref) |
bb6e09b2 HWN |
1237 | settings = extractSettingsGitLog(log) |
1238 | ||
1239 | depotPaths = settings['depot-paths'] | |
1240 | change = settings['change'] | |
1241 | ||
5834684d | 1242 | changed = False |
52102d47 | 1243 | |
6326aa58 HWN |
1244 | if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange) |
1245 | for p in depotPaths]))) == 0: | |
52102d47 SH |
1246 | print "Branch %s did not exist at change %s, deleting." % (ref, maxChange) |
1247 | system("git update-ref -d %s `git rev-parse %s`" % (ref, ref)) | |
1248 | continue | |
1249 | ||
bb6e09b2 | 1250 | while change and int(change) > maxChange: |
5834684d | 1251 | changed = True |
52102d47 SH |
1252 | if self.verbose: |
1253 | print "%s is at %s ; rewinding towards %s" % (ref, change, maxChange) | |
5834684d SH |
1254 | system("git update-ref %s \"%s^\"" % (ref, ref)) |
1255 | log = extractLogMessageFromGitCommit(ref) | |
bb6e09b2 HWN |
1256 | settings = extractSettingsGitLog(log) |
1257 | ||
1258 | ||
1259 | depotPaths = settings['depot-paths'] | |
1260 | change = settings['change'] | |
5834684d SH |
1261 | |
1262 | if changed: | |
52102d47 | 1263 | print "%s rewound to %s" % (ref, change) |
5834684d SH |
1264 | |
1265 | return True | |
1266 | ||
3ea2cfd4 | 1267 | class P4Submit(Command, P4UserMap): |
6bbfd137 PW |
1268 | |
1269 | conflict_behavior_choices = ("ask", "skip", "quit") | |
1270 | ||
4f5cf76a | 1271 | def __init__(self): |
b984733c | 1272 | Command.__init__(self) |
3ea2cfd4 | 1273 | P4UserMap.__init__(self) |
4f5cf76a | 1274 | self.options = [ |
4f5cf76a | 1275 | optparse.make_option("--origin", dest="origin"), |
ae901090 | 1276 | optparse.make_option("-M", dest="detectRenames", action="store_true"), |
3ea2cfd4 LD |
1277 | # preserve the user, requires relevant p4 permissions |
1278 | optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"), | |
06804c76 | 1279 | optparse.make_option("--export-labels", dest="exportLabels", action="store_true"), |
ef739f08 | 1280 | optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"), |
728b7ad8 | 1281 | optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"), |
6bbfd137 | 1282 | optparse.make_option("--conflict", dest="conflict_behavior", |
44e8d26c PW |
1283 | choices=self.conflict_behavior_choices), |
1284 | optparse.make_option("--branch", dest="branch"), | |
4f5cf76a SH |
1285 | ] |
1286 | self.description = "Submit changes from git to the perforce depot." | |
c9b50e63 | 1287 | self.usage += " [name of git branch to submit into perforce depot]" |
9512497b | 1288 | self.origin = "" |
ae901090 | 1289 | self.detectRenames = False |
0d609032 | 1290 | self.preserveUser = gitConfigBool("git-p4.preserveUser") |
ef739f08 | 1291 | self.dry_run = False |
728b7ad8 | 1292 | self.prepare_p4_only = False |
6bbfd137 | 1293 | self.conflict_behavior = None |
f7baba8b | 1294 | self.isWindows = (platform.system() == "Windows") |
06804c76 | 1295 | self.exportLabels = False |
249da4c0 | 1296 | self.p4HasMoveCommand = p4_has_move_command() |
44e8d26c | 1297 | self.branch = None |
4f5cf76a | 1298 | |
a5db4b12 LS |
1299 | if gitConfig('git-p4.largeFileSystem'): |
1300 | die("Large file system not supported for git-p4 submit command. Please remove it from config.") | |
1301 | ||
4f5cf76a SH |
1302 | def check(self): |
1303 | if len(p4CmdList("opened ...")) > 0: | |
1304 | die("You have files opened with perforce! Close them before starting the sync.") | |
1305 | ||
f19cb0a0 PW |
1306 | def separate_jobs_from_description(self, message): |
1307 | """Extract and return a possible Jobs field in the commit | |
1308 | message. It goes into a separate section in the p4 change | |
1309 | specification. | |
1310 | ||
1311 | A jobs line starts with "Jobs:" and looks like a new field | |
1312 | in a form. Values are white-space separated on the same | |
1313 | line or on following lines that start with a tab. | |
1314 | ||
1315 | This does not parse and extract the full git commit message | |
1316 | like a p4 form. It just sees the Jobs: line as a marker | |
1317 | to pass everything from then on directly into the p4 form, | |
1318 | but outside the description section. | |
1319 | ||
1320 | Return a tuple (stripped log message, jobs string).""" | |
1321 | ||
1322 | m = re.search(r'^Jobs:', message, re.MULTILINE) | |
1323 | if m is None: | |
1324 | return (message, None) | |
1325 | ||
1326 | jobtext = message[m.start():] | |
1327 | stripped_message = message[:m.start()].rstrip() | |
1328 | return (stripped_message, jobtext) | |
1329 | ||
1330 | def prepareLogMessage(self, template, message, jobs): | |
1331 | """Edits the template returned from "p4 change -o" to insert | |
1332 | the message in the Description field, and the jobs text in | |
1333 | the Jobs field.""" | |
4f5cf76a SH |
1334 | result = "" |
1335 | ||
edae1e2f SH |
1336 | inDescriptionSection = False |
1337 | ||
4f5cf76a SH |
1338 | for line in template.split("\n"): |
1339 | if line.startswith("#"): | |
1340 | result += line + "\n" | |
1341 | continue | |
1342 | ||
edae1e2f | 1343 | if inDescriptionSection: |
c9dbab04 | 1344 | if line.startswith("Files:") or line.startswith("Jobs:"): |
edae1e2f | 1345 | inDescriptionSection = False |
f19cb0a0 PW |
1346 | # insert Jobs section |
1347 | if jobs: | |
1348 | result += jobs + "\n" | |
edae1e2f SH |
1349 | else: |
1350 | continue | |
1351 | else: | |
1352 | if line.startswith("Description:"): | |
1353 | inDescriptionSection = True | |
1354 | line += "\n" | |
1355 | for messageLine in message.split("\n"): | |
1356 | line += "\t" + messageLine + "\n" | |
1357 | ||
1358 | result += line + "\n" | |
4f5cf76a SH |
1359 | |
1360 | return result | |
1361 | ||
60df071c LD |
1362 | def patchRCSKeywords(self, file, pattern): |
1363 | # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern | |
1364 | (handle, outFileName) = tempfile.mkstemp(dir='.') | |
1365 | try: | |
1366 | outFile = os.fdopen(handle, "w+") | |
1367 | inFile = open(file, "r") | |
1368 | regexp = re.compile(pattern, re.VERBOSE) | |
1369 | for line in inFile.readlines(): | |
1370 | line = regexp.sub(r'$\1$', line) | |
1371 | outFile.write(line) | |
1372 | inFile.close() | |
1373 | outFile.close() | |
1374 | # Forcibly overwrite the original file | |
1375 | os.unlink(file) | |
1376 | shutil.move(outFileName, file) | |
1377 | except: | |
1378 | # cleanup our temporary file | |
1379 | os.unlink(outFileName) | |
1380 | print "Failed to strip RCS keywords in %s" % file | |
1381 | raise | |
1382 | ||
1383 | print "Patched up RCS keywords in %s" % file | |
1384 | ||
3ea2cfd4 LD |
1385 | def p4UserForCommit(self,id): |
1386 | # Return the tuple (perforce user,git email) for a given git commit id | |
1387 | self.getUserMapFromPerforceServer() | |
9bf28855 PW |
1388 | gitEmail = read_pipe(["git", "log", "--max-count=1", |
1389 | "--format=%ae", id]) | |
3ea2cfd4 LD |
1390 | gitEmail = gitEmail.strip() |
1391 | if not self.emails.has_key(gitEmail): | |
1392 | return (None,gitEmail) | |
1393 | else: | |
1394 | return (self.emails[gitEmail],gitEmail) | |
1395 | ||
1396 | def checkValidP4Users(self,commits): | |
1397 | # check if any git authors cannot be mapped to p4 users | |
1398 | for id in commits: | |
1399 | (user,email) = self.p4UserForCommit(id) | |
1400 | if not user: | |
1401 | msg = "Cannot find p4 user for email %s in commit %s." % (email, id) | |
0d609032 | 1402 | if gitConfigBool("git-p4.allowMissingP4Users"): |
3ea2cfd4 LD |
1403 | print "%s" % msg |
1404 | else: | |
1405 | die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg) | |
1406 | ||
1407 | def lastP4Changelist(self): | |
1408 | # Get back the last changelist number submitted in this client spec. This | |
1409 | # then gets used to patch up the username in the change. If the same | |
1410 | # client spec is being used by multiple processes then this might go | |
1411 | # wrong. | |
1412 | results = p4CmdList("client -o") # find the current client | |
1413 | client = None | |
1414 | for r in results: | |
1415 | if r.has_key('Client'): | |
1416 | client = r['Client'] | |
1417 | break | |
1418 | if not client: | |
1419 | die("could not get client spec") | |
6de040df | 1420 | results = p4CmdList(["changes", "-c", client, "-m", "1"]) |
3ea2cfd4 LD |
1421 | for r in results: |
1422 | if r.has_key('change'): | |
1423 | return r['change'] | |
1424 | die("Could not get changelist number for last submit - cannot patch up user details") | |
1425 | ||
1426 | def modifyChangelistUser(self, changelist, newUser): | |
1427 | # fixup the user field of a changelist after it has been submitted. | |
1428 | changes = p4CmdList("change -o %s" % changelist) | |
ecdba36d LD |
1429 | if len(changes) != 1: |
1430 | die("Bad output from p4 change modifying %s to user %s" % | |
1431 | (changelist, newUser)) | |
1432 | ||
1433 | c = changes[0] | |
1434 | if c['User'] == newUser: return # nothing to do | |
1435 | c['User'] = newUser | |
1436 | input = marshal.dumps(c) | |
1437 | ||
3ea2cfd4 LD |
1438 | result = p4CmdList("change -f -i", stdin=input) |
1439 | for r in result: | |
1440 | if r.has_key('code'): | |
1441 | if r['code'] == 'error': | |
1442 | die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data'])) | |
1443 | if r.has_key('data'): | |
1444 | print("Updated user field for changelist %s to %s" % (changelist, newUser)) | |
1445 | return | |
1446 | die("Could not modify user field of changelist %s to %s" % (changelist, newUser)) | |
1447 | ||
1448 | def canChangeChangelists(self): | |
1449 | # check to see if we have p4 admin or super-user permissions, either of | |
1450 | # which are required to modify changelists. | |
52a4880b | 1451 | results = p4CmdList(["protects", self.depotPath]) |
3ea2cfd4 LD |
1452 | for r in results: |
1453 | if r.has_key('perm'): | |
1454 | if r['perm'] == 'admin': | |
1455 | return 1 | |
1456 | if r['perm'] == 'super': | |
1457 | return 1 | |
1458 | return 0 | |
1459 | ||
ea99c3ae | 1460 | def prepareSubmitTemplate(self): |
f19cb0a0 PW |
1461 | """Run "p4 change -o" to grab a change specification template. |
1462 | This does not use "p4 -G", as it is nice to keep the submission | |
1463 | template in original order, since a human might edit it. | |
1464 | ||
1465 | Remove lines in the Files section that show changes to files | |
1466 | outside the depot path we're committing into.""" | |
1467 | ||
cbc69242 SH |
1468 | [upstream, settings] = findUpstreamBranchPoint() |
1469 | ||
ea99c3ae SH |
1470 | template = "" |
1471 | inFilesSection = False | |
6de040df | 1472 | for line in p4_read_pipe_lines(['change', '-o']): |
f3e5ae4f MSO |
1473 | if line.endswith("\r\n"): |
1474 | line = line[:-2] + "\n" | |
ea99c3ae SH |
1475 | if inFilesSection: |
1476 | if line.startswith("\t"): | |
1477 | # path starts and ends with a tab | |
1478 | path = line[1:] | |
1479 | lastTab = path.rfind("\t") | |
1480 | if lastTab != -1: | |
1481 | path = path[:lastTab] | |
cbc69242 SH |
1482 | if settings.has_key('depot-paths'): |
1483 | if not [p for p in settings['depot-paths'] | |
1484 | if p4PathStartsWith(path, p)]: | |
1485 | continue | |
1486 | else: | |
1487 | if not p4PathStartsWith(path, self.depotPath): | |
1488 | continue | |
ea99c3ae SH |
1489 | else: |
1490 | inFilesSection = False | |
1491 | else: | |
1492 | if line.startswith("Files:"): | |
1493 | inFilesSection = True | |
1494 | ||
1495 | template += line | |
1496 | ||
1497 | return template | |
1498 | ||
7c766e57 PW |
1499 | def edit_template(self, template_file): |
1500 | """Invoke the editor to let the user change the submission | |
1501 | message. Return true if okay to continue with the submit.""" | |
1502 | ||
1503 | # if configured to skip the editing part, just submit | |
0d609032 | 1504 | if gitConfigBool("git-p4.skipSubmitEdit"): |
7c766e57 PW |
1505 | return True |
1506 | ||
1507 | # look at the modification time, to check later if the user saved | |
1508 | # the file | |
1509 | mtime = os.stat(template_file).st_mtime | |
1510 | ||
1511 | # invoke the editor | |
f95ceaf0 | 1512 | if os.environ.has_key("P4EDITOR") and (os.environ.get("P4EDITOR") != ""): |
7c766e57 PW |
1513 | editor = os.environ.get("P4EDITOR") |
1514 | else: | |
1515 | editor = read_pipe("git var GIT_EDITOR").strip() | |
2dade7a7 | 1516 | system(["sh", "-c", ('%s "$@"' % editor), editor, template_file]) |
7c766e57 PW |
1517 | |
1518 | # If the file was not saved, prompt to see if this patch should | |
1519 | # be skipped. But skip this verification step if configured so. | |
0d609032 | 1520 | if gitConfigBool("git-p4.skipSubmitEditCheck"): |
7c766e57 PW |
1521 | return True |
1522 | ||
d1652049 PW |
1523 | # modification time updated means user saved the file |
1524 | if os.stat(template_file).st_mtime > mtime: | |
1525 | return True | |
1526 | ||
1527 | while True: | |
1528 | response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ") | |
1529 | if response == 'y': | |
1530 | return True | |
1531 | if response == 'n': | |
1532 | return False | |
7c766e57 | 1533 | |
e2a892ee | 1534 | def get_diff_description(self, editedFiles, filesToAdd): |
b4073bb3 MC |
1535 | # diff |
1536 | if os.environ.has_key("P4DIFF"): | |
1537 | del(os.environ["P4DIFF"]) | |
1538 | diff = "" | |
1539 | for editedFile in editedFiles: | |
1540 | diff += p4_read_pipe(['diff', '-du', | |
1541 | wildcard_encode(editedFile)]) | |
1542 | ||
1543 | # new file diff | |
1544 | newdiff = "" | |
1545 | for newFile in filesToAdd: | |
1546 | newdiff += "==== new file ====\n" | |
1547 | newdiff += "--- /dev/null\n" | |
1548 | newdiff += "+++ %s\n" % newFile | |
1549 | f = open(newFile, "r") | |
1550 | for line in f.readlines(): | |
1551 | newdiff += "+" + line | |
1552 | f.close() | |
1553 | ||
e2a892ee | 1554 | return (diff + newdiff).replace('\r\n', '\n') |
b4073bb3 | 1555 | |
7cb5cbef | 1556 | def applyCommit(self, id): |
67b0fe2e PW |
1557 | """Apply one commit, return True if it succeeded.""" |
1558 | ||
1559 | print "Applying", read_pipe(["git", "show", "-s", | |
1560 | "--format=format:%h %s", id]) | |
ae901090 | 1561 | |
848de9c3 | 1562 | (p4User, gitEmail) = self.p4UserForCommit(id) |
3ea2cfd4 | 1563 | |
84cb0003 | 1564 | diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id)) |
4f5cf76a | 1565 | filesToAdd = set() |
a02b8bc4 | 1566 | filesToChangeType = set() |
4f5cf76a | 1567 | filesToDelete = set() |
d336c158 | 1568 | editedFiles = set() |
b6ad6dcc | 1569 | pureRenameCopy = set() |
c65b670e | 1570 | filesToChangeExecBit = {} |
60df071c | 1571 | |
4f5cf76a | 1572 | for line in diff: |
b43b0a3c CP |
1573 | diff = parseDiffTreeEntry(line) |
1574 | modifier = diff['status'] | |
1575 | path = diff['src'] | |
4f5cf76a | 1576 | if modifier == "M": |
6de040df | 1577 | p4_edit(path) |
c65b670e CP |
1578 | if isModeExecChanged(diff['src_mode'], diff['dst_mode']): |
1579 | filesToChangeExecBit[path] = diff['dst_mode'] | |
d336c158 | 1580 | editedFiles.add(path) |
4f5cf76a SH |
1581 | elif modifier == "A": |
1582 | filesToAdd.add(path) | |
c65b670e | 1583 | filesToChangeExecBit[path] = diff['dst_mode'] |
4f5cf76a SH |
1584 | if path in filesToDelete: |
1585 | filesToDelete.remove(path) | |
1586 | elif modifier == "D": | |
1587 | filesToDelete.add(path) | |
1588 | if path in filesToAdd: | |
1589 | filesToAdd.remove(path) | |
4fddb41b VA |
1590 | elif modifier == "C": |
1591 | src, dest = diff['src'], diff['dst'] | |
6de040df | 1592 | p4_integrate(src, dest) |
b6ad6dcc | 1593 | pureRenameCopy.add(dest) |
4fddb41b | 1594 | if diff['src_sha1'] != diff['dst_sha1']: |
6de040df | 1595 | p4_edit(dest) |
b6ad6dcc | 1596 | pureRenameCopy.discard(dest) |
4fddb41b | 1597 | if isModeExecChanged(diff['src_mode'], diff['dst_mode']): |
6de040df | 1598 | p4_edit(dest) |
b6ad6dcc | 1599 | pureRenameCopy.discard(dest) |
4fddb41b | 1600 | filesToChangeExecBit[dest] = diff['dst_mode'] |
d20f0f8e PW |
1601 | if self.isWindows: |
1602 | # turn off read-only attribute | |
1603 | os.chmod(dest, stat.S_IWRITE) | |
4fddb41b VA |
1604 | os.unlink(dest) |
1605 | editedFiles.add(dest) | |
d9a5f25b | 1606 | elif modifier == "R": |
b43b0a3c | 1607 | src, dest = diff['src'], diff['dst'] |
8e9497c2 GG |
1608 | if self.p4HasMoveCommand: |
1609 | p4_edit(src) # src must be open before move | |
1610 | p4_move(src, dest) # opens for (move/delete, move/add) | |
b6ad6dcc | 1611 | else: |
8e9497c2 GG |
1612 | p4_integrate(src, dest) |
1613 | if diff['src_sha1'] != diff['dst_sha1']: | |
1614 | p4_edit(dest) | |
1615 | else: | |
1616 | pureRenameCopy.add(dest) | |
c65b670e | 1617 | if isModeExecChanged(diff['src_mode'], diff['dst_mode']): |
8e9497c2 GG |
1618 | if not self.p4HasMoveCommand: |
1619 | p4_edit(dest) # with move: already open, writable | |
c65b670e | 1620 | filesToChangeExecBit[dest] = diff['dst_mode'] |
8e9497c2 | 1621 | if not self.p4HasMoveCommand: |
d20f0f8e PW |
1622 | if self.isWindows: |
1623 | os.chmod(dest, stat.S_IWRITE) | |
8e9497c2 GG |
1624 | os.unlink(dest) |
1625 | filesToDelete.add(src) | |
d9a5f25b | 1626 | editedFiles.add(dest) |
a02b8bc4 RP |
1627 | elif modifier == "T": |
1628 | filesToChangeType.add(path) | |
4f5cf76a SH |
1629 | else: |
1630 | die("unknown modifier %s for %s" % (modifier, path)) | |
1631 | ||
749b668c | 1632 | diffcmd = "git diff-tree --full-index -p \"%s\"" % (id) |
47a130b7 | 1633 | patchcmd = diffcmd + " | git apply " |
c1b296b9 SH |
1634 | tryPatchCmd = patchcmd + "--check -" |
1635 | applyPatchCmd = patchcmd + "--check --apply -" | |
60df071c | 1636 | patch_succeeded = True |
51a2640a | 1637 | |
47a130b7 | 1638 | if os.system(tryPatchCmd) != 0: |
60df071c LD |
1639 | fixed_rcs_keywords = False |
1640 | patch_succeeded = False | |
51a2640a | 1641 | print "Unfortunately applying the change failed!" |
60df071c LD |
1642 | |
1643 | # Patch failed, maybe it's just RCS keyword woes. Look through | |
1644 | # the patch to see if that's possible. | |
0d609032 | 1645 | if gitConfigBool("git-p4.attemptRCSCleanup"): |
60df071c LD |
1646 | file = None |
1647 | pattern = None | |
1648 | kwfiles = {} | |
1649 | for file in editedFiles | filesToDelete: | |
1650 | # did this file's delta contain RCS keywords? | |
1651 | pattern = p4_keywords_regexp_for_file(file) | |
1652 | ||
1653 | if pattern: | |
1654 | # this file is a possibility...look for RCS keywords. | |
1655 | regexp = re.compile(pattern, re.VERBOSE) | |
1656 | for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]): | |
1657 | if regexp.search(line): | |
1658 | if verbose: | |
1659 | print "got keyword match on %s in %s in %s" % (pattern, line, file) | |
1660 | kwfiles[file] = pattern | |
1661 | break | |
1662 | ||
1663 | for file in kwfiles: | |
1664 | if verbose: | |
1665 | print "zapping %s with %s" % (line,pattern) | |
d20f0f8e PW |
1666 | # File is being deleted, so not open in p4. Must |
1667 | # disable the read-only bit on windows. | |
1668 | if self.isWindows and file not in editedFiles: | |
1669 | os.chmod(file, stat.S_IWRITE) | |
60df071c LD |
1670 | self.patchRCSKeywords(file, kwfiles[file]) |
1671 | fixed_rcs_keywords = True | |
1672 | ||
1673 | if fixed_rcs_keywords: | |
1674 | print "Retrying the patch with RCS keywords cleaned up" | |
1675 | if os.system(tryPatchCmd) == 0: | |
1676 | patch_succeeded = True | |
1677 | ||
1678 | if not patch_succeeded: | |
7e5dd9f2 PW |
1679 | for f in editedFiles: |
1680 | p4_revert(f) | |
7e5dd9f2 | 1681 | return False |
51a2640a | 1682 | |
55ac2ed6 PW |
1683 | # |
1684 | # Apply the patch for real, and do add/delete/+x handling. | |
1685 | # | |
47a130b7 | 1686 | system(applyPatchCmd) |
4f5cf76a | 1687 | |
a02b8bc4 RP |
1688 | for f in filesToChangeType: |
1689 | p4_edit(f, "-t", "auto") | |
4f5cf76a | 1690 | for f in filesToAdd: |
6de040df | 1691 | p4_add(f) |
4f5cf76a | 1692 | for f in filesToDelete: |
6de040df LD |
1693 | p4_revert(f) |
1694 | p4_delete(f) | |
4f5cf76a | 1695 | |
c65b670e CP |
1696 | # Set/clear executable bits |
1697 | for f in filesToChangeExecBit.keys(): | |
1698 | mode = filesToChangeExecBit[f] | |
1699 | setP4ExecBit(f, mode) | |
1700 | ||
55ac2ed6 PW |
1701 | # |
1702 | # Build p4 change description, starting with the contents | |
1703 | # of the git commit message. | |
1704 | # | |
0e36f2d7 | 1705 | logMessage = extractLogMessageFromGitCommit(id) |
0e36f2d7 | 1706 | logMessage = logMessage.strip() |
f19cb0a0 | 1707 | (logMessage, jobs) = self.separate_jobs_from_description(logMessage) |
4f5cf76a | 1708 | |
ea99c3ae | 1709 | template = self.prepareSubmitTemplate() |
f19cb0a0 | 1710 | submitTemplate = self.prepareLogMessage(template, logMessage, jobs) |
ecdba36d | 1711 | |
c47178d4 | 1712 | if self.preserveUser: |
55ac2ed6 | 1713 | submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User |
c47178d4 | 1714 | |
55ac2ed6 PW |
1715 | if self.checkAuthorship and not self.p4UserIsMe(p4User): |
1716 | submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail | |
1717 | submitTemplate += "######## Use option --preserve-user to modify authorship.\n" | |
1718 | submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n" | |
c47178d4 | 1719 | |
55ac2ed6 | 1720 | separatorLine = "######## everything below this line is just the diff #######\n" |
b4073bb3 MC |
1721 | if not self.prepare_p4_only: |
1722 | submitTemplate += separatorLine | |
e2a892ee | 1723 | submitTemplate += self.get_diff_description(editedFiles, filesToAdd) |
55ac2ed6 | 1724 | |
c47178d4 | 1725 | (handle, fileName) = tempfile.mkstemp() |
e2a892ee | 1726 | tmpFile = os.fdopen(handle, "w+b") |
c47178d4 PW |
1727 | if self.isWindows: |
1728 | submitTemplate = submitTemplate.replace("\n", "\r\n") | |
b4073bb3 | 1729 | tmpFile.write(submitTemplate) |
c47178d4 PW |
1730 | tmpFile.close() |
1731 | ||
728b7ad8 PW |
1732 | if self.prepare_p4_only: |
1733 | # | |
1734 | # Leave the p4 tree prepared, and the submit template around | |
1735 | # and let the user decide what to do next | |
1736 | # | |
1737 | ||
1738 | print "P4 workspace prepared for submission." | |
1739 | print "To submit or revert, go to client workspace" | |
1740 | print " " + self.clientPath | |
1741 | ||
1742 | print "To submit, use \"p4 submit\" to write a new description," | |
10de86d0 | 1743 | print "or \"p4 submit -i <%s\" to use the one prepared by" \ |
728b7ad8 PW |
1744 | " \"git p4\"." % fileName |
1745 | print "You can delete the file \"%s\" when finished." % fileName | |
1746 | ||
1747 | if self.preserveUser and p4User and not self.p4UserIsMe(p4User): | |
1748 | print "To preserve change ownership by user %s, you must\n" \ | |
1749 | "do \"p4 change -f <change>\" after submitting and\n" \ | |
1750 | "edit the User field." | |
1751 | if pureRenameCopy: | |
1752 | print "After submitting, renamed files must be re-synced." | |
1753 | print "Invoke \"p4 sync -f\" on each of these files:" | |
1754 | for f in pureRenameCopy: | |
1755 | print " " + f | |
1756 | ||
1757 | ||
1758 | print "To revert the changes, use \"p4 revert ...\", and delete" | |
1759 | print "the submit template file \"%s\"" % fileName | |
1760 | if filesToAdd: | |
1761 | print "Since the commit adds new files, they must be deleted:" | |
1762 | for f in filesToAdd: | |
1763 | print " " + f | |
1764 | ||
1765 | return True | |
1766 | ||
55ac2ed6 PW |
1767 | # |
1768 | # Let the user edit the change description, then submit it. | |
1769 | # | |
b7638fed | 1770 | submitted = False |
cdc7e388 | 1771 | |
b7638fed GE |
1772 | try: |
1773 | if self.edit_template(fileName): | |
1774 | # read the edited message and submit | |
1775 | tmpFile = open(fileName, "rb") | |
1776 | message = tmpFile.read() | |
1777 | tmpFile.close() | |
1778 | if self.isWindows: | |
1779 | message = message.replace("\r\n", "\n") | |
1780 | submitTemplate = message[:message.index(separatorLine)] | |
1781 | p4_write_pipe(['submit', '-i'], submitTemplate) | |
1782 | ||
1783 | if self.preserveUser: | |
1784 | if p4User: | |
1785 | # Get last changelist number. Cannot easily get it from | |
1786 | # the submit command output as the output is | |
1787 | # unmarshalled. | |
1788 | changelist = self.lastP4Changelist() | |
1789 | self.modifyChangelistUser(changelist, p4User) | |
1790 | ||
1791 | # The rename/copy happened by applying a patch that created a | |
1792 | # new file. This leaves it writable, which confuses p4. | |
1793 | for f in pureRenameCopy: | |
1794 | p4_sync(f, "-f") | |
1795 | submitted = True | |
1796 | ||
1797 | finally: | |
c47178d4 | 1798 | # skip this patch |
b7638fed GE |
1799 | if not submitted: |
1800 | print "Submission cancelled, undoing p4 changes." | |
1801 | for f in editedFiles: | |
1802 | p4_revert(f) | |
1803 | for f in filesToAdd: | |
1804 | p4_revert(f) | |
1805 | os.remove(f) | |
1806 | for f in filesToDelete: | |
1807 | p4_revert(f) | |
c47178d4 PW |
1808 | |
1809 | os.remove(fileName) | |
b7638fed | 1810 | return submitted |
4f5cf76a | 1811 | |
06804c76 LD |
1812 | # Export git tags as p4 labels. Create a p4 label and then tag |
1813 | # with that. | |
1814 | def exportGitTags(self, gitTags): | |
c8942a22 LD |
1815 | validLabelRegexp = gitConfig("git-p4.labelExportRegexp") |
1816 | if len(validLabelRegexp) == 0: | |
1817 | validLabelRegexp = defaultLabelRegexp | |
1818 | m = re.compile(validLabelRegexp) | |
06804c76 LD |
1819 | |
1820 | for name in gitTags: | |
1821 | ||
1822 | if not m.match(name): | |
1823 | if verbose: | |
05a3cec5 | 1824 | print "tag %s does not match regexp %s" % (name, validLabelRegexp) |
06804c76 LD |
1825 | continue |
1826 | ||
1827 | # Get the p4 commit this corresponds to | |
c8942a22 LD |
1828 | logMessage = extractLogMessageFromGitCommit(name) |
1829 | values = extractSettingsGitLog(logMessage) | |
06804c76 | 1830 | |
c8942a22 | 1831 | if not values.has_key('change'): |
06804c76 LD |
1832 | # a tag pointing to something not sent to p4; ignore |
1833 | if verbose: | |
1834 | print "git tag %s does not give a p4 commit" % name | |
1835 | continue | |
c8942a22 LD |
1836 | else: |
1837 | changelist = values['change'] | |
06804c76 LD |
1838 | |
1839 | # Get the tag details. | |
1840 | inHeader = True | |
1841 | isAnnotated = False | |
1842 | body = [] | |
1843 | for l in read_pipe_lines(["git", "cat-file", "-p", name]): | |
1844 | l = l.strip() | |
1845 | if inHeader: | |
1846 | if re.match(r'tag\s+', l): | |
1847 | isAnnotated = True | |
1848 | elif re.match(r'\s*$', l): | |
1849 | inHeader = False | |
1850 | continue | |
1851 | else: | |
1852 | body.append(l) | |
1853 | ||
1854 | if not isAnnotated: | |
1855 | body = ["lightweight tag imported by git p4\n"] | |
1856 | ||
1857 | # Create the label - use the same view as the client spec we are using | |
1858 | clientSpec = getClientSpec() | |
1859 | ||
1860 | labelTemplate = "Label: %s\n" % name | |
1861 | labelTemplate += "Description:\n" | |
1862 | for b in body: | |
1863 | labelTemplate += "\t" + b + "\n" | |
1864 | labelTemplate += "View:\n" | |
9d57c4a6 KS |
1865 | for depot_side in clientSpec.mappings: |
1866 | labelTemplate += "\t%s\n" % depot_side | |
06804c76 | 1867 | |
ef739f08 PW |
1868 | if self.dry_run: |
1869 | print "Would create p4 label %s for tag" % name | |
728b7ad8 PW |
1870 | elif self.prepare_p4_only: |
1871 | print "Not creating p4 label %s for tag due to option" \ | |
1872 | " --prepare-p4-only" % name | |
ef739f08 PW |
1873 | else: |
1874 | p4_write_pipe(["label", "-i"], labelTemplate) | |
06804c76 | 1875 | |
ef739f08 PW |
1876 | # Use the label |
1877 | p4_system(["tag", "-l", name] + | |
9d57c4a6 | 1878 | ["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings]) |
06804c76 | 1879 | |
ef739f08 PW |
1880 | if verbose: |
1881 | print "created p4 label for tag %s" % name | |
06804c76 | 1882 | |
4f5cf76a | 1883 | def run(self, args): |
c9b50e63 SH |
1884 | if len(args) == 0: |
1885 | self.master = currentGitBranch() | |
c9b50e63 SH |
1886 | elif len(args) == 1: |
1887 | self.master = args[0] | |
28755dba PW |
1888 | if not branchExists(self.master): |
1889 | die("Branch %s does not exist" % self.master) | |
c9b50e63 SH |
1890 | else: |
1891 | return False | |
1892 | ||
00ad6e31 LD |
1893 | if self.master: |
1894 | allowSubmit = gitConfig("git-p4.allowSubmit") | |
1895 | if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","): | |
1896 | die("%s is not in git-p4.allowSubmit" % self.master) | |
4c2d5d72 | 1897 | |
27d2d811 | 1898 | [upstream, settings] = findUpstreamBranchPoint() |
ea99c3ae | 1899 | self.depotPath = settings['depot-paths'][0] |
27d2d811 SH |
1900 | if len(self.origin) == 0: |
1901 | self.origin = upstream | |
a3fdd579 | 1902 | |
3ea2cfd4 LD |
1903 | if self.preserveUser: |
1904 | if not self.canChangeChangelists(): | |
1905 | die("Cannot preserve user names without p4 super-user or admin permissions") | |
1906 | ||
6bbfd137 PW |
1907 | # if not set from the command line, try the config file |
1908 | if self.conflict_behavior is None: | |
1909 | val = gitConfig("git-p4.conflict") | |
1910 | if val: | |
1911 | if val not in self.conflict_behavior_choices: | |
1912 | die("Invalid value '%s' for config git-p4.conflict" % val) | |
1913 | else: | |
1914 | val = "ask" | |
1915 | self.conflict_behavior = val | |
1916 | ||
a3fdd579 SH |
1917 | if self.verbose: |
1918 | print "Origin branch is " + self.origin | |
9512497b | 1919 | |
ea99c3ae | 1920 | if len(self.depotPath) == 0: |
9512497b SH |
1921 | print "Internal error: cannot locate perforce depot path from existing branches" |
1922 | sys.exit(128) | |
1923 | ||
543987bd | 1924 | self.useClientSpec = False |
0d609032 | 1925 | if gitConfigBool("git-p4.useclientspec"): |
543987bd PW |
1926 | self.useClientSpec = True |
1927 | if self.useClientSpec: | |
1928 | self.clientSpecDirs = getClientSpec() | |
9512497b | 1929 | |
cd884106 VA |
1930 | # Check for the existance of P4 branches |
1931 | branchesDetected = (len(p4BranchesInGit().keys()) > 1) | |
1932 | ||
1933 | if self.useClientSpec and not branchesDetected: | |
543987bd PW |
1934 | # all files are relative to the client spec |
1935 | self.clientPath = getClientRoot() | |
1936 | else: | |
1937 | self.clientPath = p4Where(self.depotPath) | |
9512497b | 1938 | |
543987bd PW |
1939 | if self.clientPath == "": |
1940 | die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath) | |
9512497b | 1941 | |
ea99c3ae | 1942 | print "Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath) |
7944f142 | 1943 | self.oldWorkingDirectory = os.getcwd() |
c1b296b9 | 1944 | |
0591cfa8 | 1945 | # ensure the clientPath exists |
8d7ec362 | 1946 | new_client_dir = False |
0591cfa8 | 1947 | if not os.path.exists(self.clientPath): |
8d7ec362 | 1948 | new_client_dir = True |
0591cfa8 GG |
1949 | os.makedirs(self.clientPath) |
1950 | ||
bbd84863 | 1951 | chdir(self.clientPath, is_client_path=True) |
ef739f08 PW |
1952 | if self.dry_run: |
1953 | print "Would synchronize p4 checkout in %s" % self.clientPath | |
8d7ec362 | 1954 | else: |
ef739f08 PW |
1955 | print "Synchronizing p4 checkout..." |
1956 | if new_client_dir: | |
1957 | # old one was destroyed, and maybe nobody told p4 | |
1958 | p4_sync("...", "-f") | |
1959 | else: | |
1960 | p4_sync("...") | |
4f5cf76a | 1961 | self.check() |
4f5cf76a | 1962 | |
4c750c0d | 1963 | commits = [] |
00ad6e31 LD |
1964 | if self.master: |
1965 | commitish = self.master | |
1966 | else: | |
1967 | commitish = 'HEAD' | |
1968 | ||
1969 | for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, commitish)]): | |
4c750c0d SH |
1970 | commits.append(line.strip()) |
1971 | commits.reverse() | |
4f5cf76a | 1972 | |
0d609032 | 1973 | if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"): |
848de9c3 LD |
1974 | self.checkAuthorship = False |
1975 | else: | |
1976 | self.checkAuthorship = True | |
1977 | ||
3ea2cfd4 LD |
1978 | if self.preserveUser: |
1979 | self.checkValidP4Users(commits) | |
1980 | ||
84cb0003 GG |
1981 | # |
1982 | # Build up a set of options to be passed to diff when | |
1983 | # submitting each commit to p4. | |
1984 | # | |
1985 | if self.detectRenames: | |
1986 | # command-line -M arg | |
1987 | self.diffOpts = "-M" | |
1988 | else: | |
1989 | # If not explicitly set check the config variable | |
1990 | detectRenames = gitConfig("git-p4.detectRenames") | |
1991 | ||
1992 | if detectRenames.lower() == "false" or detectRenames == "": | |
1993 | self.diffOpts = "" | |
1994 | elif detectRenames.lower() == "true": | |
1995 | self.diffOpts = "-M" | |
1996 | else: | |
1997 | self.diffOpts = "-M%s" % detectRenames | |
1998 | ||
1999 | # no command-line arg for -C or --find-copies-harder, just | |
2000 | # config variables | |
2001 | detectCopies = gitConfig("git-p4.detectCopies") | |
2002 | if detectCopies.lower() == "false" or detectCopies == "": | |
2003 | pass | |
2004 | elif detectCopies.lower() == "true": | |
2005 | self.diffOpts += " -C" | |
2006 | else: | |
2007 | self.diffOpts += " -C%s" % detectCopies | |
2008 | ||
0d609032 | 2009 | if gitConfigBool("git-p4.detectCopiesHarder"): |
84cb0003 GG |
2010 | self.diffOpts += " --find-copies-harder" |
2011 | ||
7e5dd9f2 PW |
2012 | # |
2013 | # Apply the commits, one at a time. On failure, ask if should | |
2014 | # continue to try the rest of the patches, or quit. | |
2015 | # | |
ef739f08 PW |
2016 | if self.dry_run: |
2017 | print "Would apply" | |
67b0fe2e | 2018 | applied = [] |
7e5dd9f2 PW |
2019 | last = len(commits) - 1 |
2020 | for i, commit in enumerate(commits): | |
ef739f08 PW |
2021 | if self.dry_run: |
2022 | print " ", read_pipe(["git", "show", "-s", | |
2023 | "--format=format:%h %s", commit]) | |
2024 | ok = True | |
2025 | else: | |
2026 | ok = self.applyCommit(commit) | |
67b0fe2e PW |
2027 | if ok: |
2028 | applied.append(commit) | |
7e5dd9f2 | 2029 | else: |
728b7ad8 PW |
2030 | if self.prepare_p4_only and i < last: |
2031 | print "Processing only the first commit due to option" \ | |
2032 | " --prepare-p4-only" | |
2033 | break | |
7e5dd9f2 PW |
2034 | if i < last: |
2035 | quit = False | |
2036 | while True: | |
6bbfd137 PW |
2037 | # prompt for what to do, or use the option/variable |
2038 | if self.conflict_behavior == "ask": | |
2039 | print "What do you want to do?" | |
2040 | response = raw_input("[s]kip this commit but apply" | |
2041 | " the rest, or [q]uit? ") | |
2042 | if not response: | |
2043 | continue | |
2044 | elif self.conflict_behavior == "skip": | |
2045 | response = "s" | |
2046 | elif self.conflict_behavior == "quit": | |
2047 | response = "q" | |
2048 | else: | |
2049 | die("Unknown conflict_behavior '%s'" % | |
2050 | self.conflict_behavior) | |
2051 | ||
7e5dd9f2 PW |
2052 | if response[0] == "s": |
2053 | print "Skipping this commit, but applying the rest" | |
2054 | break | |
2055 | if response[0] == "q": | |
2056 | print "Quitting" | |
2057 | quit = True | |
2058 | break | |
2059 | if quit: | |
2060 | break | |
4f5cf76a | 2061 | |
67b0fe2e | 2062 | chdir(self.oldWorkingDirectory) |
4f5cf76a | 2063 | |
ef739f08 PW |
2064 | if self.dry_run: |
2065 | pass | |
728b7ad8 PW |
2066 | elif self.prepare_p4_only: |
2067 | pass | |
ef739f08 | 2068 | elif len(commits) == len(applied): |
67b0fe2e | 2069 | print "All commits applied!" |
14594f4b | 2070 | |
4c750c0d | 2071 | sync = P4Sync() |
44e8d26c PW |
2072 | if self.branch: |
2073 | sync.branch = self.branch | |
4c750c0d | 2074 | sync.run([]) |
14594f4b | 2075 | |
4c750c0d SH |
2076 | rebase = P4Rebase() |
2077 | rebase.rebase() | |
4f5cf76a | 2078 | |
67b0fe2e PW |
2079 | else: |
2080 | if len(applied) == 0: | |
2081 | print "No commits applied." | |
2082 | else: | |
2083 | print "Applied only the commits marked with '*':" | |
2084 | for c in commits: | |
2085 | if c in applied: | |
2086 | star = "*" | |
2087 | else: | |
2088 | star = " " | |
2089 | print star, read_pipe(["git", "show", "-s", | |
2090 | "--format=format:%h %s", c]) | |
2091 | print "You will have to do 'git p4 sync' and rebase." | |
2092 | ||
0d609032 | 2093 | if gitConfigBool("git-p4.exportLabels"): |
06dcd152 | 2094 | self.exportLabels = True |
06804c76 LD |
2095 | |
2096 | if self.exportLabels: | |
2097 | p4Labels = getP4Labels(self.depotPath) | |
2098 | gitTags = getGitTags() | |
2099 | ||
2100 | missingGitTags = gitTags - p4Labels | |
2101 | self.exportGitTags(missingGitTags) | |
2102 | ||
98e023de | 2103 | # exit with error unless everything applied perfectly |
67b0fe2e PW |
2104 | if len(commits) != len(applied): |
2105 | sys.exit(1) | |
2106 | ||
b984733c SH |
2107 | return True |
2108 | ||
ecb7cf98 PW |
2109 | class View(object): |
2110 | """Represent a p4 view ("p4 help views"), and map files in a | |
2111 | repo according to the view.""" | |
2112 | ||
9d57c4a6 | 2113 | def __init__(self, client_name): |
ecb7cf98 | 2114 | self.mappings = [] |
9d57c4a6 KS |
2115 | self.client_prefix = "//%s/" % client_name |
2116 | # cache results of "p4 where" to lookup client file locations | |
2117 | self.client_spec_path_cache = {} | |
ecb7cf98 PW |
2118 | |
2119 | def append(self, view_line): | |
2120 | """Parse a view line, splitting it into depot and client | |
9d57c4a6 KS |
2121 | sides. Append to self.mappings, preserving order. This |
2122 | is only needed for tag creation.""" | |
ecb7cf98 PW |
2123 | |
2124 | # Split the view line into exactly two words. P4 enforces | |
2125 | # structure on these lines that simplifies this quite a bit. | |
2126 | # | |
2127 | # Either or both words may be double-quoted. | |
2128 | # Single quotes do not matter. | |
2129 | # Double-quote marks cannot occur inside the words. | |
2130 | # A + or - prefix is also inside the quotes. | |
2131 | # There are no quotes unless they contain a space. | |
2132 | # The line is already white-space stripped. | |
2133 | # The two words are separated by a single space. | |
2134 | # | |
2135 | if view_line[0] == '"': | |
2136 | # First word is double quoted. Find its end. | |
2137 | close_quote_index = view_line.find('"', 1) | |
2138 | if close_quote_index <= 0: | |
2139 | die("No first-word closing quote found: %s" % view_line) | |
2140 | depot_side = view_line[1:close_quote_index] | |
2141 | # skip closing quote and space | |
2142 | rhs_index = close_quote_index + 1 + 1 | |
2143 | else: | |
2144 | space_index = view_line.find(" ") | |
2145 | if space_index <= 0: | |
2146 | die("No word-splitting space found: %s" % view_line) | |
2147 | depot_side = view_line[0:space_index] | |
2148 | rhs_index = space_index + 1 | |
2149 | ||
ecb7cf98 | 2150 | # prefix + means overlay on previous mapping |
ecb7cf98 | 2151 | if depot_side.startswith("+"): |
ecb7cf98 PW |
2152 | depot_side = depot_side[1:] |
2153 | ||
9d57c4a6 | 2154 | # prefix - means exclude this path, leave out of mappings |
ecb7cf98 PW |
2155 | exclude = False |
2156 | if depot_side.startswith("-"): | |
2157 | exclude = True | |
2158 | depot_side = depot_side[1:] | |
2159 | ||
9d57c4a6 KS |
2160 | if not exclude: |
2161 | self.mappings.append(depot_side) | |
ecb7cf98 | 2162 | |
9d57c4a6 KS |
2163 | def convert_client_path(self, clientFile): |
2164 | # chop off //client/ part to make it relative | |
2165 | if not clientFile.startswith(self.client_prefix): | |
2166 | die("No prefix '%s' on clientFile '%s'" % | |
2167 | (self.client_prefix, clientFile)) | |
2168 | return clientFile[len(self.client_prefix):] | |
ecb7cf98 | 2169 | |
9d57c4a6 KS |
2170 | def update_client_spec_path_cache(self, files): |
2171 | """ Caching file paths by "p4 where" batch query """ | |
ecb7cf98 | 2172 | |
9d57c4a6 KS |
2173 | # List depot file paths exclude that already cached |
2174 | fileArgs = [f['path'] for f in files if f['path'] not in self.client_spec_path_cache] | |
ecb7cf98 | 2175 | |
9d57c4a6 KS |
2176 | if len(fileArgs) == 0: |
2177 | return # All files in cache | |
ecb7cf98 | 2178 | |
9d57c4a6 KS |
2179 | where_result = p4CmdList(["-x", "-", "where"], stdin=fileArgs) |
2180 | for res in where_result: | |
2181 | if "code" in res and res["code"] == "error": | |
2182 | # assume error is "... file(s) not in client view" | |
2183 | continue | |
2184 | if "clientFile" not in res: | |
20005443 | 2185 | die("No clientFile in 'p4 where' output") |
9d57c4a6 KS |
2186 | if "unmap" in res: |
2187 | # it will list all of them, but only one not unmap-ped | |
2188 | continue | |
a0a50d87 LS |
2189 | if gitConfigBool("core.ignorecase"): |
2190 | res['depotFile'] = res['depotFile'].lower() | |
9d57c4a6 | 2191 | self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"]) |
ecb7cf98 | 2192 | |
9d57c4a6 KS |
2193 | # not found files or unmap files set to "" |
2194 | for depotFile in fileArgs: | |
a0a50d87 LS |
2195 | if gitConfigBool("core.ignorecase"): |
2196 | depotFile = depotFile.lower() | |
9d57c4a6 KS |
2197 | if depotFile not in self.client_spec_path_cache: |
2198 | self.client_spec_path_cache[depotFile] = "" | |
ecb7cf98 | 2199 | |
9d57c4a6 KS |
2200 | def map_in_client(self, depot_path): |
2201 | """Return the relative location in the client where this | |
2202 | depot file should live. Returns "" if the file should | |
2203 | not be mapped in the client.""" | |
ecb7cf98 | 2204 | |
a0a50d87 LS |
2205 | if gitConfigBool("core.ignorecase"): |
2206 | depot_path = depot_path.lower() | |
2207 | ||
9d57c4a6 KS |
2208 | if depot_path in self.client_spec_path_cache: |
2209 | return self.client_spec_path_cache[depot_path] | |
2210 | ||
2211 | die( "Error: %s is not found in client spec path" % depot_path ) | |
2212 | return "" | |
ecb7cf98 | 2213 | |
3ea2cfd4 | 2214 | class P4Sync(Command, P4UserMap): |
56c09345 PW |
2215 | delete_actions = ( "delete", "move/delete", "purge" ) |
2216 | ||
b984733c SH |
2217 | def __init__(self): |
2218 | Command.__init__(self) | |
3ea2cfd4 | 2219 | P4UserMap.__init__(self) |
b984733c SH |
2220 | self.options = [ |
2221 | optparse.make_option("--branch", dest="branch"), | |
2222 | optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"), | |
2223 | optparse.make_option("--changesfile", dest="changesFile"), | |
2224 | optparse.make_option("--silent", dest="silent", action="store_true"), | |
ef48f909 | 2225 | optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"), |
06804c76 | 2226 | optparse.make_option("--import-labels", dest="importLabels", action="store_true"), |
d2c6dd30 HWN |
2227 | optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false", |
2228 | help="Import into refs/heads/ , not refs/remotes"), | |
96b2d54a LS |
2229 | optparse.make_option("--max-changes", dest="maxChanges", |
2230 | help="Maximum number of changes to import"), | |
2231 | optparse.make_option("--changes-block-size", dest="changes_block_size", type="int", | |
2232 | help="Internal block size to use when iteratively calling p4 changes"), | |
86dff6b6 | 2233 | optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true', |
3a70cdfa TAL |
2234 | help="Keep entire BRANCH/DIR/SUBDIR prefix during import"), |
2235 | optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true', | |
51334bb0 LD |
2236 | help="Only sync files that are included in the Perforce Client Spec"), |
2237 | optparse.make_option("-/", dest="cloneExclude", | |
2238 | action="append", type="string", | |
2239 | help="exclude depot path"), | |
b984733c SH |
2240 | ] |
2241 | self.description = """Imports from Perforce into a git repository.\n | |
2242 | example: | |
2243 | //depot/my/project/ -- to import the current head | |
2244 | //depot/my/project/@all -- to import everything | |
2245 | //depot/my/project/@1,6 -- to import only from revision 1 to 6 | |
2246 | ||
2247 | (a ... is not needed in the path p4 specification, it's added implicitly)""" | |
2248 | ||
2249 | self.usage += " //depot/path[@revRange]" | |
b984733c | 2250 | self.silent = False |
1d7367dc RG |
2251 | self.createdBranches = set() |
2252 | self.committedChanges = set() | |
569d1bd4 | 2253 | self.branch = "" |
b984733c | 2254 | self.detectBranches = False |
cb53e1f8 | 2255 | self.detectLabels = False |
06804c76 | 2256 | self.importLabels = False |
b984733c | 2257 | self.changesFile = "" |
01265103 | 2258 | self.syncWithOrigin = True |
a028a98e | 2259 | self.importIntoRemotes = True |
01a9c9c5 | 2260 | self.maxChanges = "" |
1051ef00 | 2261 | self.changes_block_size = None |
8b41a97f | 2262 | self.keepRepoPath = False |
6326aa58 | 2263 | self.depotPaths = None |
3c699645 | 2264 | self.p4BranchesInGit = [] |
354081d5 | 2265 | self.cloneExclude = [] |
3a70cdfa | 2266 | self.useClientSpec = False |
a93d33ee | 2267 | self.useClientSpec_from_options = False |
ecb7cf98 | 2268 | self.clientSpecDirs = None |
fed23693 VA |
2269 | self.tempBranches = [] |
2270 | self.tempBranchLocation = "git-p4-tmp" | |
a5db4b12 LS |
2271 | self.largeFileSystem = None |
2272 | ||
2273 | if gitConfig('git-p4.largeFileSystem'): | |
2274 | largeFileSystemConstructor = globals()[gitConfig('git-p4.largeFileSystem')] | |
2275 | self.largeFileSystem = largeFileSystemConstructor( | |
2276 | lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents) | |
2277 | ) | |
b984733c | 2278 | |
01265103 SH |
2279 | if gitConfig("git-p4.syncFromOrigin") == "false": |
2280 | self.syncWithOrigin = False | |
2281 | ||
51334bb0 LD |
2282 | # This is required for the "append" cloneExclude action |
2283 | def ensure_value(self, attr, value): | |
2284 | if not hasattr(self, attr) or getattr(self, attr) is None: | |
2285 | setattr(self, attr, value) | |
2286 | return getattr(self, attr) | |
2287 | ||
fed23693 VA |
2288 | # Force a checkpoint in fast-import and wait for it to finish |
2289 | def checkpoint(self): | |
2290 | self.gitStream.write("checkpoint\n\n") | |
2291 | self.gitStream.write("progress checkpoint\n\n") | |
2292 | out = self.gitOutput.readline() | |
2293 | if self.verbose: | |
2294 | print "checkpoint finished: " + out | |
2295 | ||
b984733c | 2296 | def extractFilesFromCommit(self, commit): |
354081d5 TT |
2297 | self.cloneExclude = [re.sub(r"\.\.\.$", "", path) |
2298 | for path in self.cloneExclude] | |
b984733c SH |
2299 | files = [] |
2300 | fnum = 0 | |
2301 | while commit.has_key("depotFile%s" % fnum): | |
2302 | path = commit["depotFile%s" % fnum] | |
6326aa58 | 2303 | |
354081d5 | 2304 | if [p for p in self.cloneExclude |
d53de8b9 | 2305 | if p4PathStartsWith(path, p)]: |
354081d5 TT |
2306 | found = False |
2307 | else: | |
2308 | found = [p for p in self.depotPaths | |
d53de8b9 | 2309 | if p4PathStartsWith(path, p)] |
6326aa58 | 2310 | if not found: |
b984733c SH |
2311 | fnum = fnum + 1 |
2312 | continue | |
2313 | ||
2314 | file = {} | |
2315 | file["path"] = path | |
2316 | file["rev"] = commit["rev%s" % fnum] | |
2317 | file["action"] = commit["action%s" % fnum] | |
2318 | file["type"] = commit["type%s" % fnum] | |
2319 | files.append(file) | |
2320 | fnum = fnum + 1 | |
2321 | return files | |
2322 | ||
6326aa58 | 2323 | def stripRepoPath(self, path, prefixes): |
21ef5df4 PW |
2324 | """When streaming files, this is called to map a p4 depot path |
2325 | to where it should go in git. The prefixes are either | |
2326 | self.depotPaths, or self.branchPrefixes in the case of | |
2327 | branch detection.""" | |
2328 | ||
3952710b | 2329 | if self.useClientSpec: |
21ef5df4 PW |
2330 | # branch detection moves files up a level (the branch name) |
2331 | # from what client spec interpretation gives | |
0d1696ef | 2332 | path = self.clientSpecDirs.map_in_client(path) |
21ef5df4 PW |
2333 | if self.detectBranches: |
2334 | for b in self.knownBranches: | |
2335 | if path.startswith(b + "/"): | |
2336 | path = path[len(b)+1:] | |
2337 | ||
2338 | elif self.keepRepoPath: | |
2339 | # Preserve everything in relative path name except leading | |
2340 | # //depot/; just look at first prefix as they all should | |
2341 | # be in the same depot. | |
2342 | depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0]) | |
2343 | if p4PathStartsWith(path, depot): | |
2344 | path = path[len(depot):] | |
3952710b | 2345 | |
0d1696ef | 2346 | else: |
0d1696ef PW |
2347 | for p in prefixes: |
2348 | if p4PathStartsWith(path, p): | |
2349 | path = path[len(p):] | |
21ef5df4 | 2350 | break |
8b41a97f | 2351 | |
0d1696ef | 2352 | path = wildcard_decode(path) |
6326aa58 | 2353 | return path |
6754a299 | 2354 | |
71b112d4 | 2355 | def splitFilesIntoBranches(self, commit): |
21ef5df4 PW |
2356 | """Look at each depotFile in the commit to figure out to what |
2357 | branch it belongs.""" | |
2358 | ||
9d57c4a6 KS |
2359 | if self.clientSpecDirs: |
2360 | files = self.extractFilesFromCommit(commit) | |
2361 | self.clientSpecDirs.update_client_spec_path_cache(files) | |
2362 | ||
d5904674 | 2363 | branches = {} |
71b112d4 SH |
2364 | fnum = 0 |
2365 | while commit.has_key("depotFile%s" % fnum): | |
2366 | path = commit["depotFile%s" % fnum] | |
6326aa58 | 2367 | found = [p for p in self.depotPaths |
d53de8b9 | 2368 | if p4PathStartsWith(path, p)] |
6326aa58 | 2369 | if not found: |
71b112d4 SH |
2370 | fnum = fnum + 1 |
2371 | continue | |
2372 | ||
2373 | file = {} | |
2374 | file["path"] = path | |
2375 | file["rev"] = commit["rev%s" % fnum] | |
2376 | file["action"] = commit["action%s" % fnum] | |
2377 | file["type"] = commit["type%s" % fnum] | |
2378 | fnum = fnum + 1 | |
2379 | ||
21ef5df4 PW |
2380 | # start with the full relative path where this file would |
2381 | # go in a p4 client | |
2382 | if self.useClientSpec: | |
2383 | relPath = self.clientSpecDirs.map_in_client(path) | |
2384 | else: | |
2385 | relPath = self.stripRepoPath(path, self.depotPaths) | |
b984733c | 2386 | |
4b97ffb1 | 2387 | for branch in self.knownBranches.keys(): |
21ef5df4 PW |
2388 | # add a trailing slash so that a commit into qt/4.2foo |
2389 | # doesn't end up in qt/4.2, e.g. | |
6754a299 | 2390 | if relPath.startswith(branch + "/"): |
d5904674 SH |
2391 | if branch not in branches: |
2392 | branches[branch] = [] | |
71b112d4 | 2393 | branches[branch].append(file) |
6555b2cc | 2394 | break |
b984733c SH |
2395 | |
2396 | return branches | |
2397 | ||
a5db4b12 LS |
2398 | def writeToGitStream(self, gitMode, relPath, contents): |
2399 | self.gitStream.write('M %s inline %s\n' % (gitMode, relPath)) | |
2400 | self.gitStream.write('data %d\n' % sum(len(d) for d in contents)) | |
2401 | for d in contents: | |
2402 | self.gitStream.write(d) | |
2403 | self.gitStream.write('\n') | |
2404 | ||
b932705b LD |
2405 | # output one file from the P4 stream |
2406 | # - helper for streamP4Files | |
2407 | ||
2408 | def streamOneP4File(self, file, contents): | |
b932705b LD |
2409 | relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes) |
2410 | if verbose: | |
d2176a50 LS |
2411 | size = int(self.stream_file['fileSize']) |
2412 | sys.stdout.write('\r%s --> %s (%i MB)\n' % (file['depotFile'], relPath, size/1024/1024)) | |
2413 | sys.stdout.flush() | |
b932705b | 2414 | |
9cffb8c8 PW |
2415 | (type_base, type_mods) = split_p4_type(file["type"]) |
2416 | ||
2417 | git_mode = "100644" | |
2418 | if "x" in type_mods: | |
2419 | git_mode = "100755" | |
2420 | if type_base == "symlink": | |
2421 | git_mode = "120000" | |
1292df11 AJ |
2422 | # p4 print on a symlink sometimes contains "target\n"; |
2423 | # if it does, remove the newline | |
b39c3612 | 2424 | data = ''.join(contents) |
40f846c3 PW |
2425 | if not data: |
2426 | # Some version of p4 allowed creating a symlink that pointed | |
2427 | # to nothing. This causes p4 errors when checking out such | |
2428 | # a change, and errors here too. Work around it by ignoring | |
2429 | # the bad symlink; hopefully a future change fixes it. | |
2430 | print "\nIgnoring empty symlink in %s" % file['depotFile'] | |
2431 | return | |
2432 | elif data[-1] == '\n': | |
1292df11 AJ |
2433 | contents = [data[:-1]] |
2434 | else: | |
2435 | contents = [data] | |
b932705b | 2436 | |
9cffb8c8 | 2437 | if type_base == "utf16": |
55aa5714 PW |
2438 | # p4 delivers different text in the python output to -G |
2439 | # than it does when using "print -o", or normal p4 client | |
2440 | # operations. utf16 is converted to ascii or utf8, perhaps. | |
2441 | # But ascii text saved as -t utf16 is completely mangled. | |
2442 | # Invoke print -o to get the real contents. | |
7f0e5962 PW |
2443 | # |
2444 | # On windows, the newlines will always be mangled by print, so put | |
2445 | # them back too. This is not needed to the cygwin windows version, | |
2446 | # just the native "NT" type. | |
2447 | # | |
1f5f3907 LS |
2448 | try: |
2449 | text = p4_read_pipe(['print', '-q', '-o', '-', '%s@%s' % (file['depotFile'], file['change'])]) | |
2450 | except Exception as e: | |
2451 | if 'Translation of file content failed' in str(e): | |
2452 | type_base = 'binary' | |
2453 | else: | |
2454 | raise e | |
2455 | else: | |
2456 | if p4_version_string().find('/NT') >= 0: | |
2457 | text = text.replace('\r\n', '\n') | |
2458 | contents = [ text ] | |
55aa5714 | 2459 | |
9f7ef0ea PW |
2460 | if type_base == "apple": |
2461 | # Apple filetype files will be streamed as a concatenation of | |
2462 | # its appledouble header and the contents. This is useless | |
2463 | # on both macs and non-macs. If using "print -q -o xx", it | |
2464 | # will create "xx" with the data, and "%xx" with the header. | |
2465 | # This is also not very useful. | |
2466 | # | |
2467 | # Ideally, someday, this script can learn how to generate | |
2468 | # appledouble files directly and import those to git, but | |
2469 | # non-mac machines can never find a use for apple filetype. | |
2470 | print "\nIgnoring apple filetype file %s" % file['depotFile'] | |
2471 | return | |
2472 | ||
55aa5714 PW |
2473 | # Note that we do not try to de-mangle keywords on utf16 files, |
2474 | # even though in theory somebody may want that. | |
60df071c LD |
2475 | pattern = p4_keywords_regexp_for_type(type_base, type_mods) |
2476 | if pattern: | |
2477 | regexp = re.compile(pattern, re.VERBOSE) | |
2478 | text = ''.join(contents) | |
2479 | text = regexp.sub(r'$\1$', text) | |
2480 | contents = [ text ] | |
b932705b | 2481 | |
00a9403a LS |
2482 | try: |
2483 | relPath.decode('ascii') | |
2484 | except: | |
2485 | encoding = 'utf8' | |
2486 | if gitConfig('git-p4.pathEncoding'): | |
2487 | encoding = gitConfig('git-p4.pathEncoding') | |
4cb870d8 | 2488 | relPath = relPath.decode(encoding, 'replace').encode('utf8', 'replace') |
00a9403a LS |
2489 | if self.verbose: |
2490 | print 'Path with non-ASCII characters detected. Used %s to encode: %s ' % (encoding, relPath) | |
a9e38359 | 2491 | |
a5db4b12 LS |
2492 | if self.largeFileSystem: |
2493 | (git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents) | |
b932705b | 2494 | |
a5db4b12 | 2495 | self.writeToGitStream(git_mode, relPath, contents) |
b932705b LD |
2496 | |
2497 | def streamOneP4Deletion(self, file): | |
2498 | relPath = self.stripRepoPath(file['path'], self.branchPrefixes) | |
2499 | if verbose: | |
d2176a50 LS |
2500 | sys.stdout.write("delete %s\n" % relPath) |
2501 | sys.stdout.flush() | |
b932705b LD |
2502 | self.gitStream.write("D %s\n" % relPath) |
2503 | ||
a5db4b12 LS |
2504 | if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath): |
2505 | self.largeFileSystem.removeLargeFile(relPath) | |
2506 | ||
b932705b LD |
2507 | # handle another chunk of streaming data |
2508 | def streamP4FilesCb(self, marshalled): | |
2509 | ||
78189bea PW |
2510 | # catch p4 errors and complain |
2511 | err = None | |
2512 | if "code" in marshalled: | |
2513 | if marshalled["code"] == "error": | |
2514 | if "data" in marshalled: | |
2515 | err = marshalled["data"].rstrip() | |
4d25dc44 LS |
2516 | |
2517 | if not err and 'fileSize' in self.stream_file: | |
2518 | required_bytes = int((4 * int(self.stream_file["fileSize"])) - calcDiskFree()) | |
2519 | if required_bytes > 0: | |
2520 | err = 'Not enough space left on %s! Free at least %i MB.' % ( | |
2521 | os.getcwd(), required_bytes/1024/1024 | |
2522 | ) | |
2523 | ||
78189bea PW |
2524 | if err: |
2525 | f = None | |
2526 | if self.stream_have_file_info: | |
2527 | if "depotFile" in self.stream_file: | |
2528 | f = self.stream_file["depotFile"] | |
2529 | # force a failure in fast-import, else an empty | |
2530 | # commit will be made | |
2531 | self.gitStream.write("\n") | |
2532 | self.gitStream.write("die-now\n") | |
2533 | self.gitStream.close() | |
2534 | # ignore errors, but make sure it exits first | |
2535 | self.importProcess.wait() | |
2536 | if f: | |
2537 | die("Error from p4 print for %s: %s" % (f, err)) | |
2538 | else: | |
2539 | die("Error from p4 print: %s" % err) | |
2540 | ||
c3f6163b AG |
2541 | if marshalled.has_key('depotFile') and self.stream_have_file_info: |
2542 | # start of a new file - output the old one first | |
2543 | self.streamOneP4File(self.stream_file, self.stream_contents) | |
2544 | self.stream_file = {} | |
2545 | self.stream_contents = [] | |
2546 | self.stream_have_file_info = False | |
b932705b | 2547 | |
c3f6163b AG |
2548 | # pick up the new file information... for the |
2549 | # 'data' field we need to append to our array | |
2550 | for k in marshalled.keys(): | |
2551 | if k == 'data': | |
d2176a50 LS |
2552 | if 'streamContentSize' not in self.stream_file: |
2553 | self.stream_file['streamContentSize'] = 0 | |
2554 | self.stream_file['streamContentSize'] += len(marshalled['data']) | |
c3f6163b AG |
2555 | self.stream_contents.append(marshalled['data']) |
2556 | else: | |
2557 | self.stream_file[k] = marshalled[k] | |
b932705b | 2558 | |
d2176a50 LS |
2559 | if (verbose and |
2560 | 'streamContentSize' in self.stream_file and | |
2561 | 'fileSize' in self.stream_file and | |
2562 | 'depotFile' in self.stream_file): | |
2563 | size = int(self.stream_file["fileSize"]) | |
2564 | if size > 0: | |
2565 | progress = 100*self.stream_file['streamContentSize']/size | |
2566 | sys.stdout.write('\r%s %d%% (%i MB)' % (self.stream_file['depotFile'], progress, int(size/1024/1024))) | |
2567 | sys.stdout.flush() | |
2568 | ||
c3f6163b | 2569 | self.stream_have_file_info = True |
b932705b LD |
2570 | |
2571 | # Stream directly from "p4 files" into "git fast-import" | |
2572 | def streamP4Files(self, files): | |
30b5940b SH |
2573 | filesForCommit = [] |
2574 | filesToRead = [] | |
b932705b | 2575 | filesToDelete = [] |
30b5940b | 2576 | |
3a70cdfa | 2577 | for f in files: |
ecb7cf98 PW |
2578 | filesForCommit.append(f) |
2579 | if f['action'] in self.delete_actions: | |
2580 | filesToDelete.append(f) | |
2581 | else: | |
2582 | filesToRead.append(f) | |
6a49f8e2 | 2583 | |
b932705b LD |
2584 | # deleted files... |
2585 | for f in filesToDelete: | |
2586 | self.streamOneP4Deletion(f) | |
1b9a4684 | 2587 | |
b932705b LD |
2588 | if len(filesToRead) > 0: |
2589 | self.stream_file = {} | |
2590 | self.stream_contents = [] | |
2591 | self.stream_have_file_info = False | |
8ff45f2a | 2592 | |
c3f6163b AG |
2593 | # curry self argument |
2594 | def streamP4FilesCbSelf(entry): | |
2595 | self.streamP4FilesCb(entry) | |
6a49f8e2 | 2596 | |
6de040df LD |
2597 | fileArgs = ['%s#%s' % (f['path'], f['rev']) for f in filesToRead] |
2598 | ||
2599 | p4CmdList(["-x", "-", "print"], | |
2600 | stdin=fileArgs, | |
2601 | cb=streamP4FilesCbSelf) | |
30b5940b | 2602 | |
b932705b LD |
2603 | # do the last chunk |
2604 | if self.stream_file.has_key('depotFile'): | |
2605 | self.streamOneP4File(self.stream_file, self.stream_contents) | |
6a49f8e2 | 2606 | |
affb474f LD |
2607 | def make_email(self, userid): |
2608 | if userid in self.users: | |
2609 | return self.users[userid] | |
2610 | else: | |
2611 | return "%s <a@b>" % userid | |
2612 | ||
06804c76 | 2613 | def streamTag(self, gitStream, labelName, labelDetails, commit, epoch): |
b43702ac LD |
2614 | """ Stream a p4 tag. |
2615 | commit is either a git commit, or a fast-import mark, ":<p4commit>" | |
2616 | """ | |
2617 | ||
06804c76 LD |
2618 | if verbose: |
2619 | print "writing tag %s for commit %s" % (labelName, commit) | |
2620 | gitStream.write("tag %s\n" % labelName) | |
2621 | gitStream.write("from %s\n" % commit) | |
2622 | ||
2623 | if labelDetails.has_key('Owner'): | |
2624 | owner = labelDetails["Owner"] | |
2625 | else: | |
2626 | owner = None | |
2627 | ||
2628 | # Try to use the owner of the p4 label, or failing that, | |
2629 | # the current p4 user id. | |
2630 | if owner: | |
2631 | email = self.make_email(owner) | |
2632 | else: | |
2633 | email = self.make_email(self.p4UserId()) | |
2634 | tagger = "%s %s %s" % (email, epoch, self.tz) | |
2635 | ||
2636 | gitStream.write("tagger %s\n" % tagger) | |
2637 | ||
2638 | print "labelDetails=",labelDetails | |
2639 | if labelDetails.has_key('Description'): | |
2640 | description = labelDetails['Description'] | |
2641 | else: | |
2642 | description = 'Label from git p4' | |
2643 | ||
2644 | gitStream.write("data %d\n" % len(description)) | |
2645 | gitStream.write(description) | |
2646 | gitStream.write("\n") | |
2647 | ||
4ae048e6 LS |
2648 | def inClientSpec(self, path): |
2649 | if not self.clientSpecDirs: | |
2650 | return True | |
2651 | inClientSpec = self.clientSpecDirs.map_in_client(path) | |
2652 | if not inClientSpec and self.verbose: | |
2653 | print('Ignoring file outside of client spec: {0}'.format(path)) | |
2654 | return inClientSpec | |
2655 | ||
2656 | def hasBranchPrefix(self, path): | |
2657 | if not self.branchPrefixes: | |
2658 | return True | |
2659 | hasPrefix = [p for p in self.branchPrefixes | |
2660 | if p4PathStartsWith(path, p)] | |
2661 | if hasPrefix and self.verbose: | |
2662 | print('Ignoring file outside of prefix: {0}'.format(path)) | |
2663 | return hasPrefix | |
2664 | ||
e63231e5 | 2665 | def commit(self, details, files, branch, parent = ""): |
b984733c SH |
2666 | epoch = details["time"] |
2667 | author = details["user"] | |
2668 | ||
4b97ffb1 | 2669 | if self.verbose: |
4ae048e6 | 2670 | print('commit into {0}'.format(branch)) |
96e07dd2 | 2671 | |
9d57c4a6 KS |
2672 | if self.clientSpecDirs: |
2673 | self.clientSpecDirs.update_client_spec_path_cache(files) | |
2674 | ||
4ae048e6 LS |
2675 | files = [f for f in files |
2676 | if self.inClientSpec(f['path']) and self.hasBranchPrefix(f['path'])] | |
2677 | ||
2678 | if not files and not gitConfigBool('git-p4.keepEmptyCommits'): | |
2679 | print('Ignoring revision {0} as it would produce an empty commit.' | |
2680 | .format(details['change'])) | |
2681 | return | |
2682 | ||
b984733c | 2683 | self.gitStream.write("commit %s\n" % branch) |
b43702ac | 2684 | self.gitStream.write("mark :%s\n" % details["change"]) |
b984733c SH |
2685 | self.committedChanges.add(int(details["change"])) |
2686 | committer = "" | |
b607e71e SH |
2687 | if author not in self.users: |
2688 | self.getUserMapFromPerforceServer() | |
affb474f | 2689 | committer = "%s %s %s" % (self.make_email(author), epoch, self.tz) |
b984733c SH |
2690 | |
2691 | self.gitStream.write("committer %s\n" % committer) | |
2692 | ||
2693 | self.gitStream.write("data <<EOT\n") | |
2694 | self.gitStream.write(details["desc"]) | |
e63231e5 PW |
2695 | self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" % |
2696 | (','.join(self.branchPrefixes), details["change"])) | |
6581de09 SH |
2697 | if len(details['options']) > 0: |
2698 | self.gitStream.write(": options = %s" % details['options']) | |
2699 | self.gitStream.write("]\nEOT\n\n") | |
b984733c SH |
2700 | |
2701 | if len(parent) > 0: | |
4b97ffb1 SH |
2702 | if self.verbose: |
2703 | print "parent %s" % parent | |
b984733c SH |
2704 | self.gitStream.write("from %s\n" % parent) |
2705 | ||
4ae048e6 | 2706 | self.streamP4Files(files) |
b984733c SH |
2707 | self.gitStream.write("\n") |
2708 | ||
1f4ba1cb SH |
2709 | change = int(details["change"]) |
2710 | ||
9bda3a85 | 2711 | if self.labels.has_key(change): |
1f4ba1cb SH |
2712 | label = self.labels[change] |
2713 | labelDetails = label[0] | |
2714 | labelRevisions = label[1] | |
71b112d4 SH |
2715 | if self.verbose: |
2716 | print "Change %s is labelled %s" % (change, labelDetails) | |
1f4ba1cb | 2717 | |
6de040df | 2718 | files = p4CmdList(["files"] + ["%s...@%s" % (p, change) |
e63231e5 | 2719 | for p in self.branchPrefixes]) |
1f4ba1cb SH |
2720 | |
2721 | if len(files) == len(labelRevisions): | |
2722 | ||
2723 | cleanedFiles = {} | |
2724 | for info in files: | |
56c09345 | 2725 | if info["action"] in self.delete_actions: |
1f4ba1cb SH |
2726 | continue |
2727 | cleanedFiles[info["depotFile"]] = info["rev"] | |
2728 | ||
2729 | if cleanedFiles == labelRevisions: | |
06804c76 | 2730 | self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch) |
1f4ba1cb SH |
2731 | |
2732 | else: | |
a46668fa | 2733 | if not self.silent: |
cebdf5af HWN |
2734 | print ("Tag %s does not match with change %s: files do not match." |
2735 | % (labelDetails["label"], change)) | |
1f4ba1cb SH |
2736 | |
2737 | else: | |
a46668fa | 2738 | if not self.silent: |
cebdf5af HWN |
2739 | print ("Tag %s does not match with change %s: file count is different." |
2740 | % (labelDetails["label"], change)) | |
b984733c | 2741 | |
06804c76 | 2742 | # Build a dictionary of changelists and labels, for "detect-labels" option. |
1f4ba1cb SH |
2743 | def getLabels(self): |
2744 | self.labels = {} | |
2745 | ||
52a4880b | 2746 | l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths]) |
10c3211b | 2747 | if len(l) > 0 and not self.silent: |
183f8436 | 2748 | print "Finding files belonging to labels in %s" % `self.depotPaths` |
01ce1fe9 SH |
2749 | |
2750 | for output in l: | |
1f4ba1cb SH |
2751 | label = output["label"] |
2752 | revisions = {} | |
2753 | newestChange = 0 | |
71b112d4 SH |
2754 | if self.verbose: |
2755 | print "Querying files for label %s" % label | |
6de040df LD |
2756 | for file in p4CmdList(["files"] + |
2757 | ["%s...@%s" % (p, label) | |
2758 | for p in self.depotPaths]): | |
1f4ba1cb SH |
2759 | revisions[file["depotFile"]] = file["rev"] |
2760 | change = int(file["change"]) | |
2761 | if change > newestChange: | |
2762 | newestChange = change | |
2763 | ||
9bda3a85 SH |
2764 | self.labels[newestChange] = [output, revisions] |
2765 | ||
2766 | if self.verbose: | |
2767 | print "Label changes: %s" % self.labels.keys() | |
1f4ba1cb | 2768 | |
06804c76 LD |
2769 | # Import p4 labels as git tags. A direct mapping does not |
2770 | # exist, so assume that if all the files are at the same revision | |
2771 | # then we can use that, or it's something more complicated we should | |
2772 | # just ignore. | |
2773 | def importP4Labels(self, stream, p4Labels): | |
2774 | if verbose: | |
2775 | print "import p4 labels: " + ' '.join(p4Labels) | |
2776 | ||
2777 | ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels") | |
c8942a22 | 2778 | validLabelRegexp = gitConfig("git-p4.labelImportRegexp") |
06804c76 LD |
2779 | if len(validLabelRegexp) == 0: |
2780 | validLabelRegexp = defaultLabelRegexp | |
2781 | m = re.compile(validLabelRegexp) | |
2782 | ||
2783 | for name in p4Labels: | |
2784 | commitFound = False | |
2785 | ||
2786 | if not m.match(name): | |
2787 | if verbose: | |
2788 | print "label %s does not match regexp %s" % (name,validLabelRegexp) | |
2789 | continue | |
2790 | ||
2791 | if name in ignoredP4Labels: | |
2792 | continue | |
2793 | ||
2794 | labelDetails = p4CmdList(['label', "-o", name])[0] | |
2795 | ||
2796 | # get the most recent changelist for each file in this label | |
2797 | change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name) | |
2798 | for p in self.depotPaths]) | |
2799 | ||
2800 | if change.has_key('change'): | |
2801 | # find the corresponding git commit; take the oldest commit | |
2802 | changelist = int(change['change']) | |
b43702ac LD |
2803 | if changelist in self.committedChanges: |
2804 | gitCommit = ":%d" % changelist # use a fast-import mark | |
06804c76 | 2805 | commitFound = True |
b43702ac LD |
2806 | else: |
2807 | gitCommit = read_pipe(["git", "rev-list", "--max-count=1", | |
2808 | "--reverse", ":/\[git-p4:.*change = %d\]" % changelist], ignore_error=True) | |
2809 | if len(gitCommit) == 0: | |
2810 | print "importing label %s: could not find git commit for changelist %d" % (name, changelist) | |
2811 | else: | |
2812 | commitFound = True | |
2813 | gitCommit = gitCommit.strip() | |
2814 | ||
2815 | if commitFound: | |
06804c76 LD |
2816 | # Convert from p4 time format |
2817 | try: | |
2818 | tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S") | |
2819 | except ValueError: | |
a4e9054c | 2820 | print "Could not convert label time %s" % labelDetails['Update'] |
06804c76 LD |
2821 | tmwhen = 1 |
2822 | ||
2823 | when = int(time.mktime(tmwhen)) | |
2824 | self.streamTag(stream, name, labelDetails, gitCommit, when) | |
2825 | if verbose: | |
2826 | print "p4 label %s mapped to git commit %s" % (name, gitCommit) | |
2827 | else: | |
2828 | if verbose: | |
2829 | print "Label %s has no changelists - possibly deleted?" % name | |
2830 | ||
2831 | if not commitFound: | |
2832 | # We can't import this label; don't try again as it will get very | |
2833 | # expensive repeatedly fetching all the files for labels that will | |
2834 | # never be imported. If the label is moved in the future, the | |
2835 | # ignore will need to be removed manually. | |
2836 | system(["git", "config", "--add", "git-p4.ignoredP4Labels", name]) | |
2837 | ||
86dff6b6 HWN |
2838 | def guessProjectName(self): |
2839 | for p in self.depotPaths: | |
6e5295c4 SH |
2840 | if p.endswith("/"): |
2841 | p = p[:-1] | |
2842 | p = p[p.strip().rfind("/") + 1:] | |
2843 | if not p.endswith("/"): | |
2844 | p += "/" | |
2845 | return p | |
86dff6b6 | 2846 | |
4b97ffb1 | 2847 | def getBranchMapping(self): |
6555b2cc SH |
2848 | lostAndFoundBranches = set() |
2849 | ||
8ace74c0 VA |
2850 | user = gitConfig("git-p4.branchUser") |
2851 | if len(user) > 0: | |
2852 | command = "branches -u %s" % user | |
2853 | else: | |
2854 | command = "branches" | |
2855 | ||
2856 | for info in p4CmdList(command): | |
52a4880b | 2857 | details = p4Cmd(["branch", "-o", info["branch"]]) |
4b97ffb1 SH |
2858 | viewIdx = 0 |
2859 | while details.has_key("View%s" % viewIdx): | |
2860 | paths = details["View%s" % viewIdx].split(" ") | |
2861 | viewIdx = viewIdx + 1 | |
2862 | # require standard //depot/foo/... //depot/bar/... mapping | |
2863 | if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."): | |
2864 | continue | |
2865 | source = paths[0] | |
2866 | destination = paths[1] | |
6509e19c | 2867 | ## HACK |
d53de8b9 | 2868 | if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]): |
6509e19c SH |
2869 | source = source[len(self.depotPaths[0]):-4] |
2870 | destination = destination[len(self.depotPaths[0]):-4] | |
6555b2cc | 2871 | |
1a2edf4e SH |
2872 | if destination in self.knownBranches: |
2873 | if not self.silent: | |
2874 | print "p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination) | |
2875 | print "but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination) | |
2876 | continue | |
2877 | ||
6555b2cc SH |
2878 | self.knownBranches[destination] = source |
2879 | ||
2880 | lostAndFoundBranches.discard(destination) | |
2881 | ||
29bdbac1 | 2882 | if source not in self.knownBranches: |
6555b2cc SH |
2883 | lostAndFoundBranches.add(source) |
2884 | ||
7199cf13 VA |
2885 | # Perforce does not strictly require branches to be defined, so we also |
2886 | # check git config for a branch list. | |
2887 | # | |
2888 | # Example of branch definition in git config file: | |
2889 | # [git-p4] | |
2890 | # branchList=main:branchA | |
2891 | # branchList=main:branchB | |
2892 | # branchList=branchA:branchC | |
2893 | configBranches = gitConfigList("git-p4.branchList") | |
2894 | for branch in configBranches: | |
2895 | if branch: | |
2896 | (source, destination) = branch.split(":") | |
2897 | self.knownBranches[destination] = source | |
2898 | ||
2899 | lostAndFoundBranches.discard(destination) | |
2900 | ||
2901 | if source not in self.knownBranches: | |
2902 | lostAndFoundBranches.add(source) | |
2903 | ||
6555b2cc SH |
2904 | |
2905 | for branch in lostAndFoundBranches: | |
2906 | self.knownBranches[branch] = branch | |
29bdbac1 | 2907 | |
38f9f5ec SH |
2908 | def getBranchMappingFromGitBranches(self): |
2909 | branches = p4BranchesInGit(self.importIntoRemotes) | |
2910 | for branch in branches.keys(): | |
2911 | if branch == "master": | |
2912 | branch = "main" | |
2913 | else: | |
2914 | branch = branch[len(self.projectName):] | |
2915 | self.knownBranches[branch] = branch | |
2916 | ||
bb6e09b2 HWN |
2917 | def updateOptionDict(self, d): |
2918 | option_keys = {} | |
2919 | if self.keepRepoPath: | |
2920 | option_keys['keepRepoPath'] = 1 | |
2921 | ||
2922 | d["options"] = ' '.join(sorted(option_keys.keys())) | |
2923 | ||
2924 | def readOptions(self, d): | |
2925 | self.keepRepoPath = (d.has_key('options') | |
2926 | and ('keepRepoPath' in d['options'])) | |
6326aa58 | 2927 | |
8134f69c SH |
2928 | def gitRefForBranch(self, branch): |
2929 | if branch == "main": | |
2930 | return self.refPrefix + "master" | |
2931 | ||
2932 | if len(branch) <= 0: | |
2933 | return branch | |
2934 | ||
2935 | return self.refPrefix + self.projectName + branch | |
2936 | ||
1ca3d710 SH |
2937 | def gitCommitByP4Change(self, ref, change): |
2938 | if self.verbose: | |
2939 | print "looking in ref " + ref + " for change %s using bisect..." % change | |
2940 | ||
2941 | earliestCommit = "" | |
2942 | latestCommit = parseRevision(ref) | |
2943 | ||
2944 | while True: | |
2945 | if self.verbose: | |
2946 | print "trying: earliest %s latest %s" % (earliestCommit, latestCommit) | |
2947 | next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip() | |
2948 | if len(next) == 0: | |
2949 | if self.verbose: | |
2950 | print "argh" | |
2951 | return "" | |
2952 | log = extractLogMessageFromGitCommit(next) | |
2953 | settings = extractSettingsGitLog(log) | |
2954 | currentChange = int(settings['change']) | |
2955 | if self.verbose: | |
2956 | print "current change %s" % currentChange | |
2957 | ||
2958 | if currentChange == change: | |
2959 | if self.verbose: | |
2960 | print "found %s" % next | |
2961 | return next | |
2962 | ||
2963 | if currentChange < change: | |
2964 | earliestCommit = "^%s" % next | |
2965 | else: | |
2966 | latestCommit = "%s" % next | |
2967 | ||
2968 | return "" | |
2969 | ||
2970 | def importNewBranch(self, branch, maxChange): | |
2971 | # make fast-import flush all changes to disk and update the refs using the checkpoint | |
2972 | # command so that we can try to find the branch parent in the git history | |
2973 | self.gitStream.write("checkpoint\n\n"); | |
2974 | self.gitStream.flush(); | |
2975 | branchPrefix = self.depotPaths[0] + branch + "/" | |
2976 | range = "@1,%s" % maxChange | |
2977 | #print "prefix" + branchPrefix | |
96b2d54a | 2978 | changes = p4ChangesForPaths([branchPrefix], range, self.changes_block_size) |
1ca3d710 SH |
2979 | if len(changes) <= 0: |
2980 | return False | |
2981 | firstChange = changes[0] | |
2982 | #print "first change in branch: %s" % firstChange | |
2983 | sourceBranch = self.knownBranches[branch] | |
2984 | sourceDepotPath = self.depotPaths[0] + sourceBranch | |
2985 | sourceRef = self.gitRefForBranch(sourceBranch) | |
2986 | #print "source " + sourceBranch | |
2987 | ||
52a4880b | 2988 | branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"]) |
1ca3d710 SH |
2989 | #print "branch parent: %s" % branchParentChange |
2990 | gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange) | |
2991 | if len(gitParent) > 0: | |
2992 | self.initialParents[self.gitRefForBranch(branch)] = gitParent | |
2993 | #print "parent git commit: %s" % gitParent | |
2994 | ||
2995 | self.importChanges(changes) | |
2996 | return True | |
2997 | ||
fed23693 VA |
2998 | def searchParent(self, parent, branch, target): |
2999 | parentFound = False | |
c7d34884 PW |
3000 | for blob in read_pipe_lines(["git", "rev-list", "--reverse", |
3001 | "--no-merges", parent]): | |
fed23693 VA |
3002 | blob = blob.strip() |
3003 | if len(read_pipe(["git", "diff-tree", blob, target])) == 0: | |
3004 | parentFound = True | |
3005 | if self.verbose: | |
3006 | print "Found parent of %s in commit %s" % (branch, blob) | |
3007 | break | |
3008 | if parentFound: | |
3009 | return blob | |
3010 | else: | |
3011 | return None | |
3012 | ||
e87f37ae SH |
3013 | def importChanges(self, changes): |
3014 | cnt = 1 | |
3015 | for change in changes: | |
18fa13d0 | 3016 | description = p4_describe(change) |
e87f37ae SH |
3017 | self.updateOptionDict(description) |
3018 | ||
3019 | if not self.silent: | |
3020 | sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes))) | |
3021 | sys.stdout.flush() | |
3022 | cnt = cnt + 1 | |
3023 | ||
3024 | try: | |
3025 | if self.detectBranches: | |
3026 | branches = self.splitFilesIntoBranches(description) | |
3027 | for branch in branches.keys(): | |
3028 | ## HACK --hwn | |
3029 | branchPrefix = self.depotPaths[0] + branch + "/" | |
e63231e5 | 3030 | self.branchPrefixes = [ branchPrefix ] |
e87f37ae SH |
3031 | |
3032 | parent = "" | |
3033 | ||
3034 | filesForCommit = branches[branch] | |
3035 | ||
3036 | if self.verbose: | |
3037 | print "branch is %s" % branch | |
3038 | ||
3039 | self.updatedBranches.add(branch) | |
3040 | ||
3041 | if branch not in self.createdBranches: | |
3042 | self.createdBranches.add(branch) | |
3043 | parent = self.knownBranches[branch] | |
3044 | if parent == branch: | |
3045 | parent = "" | |
1ca3d710 SH |
3046 | else: |
3047 | fullBranch = self.projectName + branch | |
3048 | if fullBranch not in self.p4BranchesInGit: | |
3049 | if not self.silent: | |
3050 | print("\n Importing new branch %s" % fullBranch); | |
3051 | if self.importNewBranch(branch, change - 1): | |
3052 | parent = "" | |
3053 | self.p4BranchesInGit.append(fullBranch) | |
3054 | if not self.silent: | |
3055 | print("\n Resuming with change %s" % change); | |
3056 | ||
3057 | if self.verbose: | |
3058 | print "parent determined through known branches: %s" % parent | |
e87f37ae | 3059 | |
8134f69c SH |
3060 | branch = self.gitRefForBranch(branch) |
3061 | parent = self.gitRefForBranch(parent) | |
e87f37ae SH |
3062 | |
3063 | if self.verbose: | |
3064 | print "looking for initial parent for %s; current parent is %s" % (branch, parent) | |
3065 | ||
3066 | if len(parent) == 0 and branch in self.initialParents: | |
3067 | parent = self.initialParents[branch] | |
3068 | del self.initialParents[branch] | |
3069 | ||
fed23693 VA |
3070 | blob = None |
3071 | if len(parent) > 0: | |
4f9273d2 | 3072 | tempBranch = "%s/%d" % (self.tempBranchLocation, change) |
fed23693 VA |
3073 | if self.verbose: |
3074 | print "Creating temporary branch: " + tempBranch | |
e63231e5 | 3075 | self.commit(description, filesForCommit, tempBranch) |
fed23693 VA |
3076 | self.tempBranches.append(tempBranch) |
3077 | self.checkpoint() | |
3078 | blob = self.searchParent(parent, branch, tempBranch) | |
3079 | if blob: | |
e63231e5 | 3080 | self.commit(description, filesForCommit, branch, blob) |
fed23693 VA |
3081 | else: |
3082 | if self.verbose: | |
3083 | print "Parent of %s not found. Committing into head of %s" % (branch, parent) | |
e63231e5 | 3084 | self.commit(description, filesForCommit, branch, parent) |
e87f37ae SH |
3085 | else: |
3086 | files = self.extractFilesFromCommit(description) | |
e63231e5 | 3087 | self.commit(description, files, self.branch, |
e87f37ae | 3088 | self.initialParent) |
47497844 | 3089 | # only needed once, to connect to the previous commit |
e87f37ae SH |
3090 | self.initialParent = "" |
3091 | except IOError: | |
3092 | print self.gitError.read() | |
3093 | sys.exit(1) | |
3094 | ||
c208a243 SH |
3095 | def importHeadRevision(self, revision): |
3096 | print "Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch) | |
3097 | ||
4e2e6ce4 PW |
3098 | details = {} |
3099 | details["user"] = "git perforce import user" | |
1494fcbb | 3100 | details["desc"] = ("Initial import of %s from the state at revision %s\n" |
c208a243 SH |
3101 | % (' '.join(self.depotPaths), revision)) |
3102 | details["change"] = revision | |
3103 | newestRevision = 0 | |
3104 | ||
3105 | fileCnt = 0 | |
6de040df LD |
3106 | fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths] |
3107 | ||
3108 | for info in p4CmdList(["files"] + fileArgs): | |
c208a243 | 3109 | |
68b28593 | 3110 | if 'code' in info and info['code'] == 'error': |
c208a243 SH |
3111 | sys.stderr.write("p4 returned an error: %s\n" |
3112 | % info['data']) | |
d88e707f PW |
3113 | if info['data'].find("must refer to client") >= 0: |
3114 | sys.stderr.write("This particular p4 error is misleading.\n") | |
3115 | sys.stderr.write("Perhaps the depot path was misspelled.\n"); | |
3116 | sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths)) | |
c208a243 | 3117 | sys.exit(1) |
68b28593 PW |
3118 | if 'p4ExitCode' in info: |
3119 | sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode']) | |
c208a243 SH |
3120 | sys.exit(1) |
3121 | ||
3122 | ||
3123 | change = int(info["change"]) | |
3124 | if change > newestRevision: | |
3125 | newestRevision = change | |
3126 | ||
56c09345 | 3127 | if info["action"] in self.delete_actions: |
c208a243 SH |
3128 | # don't increase the file cnt, otherwise details["depotFile123"] will have gaps! |
3129 | #fileCnt = fileCnt + 1 | |
3130 | continue | |
3131 | ||
3132 | for prop in ["depotFile", "rev", "action", "type" ]: | |
3133 | details["%s%s" % (prop, fileCnt)] = info[prop] | |
3134 | ||
3135 | fileCnt = fileCnt + 1 | |
3136 | ||
3137 | details["change"] = newestRevision | |
4e2e6ce4 | 3138 | |
9dcb9f24 | 3139 | # Use time from top-most change so that all git p4 clones of |
4e2e6ce4 | 3140 | # the same p4 repo have the same commit SHA1s. |
18fa13d0 PW |
3141 | res = p4_describe(newestRevision) |
3142 | details["time"] = res["time"] | |
4e2e6ce4 | 3143 | |
c208a243 SH |
3144 | self.updateOptionDict(details) |
3145 | try: | |
e63231e5 | 3146 | self.commit(details, self.extractFilesFromCommit(details), self.branch) |
c208a243 SH |
3147 | except IOError: |
3148 | print "IO error with git fast-import. Is your git version recent enough?" | |
3149 | print self.gitError.read() | |
3150 | ||
3151 | ||
b984733c | 3152 | def run(self, args): |
6326aa58 | 3153 | self.depotPaths = [] |
179caebf | 3154 | self.changeRange = "" |
6326aa58 | 3155 | self.previousDepotPaths = [] |
991a2de4 | 3156 | self.hasOrigin = False |
ce6f33c8 | 3157 | |
29bdbac1 SH |
3158 | # map from branch depot path to parent branch |
3159 | self.knownBranches = {} | |
3160 | self.initialParents = {} | |
3161 | ||
a028a98e SH |
3162 | if self.importIntoRemotes: |
3163 | self.refPrefix = "refs/remotes/p4/" | |
3164 | else: | |
db775559 | 3165 | self.refPrefix = "refs/heads/p4/" |
a028a98e | 3166 | |
991a2de4 PW |
3167 | if self.syncWithOrigin: |
3168 | self.hasOrigin = originP4BranchesExist() | |
3169 | if self.hasOrigin: | |
3170 | if not self.silent: | |
3171 | print 'Syncing with origin first, using "git fetch origin"' | |
3172 | system("git fetch origin") | |
10f880f8 | 3173 | |
5a8e84cd | 3174 | branch_arg_given = bool(self.branch) |
569d1bd4 | 3175 | if len(self.branch) == 0: |
db775559 | 3176 | self.branch = self.refPrefix + "master" |
a028a98e | 3177 | if gitBranchExists("refs/heads/p4") and self.importIntoRemotes: |
48df6fd8 | 3178 | system("git update-ref %s refs/heads/p4" % self.branch) |
55d12437 | 3179 | system("git branch -D p4") |
967f72e2 | 3180 | |
a93d33ee PW |
3181 | # accept either the command-line option, or the configuration variable |
3182 | if self.useClientSpec: | |
3183 | # will use this after clone to set the variable | |
3184 | self.useClientSpec_from_options = True | |
3185 | else: | |
0d609032 | 3186 | if gitConfigBool("git-p4.useclientspec"): |
09fca77b PW |
3187 | self.useClientSpec = True |
3188 | if self.useClientSpec: | |
543987bd | 3189 | self.clientSpecDirs = getClientSpec() |
3a70cdfa | 3190 | |
6a49f8e2 HWN |
3191 | # TODO: should always look at previous commits, |
3192 | # merge with previous imports, if possible. | |
3193 | if args == []: | |
d414c74a | 3194 | if self.hasOrigin: |
5ca44617 | 3195 | createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent) |
3b650fc9 PW |
3196 | |
3197 | # branches holds mapping from branch name to sha1 | |
3198 | branches = p4BranchesInGit(self.importIntoRemotes) | |
8c9e8b6e PW |
3199 | |
3200 | # restrict to just this one, disabling detect-branches | |
3201 | if branch_arg_given: | |
3202 | short = self.branch.split("/")[-1] | |
3203 | if short in branches: | |
3204 | self.p4BranchesInGit = [ short ] | |
3205 | else: | |
3206 | self.p4BranchesInGit = branches.keys() | |
abcd790f SH |
3207 | |
3208 | if len(self.p4BranchesInGit) > 1: | |
3209 | if not self.silent: | |
3210 | print "Importing from/into multiple branches" | |
3211 | self.detectBranches = True | |
8c9e8b6e PW |
3212 | for branch in branches.keys(): |
3213 | self.initialParents[self.refPrefix + branch] = \ | |
3214 | branches[branch] | |
967f72e2 | 3215 | |
29bdbac1 SH |
3216 | if self.verbose: |
3217 | print "branches: %s" % self.p4BranchesInGit | |
3218 | ||
3219 | p4Change = 0 | |
3220 | for branch in self.p4BranchesInGit: | |
cebdf5af | 3221 | logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch) |
bb6e09b2 HWN |
3222 | |
3223 | settings = extractSettingsGitLog(logMsg) | |
29bdbac1 | 3224 | |
bb6e09b2 HWN |
3225 | self.readOptions(settings) |
3226 | if (settings.has_key('depot-paths') | |
3227 | and settings.has_key ('change')): | |
3228 | change = int(settings['change']) + 1 | |
29bdbac1 SH |
3229 | p4Change = max(p4Change, change) |
3230 | ||
bb6e09b2 HWN |
3231 | depotPaths = sorted(settings['depot-paths']) |
3232 | if self.previousDepotPaths == []: | |
6326aa58 | 3233 | self.previousDepotPaths = depotPaths |
29bdbac1 | 3234 | else: |
6326aa58 HWN |
3235 | paths = [] |
3236 | for (prev, cur) in zip(self.previousDepotPaths, depotPaths): | |
04d277b3 VA |
3237 | prev_list = prev.split("/") |
3238 | cur_list = cur.split("/") | |
3239 | for i in range(0, min(len(cur_list), len(prev_list))): | |
3240 | if cur_list[i] <> prev_list[i]: | |
583e1707 | 3241 | i = i - 1 |
6326aa58 HWN |
3242 | break |
3243 | ||
04d277b3 | 3244 | paths.append ("/".join(cur_list[:i + 1])) |
6326aa58 HWN |
3245 | |
3246 | self.previousDepotPaths = paths | |
29bdbac1 SH |
3247 | |
3248 | if p4Change > 0: | |
bb6e09b2 | 3249 | self.depotPaths = sorted(self.previousDepotPaths) |
d5904674 | 3250 | self.changeRange = "@%s,#head" % p4Change |
341dc1c1 | 3251 | if not self.silent and not self.detectBranches: |
967f72e2 | 3252 | print "Performing incremental import into %s git branch" % self.branch |
569d1bd4 | 3253 | |
40d69ac3 PW |
3254 | # accept multiple ref name abbreviations: |
3255 | # refs/foo/bar/branch -> use it exactly | |
3256 | # p4/branch -> prepend refs/remotes/ or refs/heads/ | |
3257 | # branch -> prepend refs/remotes/p4/ or refs/heads/p4/ | |
f9162f6a | 3258 | if not self.branch.startswith("refs/"): |
40d69ac3 PW |
3259 | if self.importIntoRemotes: |
3260 | prepend = "refs/remotes/" | |
3261 | else: | |
3262 | prepend = "refs/heads/" | |
3263 | if not self.branch.startswith("p4/"): | |
3264 | prepend += "p4/" | |
3265 | self.branch = prepend + self.branch | |
179caebf | 3266 | |
6326aa58 | 3267 | if len(args) == 0 and self.depotPaths: |
b984733c | 3268 | if not self.silent: |
6326aa58 | 3269 | print "Depot paths: %s" % ' '.join(self.depotPaths) |
b984733c | 3270 | else: |
6326aa58 | 3271 | if self.depotPaths and self.depotPaths != args: |
cebdf5af | 3272 | print ("previous import used depot path %s and now %s was specified. " |
6326aa58 HWN |
3273 | "This doesn't work!" % (' '.join (self.depotPaths), |
3274 | ' '.join (args))) | |
b984733c | 3275 | sys.exit(1) |
6326aa58 | 3276 | |
bb6e09b2 | 3277 | self.depotPaths = sorted(args) |
b984733c | 3278 | |
1c49fc19 | 3279 | revision = "" |
b984733c | 3280 | self.users = {} |
b984733c | 3281 | |
58c8bc7c PW |
3282 | # Make sure no revision specifiers are used when --changesfile |
3283 | # is specified. | |
3284 | bad_changesfile = False | |
3285 | if len(self.changesFile) > 0: | |
3286 | for p in self.depotPaths: | |
3287 | if p.find("@") >= 0 or p.find("#") >= 0: | |
3288 | bad_changesfile = True | |
3289 | break | |
3290 | if bad_changesfile: | |
3291 | die("Option --changesfile is incompatible with revision specifiers") | |
3292 | ||
6326aa58 HWN |
3293 | newPaths = [] |
3294 | for p in self.depotPaths: | |
3295 | if p.find("@") != -1: | |
3296 | atIdx = p.index("@") | |
3297 | self.changeRange = p[atIdx:] | |
3298 | if self.changeRange == "@all": | |
3299 | self.changeRange = "" | |
6a49f8e2 | 3300 | elif ',' not in self.changeRange: |
1c49fc19 | 3301 | revision = self.changeRange |
6326aa58 | 3302 | self.changeRange = "" |
7fcff9de | 3303 | p = p[:atIdx] |
6326aa58 HWN |
3304 | elif p.find("#") != -1: |
3305 | hashIdx = p.index("#") | |
1c49fc19 | 3306 | revision = p[hashIdx:] |
7fcff9de | 3307 | p = p[:hashIdx] |
6326aa58 | 3308 | elif self.previousDepotPaths == []: |
58c8bc7c PW |
3309 | # pay attention to changesfile, if given, else import |
3310 | # the entire p4 tree at the head revision | |
3311 | if len(self.changesFile) == 0: | |
3312 | revision = "#head" | |
6326aa58 HWN |
3313 | |
3314 | p = re.sub ("\.\.\.$", "", p) | |
3315 | if not p.endswith("/"): | |
3316 | p += "/" | |
3317 | ||
3318 | newPaths.append(p) | |
3319 | ||
3320 | self.depotPaths = newPaths | |
3321 | ||
e63231e5 PW |
3322 | # --detect-branches may change this for each branch |
3323 | self.branchPrefixes = self.depotPaths | |
3324 | ||
b607e71e | 3325 | self.loadUserMapFromCache() |
cb53e1f8 SH |
3326 | self.labels = {} |
3327 | if self.detectLabels: | |
3328 | self.getLabels(); | |
b984733c | 3329 | |
4b97ffb1 | 3330 | if self.detectBranches: |
df450923 SH |
3331 | ## FIXME - what's a P4 projectName ? |
3332 | self.projectName = self.guessProjectName() | |
3333 | ||
38f9f5ec SH |
3334 | if self.hasOrigin: |
3335 | self.getBranchMappingFromGitBranches() | |
3336 | else: | |
3337 | self.getBranchMapping() | |
29bdbac1 SH |
3338 | if self.verbose: |
3339 | print "p4-git branches: %s" % self.p4BranchesInGit | |
3340 | print "initial parents: %s" % self.initialParents | |
3341 | for b in self.p4BranchesInGit: | |
3342 | if b != "master": | |
6326aa58 HWN |
3343 | |
3344 | ## FIXME | |
29bdbac1 SH |
3345 | b = b[len(self.projectName):] |
3346 | self.createdBranches.add(b) | |
4b97ffb1 | 3347 | |
f291b4e3 | 3348 | self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60)) |
b984733c | 3349 | |
78189bea PW |
3350 | self.importProcess = subprocess.Popen(["git", "fast-import"], |
3351 | stdin=subprocess.PIPE, | |
3352 | stdout=subprocess.PIPE, | |
3353 | stderr=subprocess.PIPE); | |
3354 | self.gitOutput = self.importProcess.stdout | |
3355 | self.gitStream = self.importProcess.stdin | |
3356 | self.gitError = self.importProcess.stderr | |
b984733c | 3357 | |
1c49fc19 | 3358 | if revision: |
c208a243 | 3359 | self.importHeadRevision(revision) |
b984733c SH |
3360 | else: |
3361 | changes = [] | |
3362 | ||
0828ab14 | 3363 | if len(self.changesFile) > 0: |
b984733c | 3364 | output = open(self.changesFile).readlines() |
1d7367dc | 3365 | changeSet = set() |
b984733c SH |
3366 | for line in output: |
3367 | changeSet.add(int(line)) | |
3368 | ||
3369 | for change in changeSet: | |
3370 | changes.append(change) | |
3371 | ||
3372 | changes.sort() | |
3373 | else: | |
9dcb9f24 PW |
3374 | # catch "git p4 sync" with no new branches, in a repo that |
3375 | # does not have any existing p4 branches | |
5a8e84cd PW |
3376 | if len(args) == 0: |
3377 | if not self.p4BranchesInGit: | |
3378 | die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.") | |
3379 | ||
3380 | # The default branch is master, unless --branch is used to | |
3381 | # specify something else. Make sure it exists, or complain | |
3382 | # nicely about how to use --branch. | |
3383 | if not self.detectBranches: | |
3384 | if not branch_exists(self.branch): | |
3385 | if branch_arg_given: | |
3386 | die("Error: branch %s does not exist." % self.branch) | |
3387 | else: | |
3388 | die("Error: no branch %s; perhaps specify one with --branch." % | |
3389 | self.branch) | |
3390 | ||
29bdbac1 | 3391 | if self.verbose: |
86dff6b6 | 3392 | print "Getting p4 changes for %s...%s" % (', '.join(self.depotPaths), |
6326aa58 | 3393 | self.changeRange) |
96b2d54a | 3394 | changes = p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size) |
b984733c | 3395 | |
01a9c9c5 | 3396 | if len(self.maxChanges) > 0: |
7fcff9de | 3397 | changes = changes[:min(int(self.maxChanges), len(changes))] |
01a9c9c5 | 3398 | |
b984733c | 3399 | if len(changes) == 0: |
0828ab14 | 3400 | if not self.silent: |
341dc1c1 | 3401 | print "No changes to import!" |
06804c76 LD |
3402 | else: |
3403 | if not self.silent and not self.detectBranches: | |
3404 | print "Import destination: %s" % self.branch | |
3405 | ||
3406 | self.updatedBranches = set() | |
b984733c | 3407 | |
47497844 PW |
3408 | if not self.detectBranches: |
3409 | if args: | |
3410 | # start a new branch | |
3411 | self.initialParent = "" | |
3412 | else: | |
3413 | # build on a previous revision | |
3414 | self.initialParent = parseRevision(self.branch) | |
3415 | ||
06804c76 | 3416 | self.importChanges(changes) |
a9d1a27a | 3417 | |
06804c76 LD |
3418 | if not self.silent: |
3419 | print "" | |
3420 | if len(self.updatedBranches) > 0: | |
3421 | sys.stdout.write("Updated branches: ") | |
3422 | for b in self.updatedBranches: | |
3423 | sys.stdout.write("%s " % b) | |
3424 | sys.stdout.write("\n") | |
341dc1c1 | 3425 | |
0d609032 | 3426 | if gitConfigBool("git-p4.importLabels"): |
06dcd152 | 3427 | self.importLabels = True |
b984733c | 3428 | |
06804c76 LD |
3429 | if self.importLabels: |
3430 | p4Labels = getP4Labels(self.depotPaths) | |
3431 | gitTags = getGitTags() | |
3432 | ||
3433 | missingP4Labels = p4Labels - gitTags | |
3434 | self.importP4Labels(self.gitStream, missingP4Labels) | |
b984733c | 3435 | |
b984733c | 3436 | self.gitStream.close() |
78189bea | 3437 | if self.importProcess.wait() != 0: |
29bdbac1 | 3438 | die("fast-import failed: %s" % self.gitError.read()) |
b984733c SH |
3439 | self.gitOutput.close() |
3440 | self.gitError.close() | |
3441 | ||
fed23693 VA |
3442 | # Cleanup temporary branches created during import |
3443 | if self.tempBranches != []: | |
3444 | for branch in self.tempBranches: | |
3445 | read_pipe("git update-ref -d %s" % branch) | |
3446 | os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation)) | |
3447 | ||
55d12437 PW |
3448 | # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow |
3449 | # a convenient shortcut refname "p4". | |
3450 | if self.importIntoRemotes: | |
3451 | head_ref = self.refPrefix + "HEAD" | |
3452 | if not gitBranchExists(head_ref) and gitBranchExists(self.branch): | |
3453 | system(["git", "symbolic-ref", head_ref, self.branch]) | |
3454 | ||
b984733c SH |
3455 | return True |
3456 | ||
01ce1fe9 SH |
3457 | class P4Rebase(Command): |
3458 | def __init__(self): | |
3459 | Command.__init__(self) | |
06804c76 LD |
3460 | self.options = [ |
3461 | optparse.make_option("--import-labels", dest="importLabels", action="store_true"), | |
06804c76 | 3462 | ] |
06804c76 | 3463 | self.importLabels = False |
cebdf5af HWN |
3464 | self.description = ("Fetches the latest revision from perforce and " |
3465 | + "rebases the current work (branch) against it") | |
01ce1fe9 SH |
3466 | |
3467 | def run(self, args): | |
3468 | sync = P4Sync() | |
06804c76 | 3469 | sync.importLabels = self.importLabels |
01ce1fe9 | 3470 | sync.run([]) |
d7e3868c | 3471 | |
14594f4b SH |
3472 | return self.rebase() |
3473 | ||
3474 | def rebase(self): | |
36ee4ee4 SH |
3475 | if os.system("git update-index --refresh") != 0: |
3476 | 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."); | |
3477 | if len(read_pipe("git diff-index HEAD --")) > 0: | |
f7e604ed | 3478 | die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash."); |
36ee4ee4 | 3479 | |
d7e3868c SH |
3480 | [upstream, settings] = findUpstreamBranchPoint() |
3481 | if len(upstream) == 0: | |
3482 | die("Cannot find upstream branchpoint for rebase") | |
3483 | ||
3484 | # the branchpoint may be p4/foo~3, so strip off the parent | |
3485 | upstream = re.sub("~[0-9]+$", "", upstream) | |
3486 | ||
3487 | print "Rebasing the current branch onto %s" % upstream | |
b25b2065 | 3488 | oldHead = read_pipe("git rev-parse HEAD").strip() |
d7e3868c | 3489 | system("git rebase %s" % upstream) |
4e49d95e | 3490 | system("git diff-tree --stat --summary -M %s HEAD --" % oldHead) |
01ce1fe9 SH |
3491 | return True |
3492 | ||
f9a3a4f7 SH |
3493 | class P4Clone(P4Sync): |
3494 | def __init__(self): | |
3495 | P4Sync.__init__(self) | |
3496 | self.description = "Creates a new git repository and imports from Perforce into it" | |
bb6e09b2 | 3497 | self.usage = "usage: %prog [options] //depot/path[@revRange]" |
354081d5 | 3498 | self.options += [ |
bb6e09b2 HWN |
3499 | optparse.make_option("--destination", dest="cloneDestination", |
3500 | action='store', default=None, | |
354081d5 | 3501 | help="where to leave result of the clone"), |
38200076 PW |
3502 | optparse.make_option("--bare", dest="cloneBare", |
3503 | action="store_true", default=False), | |
354081d5 | 3504 | ] |
bb6e09b2 | 3505 | self.cloneDestination = None |
f9a3a4f7 | 3506 | self.needsGit = False |
38200076 | 3507 | self.cloneBare = False |
f9a3a4f7 | 3508 | |
6a49f8e2 HWN |
3509 | def defaultDestination(self, args): |
3510 | ## TODO: use common prefix of args? | |
3511 | depotPath = args[0] | |
3512 | depotDir = re.sub("(@[^@]*)$", "", depotPath) | |
3513 | depotDir = re.sub("(#[^#]*)$", "", depotDir) | |
053d9e43 | 3514 | depotDir = re.sub(r"\.\.\.$", "", depotDir) |
6a49f8e2 HWN |
3515 | depotDir = re.sub(r"/$", "", depotDir) |
3516 | return os.path.split(depotDir)[1] | |
3517 | ||
f9a3a4f7 SH |
3518 | def run(self, args): |
3519 | if len(args) < 1: | |
3520 | return False | |
bb6e09b2 HWN |
3521 | |
3522 | if self.keepRepoPath and not self.cloneDestination: | |
3523 | sys.stderr.write("Must specify destination for --keep-path\n") | |
3524 | sys.exit(1) | |
f9a3a4f7 | 3525 | |
6326aa58 | 3526 | depotPaths = args |
5e100b5c SH |
3527 | |
3528 | if not self.cloneDestination and len(depotPaths) > 1: | |
3529 | self.cloneDestination = depotPaths[-1] | |
3530 | depotPaths = depotPaths[:-1] | |
3531 | ||
354081d5 | 3532 | self.cloneExclude = ["/"+p for p in self.cloneExclude] |
6326aa58 HWN |
3533 | for p in depotPaths: |
3534 | if not p.startswith("//"): | |
0f487d30 | 3535 | sys.stderr.write('Depot paths must start with "//": %s\n' % p) |
6326aa58 | 3536 | return False |
f9a3a4f7 | 3537 | |
bb6e09b2 | 3538 | if not self.cloneDestination: |
98ad4faf | 3539 | self.cloneDestination = self.defaultDestination(args) |
f9a3a4f7 | 3540 | |
86dff6b6 | 3541 | print "Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination) |
38200076 | 3542 | |
c3bf3f13 KG |
3543 | if not os.path.exists(self.cloneDestination): |
3544 | os.makedirs(self.cloneDestination) | |
053fd0c1 | 3545 | chdir(self.cloneDestination) |
38200076 PW |
3546 | |
3547 | init_cmd = [ "git", "init" ] | |
3548 | if self.cloneBare: | |
3549 | init_cmd.append("--bare") | |
a235e85c BC |
3550 | retcode = subprocess.call(init_cmd) |
3551 | if retcode: | |
3552 | raise CalledProcessError(retcode, init_cmd) | |
38200076 | 3553 | |
6326aa58 | 3554 | if not P4Sync.run(self, depotPaths): |
f9a3a4f7 | 3555 | return False |
c595956d PW |
3556 | |
3557 | # create a master branch and check out a work tree | |
3558 | if gitBranchExists(self.branch): | |
3559 | system([ "git", "branch", "master", self.branch ]) | |
3560 | if not self.cloneBare: | |
3561 | system([ "git", "checkout", "-f" ]) | |
3562 | else: | |
3563 | print 'Not checking out any branch, use ' \ | |
3564 | '"git checkout -q -b master <branch>"' | |
86dff6b6 | 3565 | |
a93d33ee PW |
3566 | # auto-set this variable if invoked with --use-client-spec |
3567 | if self.useClientSpec_from_options: | |
3568 | system("git config --bool git-p4.useclientspec true") | |
3569 | ||
f9a3a4f7 SH |
3570 | return True |
3571 | ||
09d89de2 SH |
3572 | class P4Branches(Command): |
3573 | def __init__(self): | |
3574 | Command.__init__(self) | |
3575 | self.options = [ ] | |
3576 | self.description = ("Shows the git branches that hold imports and their " | |
3577 | + "corresponding perforce depot paths") | |
3578 | self.verbose = False | |
3579 | ||
3580 | def run(self, args): | |
5ca44617 SH |
3581 | if originP4BranchesExist(): |
3582 | createOrUpdateBranchesFromOrigin() | |
3583 | ||
09d89de2 SH |
3584 | cmdline = "git rev-parse --symbolic " |
3585 | cmdline += " --remotes" | |
3586 | ||
3587 | for line in read_pipe_lines(cmdline): | |
3588 | line = line.strip() | |
3589 | ||
3590 | if not line.startswith('p4/') or line == "p4/HEAD": | |
3591 | continue | |
3592 | branch = line | |
3593 | ||
3594 | log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch) | |
3595 | settings = extractSettingsGitLog(log) | |
3596 | ||
3597 | print "%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]) | |
3598 | return True | |
3599 | ||
b984733c SH |
3600 | class HelpFormatter(optparse.IndentedHelpFormatter): |
3601 | def __init__(self): | |
3602 | optparse.IndentedHelpFormatter.__init__(self) | |
3603 | ||
3604 | def format_description(self, description): | |
3605 | if description: | |
3606 | return description + "\n" | |
3607 | else: | |
3608 | return "" | |
4f5cf76a | 3609 | |
86949eef SH |
3610 | def printUsage(commands): |
3611 | print "usage: %s <command> [options]" % sys.argv[0] | |
3612 | print "" | |
3613 | print "valid commands: %s" % ", ".join(commands) | |
3614 | print "" | |
3615 | print "Try %s <command> --help for command specific help." % sys.argv[0] | |
3616 | print "" | |
3617 | ||
3618 | commands = { | |
b86f7378 HWN |
3619 | "debug" : P4Debug, |
3620 | "submit" : P4Submit, | |
a9834f58 | 3621 | "commit" : P4Submit, |
b86f7378 HWN |
3622 | "sync" : P4Sync, |
3623 | "rebase" : P4Rebase, | |
3624 | "clone" : P4Clone, | |
09d89de2 SH |
3625 | "rollback" : P4RollBack, |
3626 | "branches" : P4Branches | |
86949eef SH |
3627 | } |
3628 | ||
86949eef | 3629 | |
bb6e09b2 HWN |
3630 | def main(): |
3631 | if len(sys.argv[1:]) == 0: | |
3632 | printUsage(commands.keys()) | |
3633 | sys.exit(2) | |
4f5cf76a | 3634 | |
bb6e09b2 HWN |
3635 | cmdName = sys.argv[1] |
3636 | try: | |
b86f7378 HWN |
3637 | klass = commands[cmdName] |
3638 | cmd = klass() | |
bb6e09b2 HWN |
3639 | except KeyError: |
3640 | print "unknown command %s" % cmdName | |
3641 | print "" | |
3642 | printUsage(commands.keys()) | |
3643 | sys.exit(2) | |
3644 | ||
3645 | options = cmd.options | |
b86f7378 | 3646 | cmd.gitdir = os.environ.get("GIT_DIR", None) |
bb6e09b2 HWN |
3647 | |
3648 | args = sys.argv[2:] | |
3649 | ||
b0ccc80d | 3650 | options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true")) |
6a10b6aa LD |
3651 | if cmd.needsGit: |
3652 | options.append(optparse.make_option("--git-dir", dest="gitdir")) | |
bb6e09b2 | 3653 | |
6a10b6aa LD |
3654 | parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName), |
3655 | options, | |
3656 | description = cmd.description, | |
3657 | formatter = HelpFormatter()) | |
bb6e09b2 | 3658 | |
6a10b6aa | 3659 | (cmd, args) = parser.parse_args(sys.argv[2:], cmd); |
bb6e09b2 HWN |
3660 | global verbose |
3661 | verbose = cmd.verbose | |
3662 | if cmd.needsGit: | |
b86f7378 HWN |
3663 | if cmd.gitdir == None: |
3664 | cmd.gitdir = os.path.abspath(".git") | |
3665 | if not isValidGitDir(cmd.gitdir): | |
3666 | cmd.gitdir = read_pipe("git rev-parse --git-dir").strip() | |
3667 | if os.path.exists(cmd.gitdir): | |
bb6e09b2 HWN |
3668 | cdup = read_pipe("git rev-parse --show-cdup").strip() |
3669 | if len(cdup) > 0: | |
053fd0c1 | 3670 | chdir(cdup); |
e20a9e53 | 3671 | |
b86f7378 HWN |
3672 | if not isValidGitDir(cmd.gitdir): |
3673 | if isValidGitDir(cmd.gitdir + "/.git"): | |
3674 | cmd.gitdir += "/.git" | |
bb6e09b2 | 3675 | else: |
b86f7378 | 3676 | die("fatal: cannot locate git repository at %s" % cmd.gitdir) |
e20a9e53 | 3677 | |
b86f7378 | 3678 | os.environ["GIT_DIR"] = cmd.gitdir |
86949eef | 3679 | |
bb6e09b2 HWN |
3680 | if not cmd.run(args): |
3681 | parser.print_help() | |
09fca77b | 3682 | sys.exit(2) |
4f5cf76a | 3683 | |
4f5cf76a | 3684 | |
bb6e09b2 HWN |
3685 | if __name__ == '__main__': |
3686 | main() |