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