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