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