Merge branch 'jc/cat-file-batch-commands'
[alt-git.git] / git-p4.py
bloba9b1f9044108e4dce94b865f1f777039d8755613
1 #!/usr/bin/env python
3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
7 # 2007 Trolltech ASA
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
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
18 import sys
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")
21 sys.exit(1)
22 import os
23 import optparse
24 import functools
25 import marshal
26 import subprocess
27 import tempfile
28 import time
29 import platform
30 import re
31 import shutil
32 import stat
33 import zipfile
34 import zlib
35 import ctypes
36 import errno
37 import glob
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
42 # support basestring in python3
43 try:
44 if raw_input and input:
45 input = raw_input
46 except:
47 pass
49 verbose = False
51 # Only labels/tags matching this will be imported/exported
52 defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
54 # The block size is reduced automatically if required
55 defaultBlockSize = 1<<20
57 p4_access_checked = False
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]+)?\$')
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)
74 def p4_build_cmd(cmd):
75 """Build a suitable p4 command line.
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 """
81 real_cmd = ["p4"]
83 user = gitConfig("git-p4.user")
84 if len(user) > 0:
85 real_cmd += ["-u",user]
87 password = gitConfig("git-p4.password")
88 if len(password) > 0:
89 real_cmd += ["-P", password]
91 port = gitConfig("git-p4.port")
92 if len(port) > 0:
93 real_cmd += ["-p", port]
95 host = gitConfig("git-p4.host")
96 if len(host) > 0:
97 real_cmd += ["-H", host]
99 client = gitConfig("git-p4.client")
100 if len(client) > 0:
101 real_cmd += ["-c", client]
103 retries = gitConfigInt("git-p4.retries")
104 if retries is None:
105 # Perform 3 retries by default
106 retries = 3
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)]
111 real_cmd += cmd
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()
119 return real_cmd
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.
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
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.
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.
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.
148 os.chdir(path)
149 if not is_client_path:
150 path = os.getcwd()
151 os.environ['PWD'] = path
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
163 def die(msg):
164 """ Terminate execution. Make sure that any running child processes have been wait()ed for before
165 calling this.
167 if verbose:
168 raise Exception(msg)
169 else:
170 sys.stderr.write(msg + "\n")
171 sys.exit(1)
173 def prompt(prompt_text):
174 """ Prompt the user to choose one of the choices
176 Choices are identified in the prompt_text by square brackets around
177 a single letter option.
179 choices = set(m.group(1) for m in re.finditer(r"\[(.)\]", prompt_text))
180 while True:
181 sys.stderr.flush()
182 sys.stdout.write(prompt_text)
183 sys.stdout.flush()
184 response=sys.stdin.readline().strip().lower()
185 if not response:
186 continue
187 response = response[0]
188 if response in choices:
189 return response
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
206 def decode_path(path):
207 """Decode a given string (bytes or otherwise) using configured path encoding options
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
221 def run_git_hook(cmd, param=[]):
222 """Execute a hook if the hook exists."""
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
230 def write_pipe(c, stdin, *k, **kw):
231 if verbose:
232 sys.stderr.write('Writing pipe: {}\n'.format(' '.join(c)))
234 p = subprocess.Popen(c, stdin=subprocess.PIPE, *k, **kw)
235 pipe = p.stdin
236 val = pipe.write(stdin)
237 pipe.close()
238 if p.wait():
239 die('Command failed: {}'.format(' '.join(c)))
241 return val
243 def p4_write_pipe(c, stdin, *k, **kw):
244 real_cmd = p4_build_cmd(c)
245 if bytes is not str and isinstance(stdin, str):
246 stdin = encode_text_stream(stdin)
247 return write_pipe(real_cmd, stdin, *k, **kw)
249 def read_pipe_full(c, *k, **kw):
250 """ Read output from command. Returns a tuple
251 of the return status, stdout text and stderr
252 text.
254 if verbose:
255 sys.stderr.write('Reading pipe: {}\n'.format(' '.join(c)))
257 p = subprocess.Popen(
258 c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, *k, **kw)
259 (out, err) = p.communicate()
260 return (p.returncode, out, decode_text_stream(err))
262 def read_pipe(c, ignore_error=False, raw=False, *k, **kw):
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.
267 If raw is True, do not attempt to decode output text.
269 (retcode, out, err) = read_pipe_full(c, *k, **kw)
270 if retcode != 0:
271 if ignore_error:
272 out = ""
273 else:
274 die('Command failed: {}\nError: {}'.format(' '.join(c), err))
275 if not raw:
276 out = decode_text_stream(out)
277 return out
279 def read_pipe_text(c, *k, **kw):
280 """ Read output from a command with trailing whitespace stripped.
281 On error, returns None.
283 (retcode, out, err) = read_pipe_full(c, *k, **kw)
284 if retcode != 0:
285 return None
286 else:
287 return decode_text_stream(out).rstrip()
289 def p4_read_pipe(c, ignore_error=False, raw=False, *k, **kw):
290 real_cmd = p4_build_cmd(c)
291 return read_pipe(real_cmd, ignore_error, raw=raw, *k, **kw)
293 def read_pipe_lines(c, raw=False, *k, **kw):
294 if verbose:
295 sys.stderr.write('Reading pipe: {}\n'.format(' '.join(c)))
297 p = subprocess.Popen(c, stdout=subprocess.PIPE, *k, **kw)
298 pipe = p.stdout
299 lines = pipe.readlines()
300 if not raw:
301 lines = [decode_text_stream(line) for line in lines]
302 if pipe.close() or p.wait():
303 die('Command failed: {}'.format(' '.join(c)))
304 return lines
306 def p4_read_pipe_lines(c, *k, **kw):
307 """Specifically invoke p4 on the command supplied. """
308 real_cmd = p4_build_cmd(c)
309 return read_pipe_lines(real_cmd, *k, **kw)
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
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."""
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()
331 err = decode_text_stream(err)
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
340 def system(cmd, ignore_error=False, *k, **kw):
341 if verbose:
342 sys.stderr.write("executing {}\n".format(
343 ' '.join(cmd) if isinstance(cmd, list) else cmd))
344 retcode = subprocess.call(cmd, *k, **kw)
345 if retcode and not ignore_error:
346 raise subprocess.CalledProcessError(retcode, cmd)
348 return retcode
350 def p4_system(cmd, *k, **kw):
351 """Specifically invoke p4 as the system command. """
352 real_cmd = p4_build_cmd(cmd)
353 retcode = subprocess.call(real_cmd, *k, **kw)
354 if retcode:
355 raise subprocess.CalledProcessError(retcode, real_cmd)
357 def die_bad_access(s):
358 die("failure accessing depot: {0}".format(s.rstrip()))
360 def p4_check_access(min_expiration=1):
361 """ Check if we can access Perforce - account still logged in
363 results = p4CmdList(["login", "-s"])
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")
369 result = results[0]
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")
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")
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))
390 else:
391 # account without a timeout - all ok
392 return
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")
400 elif code == "info":
401 return
402 else:
403 die_bad_access("unknown error code {0}".format(code))
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.
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).
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
421 def p4_integrate(src, dest):
422 p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
424 def p4_sync(f, *options):
425 p4_system(["sync"] + list(options) + [wildcard_encode(f)])
427 def p4_add(f):
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])
434 def p4_delete(f):
435 p4_system(["delete", wildcard_encode(f)])
437 def p4_edit(f, *options):
438 p4_system(["edit"] + list(options) + [wildcard_encode(f)])
440 def p4_revert(f):
441 p4_system(["revert", wildcard_encode(f)])
443 def p4_reopen(type, f):
444 p4_system(["reopen", "-t", type, wildcard_encode(f)])
446 def p4_reopen_in_change(changelist, files):
447 cmd = ["reopen", "-c", str(changelist)] + files
448 p4_system(cmd)
450 def p4_move(src, dest):
451 p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
453 def p4_last_change():
454 results = p4CmdList(["changes", "-m", "1"], skip_info=True)
455 return int(results[0]['change'])
457 def p4_describe(change, shelved=False):
458 """Make sure it returns a valid result by checking for
459 the presence of field "time". Return a dict of the
460 results."""
462 cmd = ["describe", "-s"]
463 if shelved:
464 cmd += ["-S"]
465 cmd += [str(change)]
467 ds = p4CmdList(cmd, skip_info=True)
468 if len(ds) != 1:
469 die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
471 d = ds[0]
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)))
480 if "time" not in d:
481 die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
483 return d
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.
490 def split_p4_type(p4type):
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",
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)
521 # return the raw p4 type of a file (text, text+ko, etc)
523 def p4_type(f):
524 results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)])
525 return results[0]['headType']
528 # Given a type base and modifier, return a regexp matching
529 # the keywords that can be expanded in the file
531 def p4_keywords_regexp_for_type(base, type_mods):
532 if base in ("text", "unicode", "binary"):
533 if "ko" in type_mods:
534 return re_ko_keywords
535 elif "k" in type_mods:
536 return re_k_keywords
537 else:
538 return None
539 else:
540 return None
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.
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)
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.
558 p4Type = "+x"
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]
567 p4_reopen(p4Type, file)
569 def getP4OpenedType(file):
570 # Returns the perforce file type for the given file.
572 result = p4_read_pipe(["opened", wildcard_encode(file)])
573 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result)
574 if match:
575 return match.group(1)
576 else:
577 die("Could not determine file type for %s (result: '%s')" % (file, result))
579 # Return the set of all p4 labels
580 def getP4Labels(depotPaths):
581 labels = set()
582 if not isinstance(depotPaths, list):
583 depotPaths = [depotPaths]
585 for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
586 label = l['label']
587 labels.add(label)
589 return labels
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
599 _diff_tree_pattern = None
601 def parseDiffTreeEntry(entry):
602 """Parses a single diff tree entry into its component elements.
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:
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.
618 If the pattern is not matched, None is returned."""
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(.*))|$)')
624 match = _diff_tree_pattern.match(entry)
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)
636 return None
638 def isModeExec(mode):
639 # Returns True if the given git mode represents an executable file,
640 # otherwise False.
641 return mode[-3:] == "755"
643 class P4Exception(Exception):
644 """ Base class for exceptions from the p4 client """
645 def __init__(self, exit_code):
646 self.p4ExitCode = exit_code
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']
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
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
667 def __str__(self):
668 return self.msg
670 def isModeExecChanged(src_mode, dst_mode):
671 return isModeExec(src_mode) != isModeExec(dst_mode)
673 def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,
674 errors_as_exceptions=False, *k, **kw):
676 cmd = p4_build_cmd(["-G"] + cmd)
677 if verbose:
678 sys.stderr.write("Opening pipe: {}\n".format(' '.join(cmd)))
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)
686 if not isinstance(stdin, list):
687 stdin_file.write(stdin)
688 else:
689 for i in stdin:
690 stdin_file.write(encode_text_stream(i))
691 stdin_file.write(b'\n')
692 stdin_file.flush()
693 stdin_file.seek(0)
695 p4 = subprocess.Popen(
696 cmd, stdin=stdin_file, stdout=subprocess.PIPE, *k, **kw)
698 result = []
699 try:
700 while True:
701 entry = marshal.load(p4.stdout)
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
716 if skip_info:
717 if 'code' in entry and entry['code'] == 'info':
718 continue
719 if cb is not None:
720 cb(entry)
721 else:
722 result.append(entry)
723 except EOFError:
724 pass
725 exitCode = p4.wait()
726 if exitCode != 0:
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)
735 if m:
736 limit = int(m.group(1))
737 raise P4RequestSizeException(exitCode, result, limit)
739 raise P4ServerException(exitCode, result)
740 else:
741 raise P4Exception(exitCode)
742 else:
743 entry = {}
744 entry["p4ExitCode"] = exitCode
745 result.append(entry)
747 return result
749 def p4Cmd(cmd, *k, **kw):
750 list = p4CmdList(cmd, *k, **kw)
751 result = {}
752 for entry in list:
753 result.update(entry)
754 return result;
756 def p4Where(depotPath):
757 if not depotPath.endswith("/"):
758 depotPath += "/"
759 depotPathLong = depotPath + "..."
760 outputList = p4CmdList(["where", depotPathLong])
761 output = None
762 for entry in outputList:
763 if "depotFile" in entry:
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 "/...".
766 entry_path = decode_path(entry['depotFile'])
767 if entry_path.find(depotPath) == 0 and entry_path[-4:] == "/...":
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
776 if output == None:
777 return ""
778 if output["code"] == "error":
779 return ""
780 clientPath = ""
781 if "path" in output:
782 clientPath = decode_path(output['path'])
783 elif "data" in output:
784 data = output.get("data")
785 lastSpace = data.rfind(b" ")
786 clientPath = decode_path(data[lastSpace + 1:])
788 if clientPath.endswith("..."):
789 clientPath = clientPath[:-3]
790 return clientPath
792 def currentGitBranch():
793 return read_pipe_text(["git", "symbolic-ref", "--short", "-q", "HEAD"])
795 def isValidGitDir(path):
796 return git_dir(path) != None
798 def parseRevision(ref):
799 return read_pipe(["git", "rev-parse", ref]).strip()
801 def branchExists(ref):
802 rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
803 ignore_error=True)
804 return len(rev) > 0
806 def extractLogMessageFromGitCommit(commit):
807 logMessage = ""
809 ## fixme: title is first line of commit, not 1st paragraph.
810 foundTitle = False
811 for log in read_pipe_lines(["git", "cat-file", "commit", commit]):
812 if not foundTitle:
813 if len(log) == 1:
814 foundTitle = True
815 continue
817 logMessage += log
818 return logMessage
820 def extractSettingsGitLog(log):
821 values = {}
822 for line in log.split("\n"):
823 line = line.strip()
824 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
825 if not m:
826 continue
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]
836 values[key] = val
838 paths = values.get("depot-paths")
839 if not paths:
840 paths = values.get("depot-path")
841 if paths:
842 values['depot-paths'] = paths.split(',')
843 return values
845 def gitBranchExists(branch):
846 proc = subprocess.Popen(["git", "rev-parse", branch],
847 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
848 return proc.wait() == 0;
850 def gitUpdateRef(ref, newvalue):
851 subprocess.check_call(["git", "update-ref", ref, newvalue])
853 def gitDeleteRef(ref):
854 subprocess.check_call(["git", "update-ref", "-d", ref])
856 _gitConfig = {}
858 def gitConfig(key, typeSpecifier=None):
859 if key not in _gitConfig:
860 cmd = [ "git", "config" ]
861 if typeSpecifier:
862 cmd += [ typeSpecifier ]
863 cmd += [ key ]
864 s = read_pipe(cmd, ignore_error=True)
865 _gitConfig[key] = s.strip()
866 return _gitConfig[key]
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."""
873 if key not in _gitConfig:
874 _gitConfig[key] = gitConfig(key, '--bool') == "true"
875 return _gitConfig[key]
877 def gitConfigInt(key):
878 if key not in _gitConfig:
879 cmd = [ "git", "config", "--int", key ]
880 s = read_pipe(cmd, ignore_error=True)
881 v = s.strip()
882 try:
883 _gitConfig[key] = int(gitConfig(key, '--int'))
884 except ValueError:
885 _gitConfig[key] = None
886 return _gitConfig[key]
888 def gitConfigList(key):
889 if key not in _gitConfig:
890 s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
891 _gitConfig[key] = s.strip().splitlines()
892 if _gitConfig[key] == ['']:
893 _gitConfig[key] = []
894 return _gitConfig[key]
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."""
903 branches = {}
905 cmdline = ["git", "rev-parse", "--symbolic"]
906 if branchesAreInRemotes:
907 cmdline.append("--remotes")
908 else:
909 cmdline.append("--branches")
911 for line in read_pipe_lines(cmdline):
912 line = line.strip()
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":
919 continue
921 # strip off p4/ prefix
922 branch = line[len("p4/"):]
924 branches[branch] = parseRevision(line)
926 return branches
928 def branch_exists(branch):
929 """Make sure that the given ref name really exists."""
931 cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
932 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
933 out, _ = p.communicate()
934 out = decode_text_stream(out)
935 if p.returncode:
936 return False
937 # expect exactly one line of output: the branch name
938 return out.rstrip() == branch
940 def findUpstreamBranchPoint(head = "HEAD"):
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)
948 if "depot-paths" in settings:
949 paths = ",".join(settings["depot-paths"])
950 branchByDepotPath[paths] = "remotes/p4/" + branch
952 settings = None
953 parent = 0
954 while parent < 65535:
955 commit = head + "~%s" % parent
956 log = extractLogMessageFromGitCommit(commit)
957 settings = extractSettingsGitLog(log)
958 if "depot-paths" in settings:
959 paths = ",".join(settings["depot-paths"])
960 if paths in branchByDepotPath:
961 return [branchByDepotPath[paths], settings]
963 parent = parent + 1
965 return ["", settings]
967 def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
968 if not silent:
969 print("Creating/updating branch(es) in %s based on origin branch(es)"
970 % localRefPrefix)
972 originPrefix = "origin/p4/"
974 for line in read_pipe_lines(["git", "rev-parse", "--symbolic", "--remotes"]):
975 line = line.strip()
976 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
977 continue
979 headName = line[len(originPrefix):]
980 remoteHead = localRefPrefix + headName
981 originHead = line
983 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
984 if ('depot-paths' not in original
985 or 'change' not in original):
986 continue
988 update = False
989 if not gitBranchExists(remoteHead):
990 if verbose:
991 print("creating %s" % remoteHead)
992 update = True
993 else:
994 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
995 if 'change' in settings:
996 if settings['depot-paths'] == original['depot-paths']:
997 originP4Change = int(original['change'])
998 p4Change = int(settings['change'])
999 if originP4Change > p4Change:
1000 print("%s (%s) is newer than %s (%s). "
1001 "Updating p4 branch from origin."
1002 % (originHead, originP4Change,
1003 remoteHead, p4Change))
1004 update = True
1005 else:
1006 print("Ignoring: %s was imported from %s while "
1007 "%s was imported from %s"
1008 % (originHead, ','.join(original['depot-paths']),
1009 remoteHead, ','.join(settings['depot-paths'])))
1011 if update:
1012 system(["git", "update-ref", remoteHead, originHead])
1014 def originP4BranchesExist():
1015 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
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])
1025 return (changeStart, changeEnd)
1027 def chooseBlockSize(blockSize):
1028 if blockSize:
1029 return blockSize
1030 else:
1031 return defaultBlockSize
1033 def p4ChangesForPaths(depotPaths, changeRange, requestedBlockSize):
1034 assert depotPaths
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.
1042 if changeRange is None or changeRange == '':
1043 changeStart = 1
1044 changeEnd = p4_last_change()
1045 block_size = chooseBlockSize(requestedBlockSize)
1046 else:
1047 parts = changeRange.split(',')
1048 assert len(parts) == 2
1049 try:
1050 (changeStart, changeEnd) = p4ParseNumericChangeRange(parts)
1051 block_size = chooseBlockSize(requestedBlockSize)
1052 except ValueError:
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
1059 changes = set()
1061 # Retrieve changes a block at a time, to prevent running
1062 # into a MaxResults/MaxScanRows error from the server. If
1063 # we _do_ hit one of those errors, turn down the block size
1065 while True:
1066 cmd = ['changes']
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)
1074 for p in depotPaths:
1075 cmd += ["%s...@%s" % (p, revisionRange)]
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)
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))
1093 # Insert changes in chronological order
1094 for entry in reversed(result):
1095 if 'change' not in entry:
1096 continue
1097 changes.add(int(entry['change']))
1099 if not block_size:
1100 break
1102 if end >= changeEnd:
1103 break
1105 changeStart = end + 1
1107 changes = sorted(changes)
1108 return changes
1110 def p4PathStartsWith(path, prefix):
1111 # This method tries to remedy a potential mixed-case issue:
1113 # If UserA adds //depot/DirA/file1
1114 # and UserB adds //depot/dira/file2
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
1118 if gitConfigBool("core.ignorecase"):
1119 return path.lower().startswith(prefix.lower())
1120 return path.startswith(prefix)
1122 def getClientSpec():
1123 """Look at the p4 client spec, create a View() object that contains
1124 all the mappings, and return it."""
1126 specList = p4CmdList(["client", "-o"])
1127 if len(specList) != 1:
1128 die('Output from "client -o" is %d lines, expecting 1' %
1129 len(specList))
1131 # dictionary of all client parameters
1132 entry = specList[0]
1134 # the //client/ name
1135 client_name = entry["Client"]
1137 # just the keys that start with "View"
1138 view_keys = [ k for k in entry.keys() if k.startswith("View") ]
1140 # hold this new View
1141 view = View(client_name)
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])
1150 return view
1152 def getClientRoot():
1153 """Grab the client directory."""
1155 output = p4CmdList(["client", "-o"])
1156 if len(output) != 1:
1157 die('Output from "client -o" is %d lines, expecting 1' % len(output))
1159 entry = output[0]
1160 if "Root" not in entry:
1161 die('Client has no "Root"')
1163 return entry["Root"]
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.
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
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
1190 def wildcard_present(path):
1191 m = re.search("[*#@%]", path)
1192 return m is not None
1194 class LargeFileSystem(object):
1195 """Base class for large file system support."""
1197 def __init__(self, writeToGitStream):
1198 self.largeFiles = set()
1199 self.writeToGitStream = writeToGitStream
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__
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__
1211 def hasLargeFileExtension(self, relPath):
1212 return functools.reduce(
1213 lambda a, b: a or b,
1214 [relPath.endswith('.' + e) for e in gitConfigList('git-p4.largeFileExtensions')],
1215 False
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
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)
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
1239 os.remove(contentTempFile)
1240 if compressedContentsSize > gitConfigInt('git-p4.largeFileCompressedThreshold'):
1241 return True
1242 return False
1244 def addLargeFile(self, relPath):
1245 self.largeFiles.add(relPath)
1247 def removeLargeFile(self, relPath):
1248 self.largeFiles.remove(relPath)
1250 def isLargeFile(self, relPath):
1251 return relPath in self.largeFiles
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)
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))
1273 return (git_mode, contents)
1275 class MockLFS(LargeFileSystem):
1276 """Mock large file system for testing."""
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.
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)
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.
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)))
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."""
1302 def __init__(self, *args):
1303 LargeFileSystem.__init__(self, *args)
1304 self.baseGitAttributes = []
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.
1312 if os.path.getsize(contentFile) == 0:
1313 return (None, '', None)
1315 pointerProcess = subprocess.Popen(
1316 ['git', 'lfs', 'pointer', '--file=' + contentFile],
1317 stdout=subprocess.PIPE
1319 pointerFile = decode_text_stream(pointerProcess.stdout.read())
1320 if pointerProcess.wait():
1321 os.remove(contentFile)
1322 die('git-lfs pointer command failed. Did you install the extension?')
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)
1331 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)
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)
1338 localLargeFile = os.path.join(
1339 lfs_path,
1340 'objects', oid[:2], oid[2:4],
1341 oid,
1343 # LFS Spec states that pointer files should not have the executable bit set.
1344 gitMode = '100644'
1345 return (gitMode, pointerFile, localLargeFile)
1347 def pushFile(self, localLargeFile):
1348 uploadProcess = subprocess.Popen(
1349 ['git', 'lfs', 'push', '--object-id', 'origin', os.path.basename(localLargeFile)]
1351 if uploadProcess.wait():
1352 die('git-lfs push command failed. Did you define a remote?')
1354 def generateGitAttributes(self):
1355 return (
1356 self.baseGitAttributes +
1358 '\n',
1359 '#\n',
1360 '# Git LFS (see https://git-lfs.github.com/)\n',
1361 '#\n',
1363 ['*.' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1364 for f in sorted(gitConfigList('git-p4.largeFileExtensions'))
1366 ['/' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1367 for f in sorted(self.largeFiles) if not self.hasLargeFileExtension(f)
1371 def addLargeFile(self, relPath):
1372 LargeFileSystem.addLargeFile(self, relPath)
1373 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
1375 def removeLargeFile(self, relPath):
1376 LargeFileSystem.removeLargeFile(self, relPath)
1377 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
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)
1386 class Command:
1387 delete_actions = ( "delete", "move/delete", "purge" )
1388 add_actions = ( "add", "branch", "move/add" )
1390 def __init__(self):
1391 self.usage = "usage: %prog [options]"
1392 self.needsGit = True
1393 self.verbose = False
1395 # This is required for the "append" update_shelve action
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)
1401 class P4UserMap:
1402 def __init__(self):
1403 self.userMapFromPerforceServer = False
1404 self.myP4UserId = None
1406 def p4UserId(self):
1407 if self.myP4UserId:
1408 return self.myP4UserId
1410 results = p4CmdList(["user", "-o"])
1411 for r in results:
1412 if 'User' in r:
1413 self.myP4UserId = r['User']
1414 return r['User']
1415 die("Could not find your p4 user id")
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
1425 def getUserCacheFilename(self):
1426 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
1427 return home + "/.gitp4-usercache.txt"
1429 def getUserMapFromPerforceServer(self):
1430 if self.userMapFromPerforceServer:
1431 return
1432 self.users = {}
1433 self.emails = {}
1435 for output in p4CmdList(["users"]):
1436 if "User" not in output:
1437 continue
1438 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
1439 self.emails[output["Email"]] = output["User"]
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
1451 s = ''
1452 for (key, val) in self.users.items():
1453 s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
1455 open(self.getUserCacheFilename(), 'w').write(s)
1456 self.userMapFromPerforceServer = True
1458 def loadUserMapFromCache(self):
1459 self.users = {}
1460 self.userMapFromPerforceServer = False
1461 try:
1462 cache = open(self.getUserCacheFilename(), 'r')
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()
1471 class P4Submit(Command, P4UserMap):
1473 conflict_behavior_choices = ("ask", "skip", "quit")
1475 def __init__(self):
1476 Command.__init__(self)
1477 P4UserMap.__init__(self)
1478 self.options = [
1479 optparse.make_option("--origin", dest="origin"),
1480 optparse.make_option("-M", dest="detectRenames", action="store_true"),
1481 # preserve the user, requires relevant p4 permissions
1482 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
1483 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
1484 optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
1485 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
1486 optparse.make_option("--conflict", dest="conflict_behavior",
1487 choices=self.conflict_behavior_choices),
1488 optparse.make_option("--branch", dest="branch"),
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"),
1492 optparse.make_option("--update-shelve", dest="update_shelve", action="append", type="int",
1493 metavar="CHANGELIST",
1494 help="update an existing shelved changelist, implies --shelve, "
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 "
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"),
1503 optparse.make_option("--no-verify", dest="no_verify", action="store_true",
1504 help="Bypass p4-pre-submit and p4-changelist hooks"),
1506 self.description = """Submit changes from git to the perforce depot.\n
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.
1512 One usage scenario is to run unit tests in the hook.
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.
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.
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.
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.
1532 The `p4-post-changelist` hook is invoked after the submit has successfully
1533 occurred in P4. It takes no parameters and is meant primarily for notification
1534 and cannot affect the outcome of the git p4 submit action.
1537 self.usage += " [name of git branch to submit into perforce depot]"
1538 self.origin = ""
1539 self.detectRenames = False
1540 self.preserveUser = gitConfigBool("git-p4.preserveUser")
1541 self.dry_run = False
1542 self.shelve = False
1543 self.update_shelve = list()
1544 self.commit = ""
1545 self.disable_rebase = gitConfigBool("git-p4.disableRebase")
1546 self.disable_p4sync = gitConfigBool("git-p4.disableP4Sync")
1547 self.prepare_p4_only = False
1548 self.conflict_behavior = None
1549 self.isWindows = (platform.system() == "Windows")
1550 self.exportLabels = False
1551 self.p4HasMoveCommand = p4_has_move_command()
1552 self.branch = None
1553 self.no_verify = False
1555 if gitConfig('git-p4.largeFileSystem'):
1556 die("Large file system not supported for git-p4 submit command. Please remove it from config.")
1558 def check(self):
1559 if len(p4CmdList(["opened", "..."])) > 0:
1560 die("You have files opened with perforce! Close them before starting the sync.")
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.
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.
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.
1576 Return a tuple (stripped log message, jobs string)."""
1578 m = re.search(r'^Jobs:', message, re.MULTILINE)
1579 if m is None:
1580 return (message, None)
1582 jobtext = message[m.start():]
1583 stripped_message = message[:m.start()].rstrip()
1584 return (stripped_message, jobtext)
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."""
1590 result = ""
1592 inDescriptionSection = False
1594 for line in template.split("\n"):
1595 if line.startswith("#"):
1596 result += line + "\n"
1597 continue
1599 if inDescriptionSection:
1600 if line.startswith("Files:") or line.startswith("Jobs:"):
1601 inDescriptionSection = False
1602 # insert Jobs section
1603 if jobs:
1604 result += jobs + "\n"
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"
1614 result += line + "\n"
1616 return result
1618 def patchRCSKeywords(self, file, regexp):
1619 # Attempt to zap the RCS keywords in a p4 controlled file matching the given regex
1620 (handle, outFileName) = tempfile.mkstemp(dir='.')
1621 try:
1622 with os.fdopen(handle, "wb") as outFile, open(file, "rb") as inFile:
1623 for line in inFile.readlines():
1624 outFile.write(regexp.sub(br'$\1$', line))
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)
1631 print("Failed to strip RCS keywords in %s" % file)
1632 raise
1634 print("Patched up RCS keywords in %s" % file)
1636 def p4UserForCommit(self,id):
1637 # Return the tuple (perforce user,git email) for a given git commit id
1638 self.getUserMapFromPerforceServer()
1639 gitEmail = read_pipe(["git", "log", "--max-count=1",
1640 "--format=%ae", id])
1641 gitEmail = gitEmail.strip()
1642 if gitEmail not in self.emails:
1643 return (None,gitEmail)
1644 else:
1645 return (self.emails[gitEmail],gitEmail)
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)
1653 if gitConfigBool("git-p4.allowMissingP4Users"):
1654 print("%s" % msg)
1655 else:
1656 die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
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.
1663 results = p4CmdList(["client", "-o"]) # find the current client
1664 client = None
1665 for r in results:
1666 if 'Client' in r:
1667 client = r['Client']
1668 break
1669 if not client:
1670 die("could not get client spec")
1671 results = p4CmdList(["changes", "-c", client, "-m", "1"])
1672 for r in results:
1673 if 'change' in r:
1674 return r['change']
1675 die("Could not get changelist number for last submit - cannot patch up user details")
1677 def modifyChangelistUser(self, changelist, newUser):
1678 # fixup the user field of a changelist after it has been submitted.
1679 changes = p4CmdList(["change", "-o", changelist])
1680 if len(changes) != 1:
1681 die("Bad output from p4 change modifying %s to user %s" %
1682 (changelist, newUser))
1684 c = changes[0]
1685 if c['User'] == newUser: return # nothing to do
1686 c['User'] = newUser
1687 # p4 does not understand format version 3 and above
1688 input = marshal.dumps(c, 2)
1690 result = p4CmdList(["change", "-f", "-i"], stdin=input)
1691 for r in result:
1692 if 'code' in r:
1693 if r['code'] == 'error':
1694 die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
1695 if 'data' in r:
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))
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.
1703 results = p4CmdList(["protects", self.depotPath])
1704 for r in results:
1705 if 'perm' in r:
1706 if r['perm'] == 'admin':
1707 return 1
1708 if r['perm'] == 'super':
1709 return 1
1710 return 0
1712 def prepareSubmitTemplate(self, changelist=None):
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.
1717 Remove lines in the Files section that show changes to files
1718 outside the depot path we're committing into."""
1720 [upstream, settings] = findUpstreamBranchPoint()
1722 template = """\
1723 # A Perforce Change Specification.
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.)
1738 files_list = []
1739 inFilesSection = False
1740 change_entry = None
1741 args = ['change', '-o']
1742 if changelist:
1743 args.append(str(changelist))
1744 for entry in p4CmdList(args):
1745 if 'code' not in entry:
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')
1752 for key, value in change_entry.items():
1753 if key.startswith('File'):
1754 if 'depot-paths' in settings:
1755 if not [p for p in settings['depot-paths']
1756 if p4PathStartsWith(value, p)]:
1757 continue
1758 else:
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']:
1765 if key not in change_entry:
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'
1778 return template
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."""
1784 # if configured to skip the editing part, just submit
1785 if gitConfigBool("git-p4.skipSubmitEdit"):
1786 return True
1788 # look at the modification time, to check later if the user saved
1789 # the file
1790 mtime = os.stat(template_file).st_mtime
1792 # invoke the editor
1793 if "P4EDITOR" in os.environ and (os.environ.get("P4EDITOR") != ""):
1794 editor = os.environ.get("P4EDITOR")
1795 else:
1796 editor = read_pipe(["git", "var", "GIT_EDITOR"]).strip()
1797 system(["sh", "-c", ('%s "$@"' % editor), editor, template_file])
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.
1801 if gitConfigBool("git-p4.skipSubmitEditCheck"):
1802 return True
1804 # modification time updated means user saved the file
1805 if os.stat(template_file).st_mtime > mtime:
1806 return True
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
1814 def get_diff_description(self, editedFiles, filesToAdd, symlinks):
1815 # diff
1816 if "P4DIFF" in os.environ:
1817 del(os.environ["P4DIFF"])
1818 diff = ""
1819 for editedFile in editedFiles:
1820 diff += p4_read_pipe(['diff', '-du',
1821 wildcard_encode(editedFile)])
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
1830 is_link = os.path.islink(newFile)
1831 expect_link = newFile in symlinks
1833 if is_link and expect_link:
1834 newdiff += "+%s\n" % os.readlink(newFile)
1835 else:
1836 f = open(newFile, "r")
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
1842 f.close()
1844 return (diff + newdiff).replace('\r\n', '\n')
1846 def applyCommit(self, id):
1847 """Apply one commit, return True if it succeeded."""
1849 print("Applying", read_pipe(["git", "show", "-s",
1850 "--format=format:%h %s", id]))
1852 (p4User, gitEmail) = self.p4UserForCommit(id)
1854 diff = read_pipe_lines(
1855 ["git", "diff-tree", "-r"] + self.diffOpts + ["{}^".format(id), id])
1856 filesToAdd = set()
1857 filesToChangeType = set()
1858 filesToDelete = set()
1859 editedFiles = set()
1860 pureRenameCopy = set()
1861 symlinks = set()
1862 filesToChangeExecBit = {}
1863 all_files = list()
1865 for line in diff:
1866 diff = parseDiffTreeEntry(line)
1867 modifier = diff['status']
1868 path = diff['src']
1869 all_files.append(path)
1871 if modifier == "M":
1872 p4_edit(path)
1873 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1874 filesToChangeExecBit[path] = diff['dst_mode']
1875 editedFiles.add(path)
1876 elif modifier == "A":
1877 filesToAdd.add(path)
1878 filesToChangeExecBit[path] = diff['dst_mode']
1879 if path in filesToDelete:
1880 filesToDelete.remove(path)
1882 dst_mode = int(diff['dst_mode'], 8)
1883 if dst_mode == 0o120000:
1884 symlinks.add(path)
1886 elif modifier == "D":
1887 filesToDelete.add(path)
1888 if path in filesToAdd:
1889 filesToAdd.remove(path)
1890 elif modifier == "C":
1891 src, dest = diff['src'], diff['dst']
1892 all_files.append(dest)
1893 p4_integrate(src, dest)
1894 pureRenameCopy.add(dest)
1895 if diff['src_sha1'] != diff['dst_sha1']:
1896 p4_edit(dest)
1897 pureRenameCopy.discard(dest)
1898 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1899 p4_edit(dest)
1900 pureRenameCopy.discard(dest)
1901 filesToChangeExecBit[dest] = diff['dst_mode']
1902 if self.isWindows:
1903 # turn off read-only attribute
1904 os.chmod(dest, stat.S_IWRITE)
1905 os.unlink(dest)
1906 editedFiles.add(dest)
1907 elif modifier == "R":
1908 src, dest = diff['src'], diff['dst']
1909 all_files.append(dest)
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)
1913 else:
1914 p4_integrate(src, dest)
1915 if diff['src_sha1'] != diff['dst_sha1']:
1916 p4_edit(dest)
1917 else:
1918 pureRenameCopy.add(dest)
1919 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1920 if not self.p4HasMoveCommand:
1921 p4_edit(dest) # with move: already open, writable
1922 filesToChangeExecBit[dest] = diff['dst_mode']
1923 if not self.p4HasMoveCommand:
1924 if self.isWindows:
1925 os.chmod(dest, stat.S_IWRITE)
1926 os.unlink(dest)
1927 filesToDelete.add(src)
1928 editedFiles.add(dest)
1929 elif modifier == "T":
1930 filesToChangeType.add(path)
1931 else:
1932 die("unknown modifier %s for %s" % (modifier, path))
1934 diffcmd = "git diff-tree --full-index -p \"%s\"" % (id)
1935 patchcmd = diffcmd + " | git apply "
1936 tryPatchCmd = patchcmd + "--check -"
1937 applyPatchCmd = patchcmd + "--check --apply -"
1938 patch_succeeded = True
1940 if verbose:
1941 print("TryPatch: %s" % tryPatchCmd)
1943 if os.system(tryPatchCmd) != 0:
1944 fixed_rcs_keywords = False
1945 patch_succeeded = False
1946 print("Unfortunately applying the change failed!")
1948 # Patch failed, maybe it's just RCS keyword woes. Look through
1949 # the patch to see if that's possible.
1950 if gitConfigBool("git-p4.attemptRCSCleanup"):
1951 file = None
1952 kwfiles = {}
1953 for file in editedFiles | filesToDelete:
1954 # did this file's delta contain RCS keywords?
1955 regexp = p4_keywords_regexp_for_file(file)
1956 if regexp:
1957 # this file is a possibility...look for RCS keywords.
1958 for line in read_pipe_lines(
1959 ["git", "diff", "%s^..%s" % (id, id), file],
1960 raw=True):
1961 if regexp.search(line):
1962 if verbose:
1963 print("got keyword match on %s in %s in %s" % (regex.pattern, line, file))
1964 kwfiles[file] = regexp
1965 break
1967 for file, regexp in kwfiles.items():
1968 if verbose:
1969 print("zapping %s with %s" % (line, regexp.pattern))
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)
1974 self.patchRCSKeywords(file, kwfiles[file])
1975 fixed_rcs_keywords = True
1977 if fixed_rcs_keywords:
1978 print("Retrying the patch with RCS keywords cleaned up")
1979 if os.system(tryPatchCmd) == 0:
1980 patch_succeeded = True
1981 print("Patch succeesed this time with RCS keywords cleaned")
1983 if not patch_succeeded:
1984 for f in editedFiles:
1985 p4_revert(f)
1986 return False
1989 # Apply the patch for real, and do add/delete/+x handling.
1991 system(applyPatchCmd, shell=True)
1993 for f in filesToChangeType:
1994 p4_edit(f, "-t", "auto")
1995 for f in filesToAdd:
1996 p4_add(f)
1997 for f in filesToDelete:
1998 p4_revert(f)
1999 p4_delete(f)
2001 # Set/clear executable bits
2002 for f in filesToChangeExecBit.keys():
2003 mode = filesToChangeExecBit[f]
2004 setP4ExecBit(f, mode)
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)
2012 # Build p4 change description, starting with the contents
2013 # of the git commit message.
2015 logMessage = extractLogMessageFromGitCommit(id)
2016 logMessage = logMessage.strip()
2017 (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
2019 template = self.prepareSubmitTemplate(update_shelve)
2020 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
2022 if self.preserveUser:
2023 submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
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"
2030 separatorLine = "######## everything below this line is just the diff #######\n"
2031 if not self.prepare_p4_only:
2032 submitTemplate += separatorLine
2033 submitTemplate += self.get_diff_description(editedFiles, filesToAdd, symlinks)
2035 (handle, fileName) = tempfile.mkstemp()
2036 tmpFile = os.fdopen(handle, "w+b")
2037 if self.isWindows:
2038 submitTemplate = submitTemplate.replace("\n", "\r\n")
2039 tmpFile.write(encode_text_stream(submitTemplate))
2040 tmpFile.close()
2042 submitted = False
2044 try:
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
2050 if self.prepare_p4_only:
2052 # Leave the p4 tree prepared, and the submit template around
2053 # and let the user decide what to do next
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)
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)
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
2087 if self.edit_template(fileName):
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
2094 # read the edited message and submit
2095 tmpFile = open(fileName, "rb")
2096 message = decode_text_stream(tmpFile.read())
2097 tmpFile.close()
2098 if self.isWindows:
2099 message = message.replace("\r\n", "\n")
2100 if message.find(separatorLine) != -1:
2101 submitTemplate = message[:message.index(separatorLine)]
2102 else:
2103 submitTemplate = message
2105 if len(submitTemplate.strip()) == 0:
2106 print("Changelist is empty, aborting this changelist.")
2107 sys.stdout.flush()
2108 return False
2110 if update_shelve:
2111 p4_write_pipe(['shelve', '-r', '-i'], submitTemplate)
2112 elif self.shelve:
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")
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)
2129 submitted = True
2131 run_git_hook("p4-post-changelist")
2132 finally:
2133 # Revert changes if we skip this patch
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.")
2139 sys.stdout.flush()
2140 for f in editedFiles | filesToDelete:
2141 p4_revert(f)
2142 for f in filesToAdd:
2143 p4_revert(f)
2144 os.remove(f)
2146 if not self.prepare_p4_only:
2147 os.remove(fileName)
2148 return submitted
2150 # Export git tags as p4 labels. Create a p4 label and then tag
2151 # with that.
2152 def exportGitTags(self, gitTags):
2153 validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
2154 if len(validLabelRegexp) == 0:
2155 validLabelRegexp = defaultLabelRegexp
2156 m = re.compile(validLabelRegexp)
2158 for name in gitTags:
2160 if not m.match(name):
2161 if verbose:
2162 print("tag %s does not match regexp %s" % (name, validLabelRegexp))
2163 continue
2165 # Get the p4 commit this corresponds to
2166 logMessage = extractLogMessageFromGitCommit(name)
2167 values = extractSettingsGitLog(logMessage)
2169 if 'change' not in values:
2170 # a tag pointing to something not sent to p4; ignore
2171 if verbose:
2172 print("git tag %s does not give a p4 commit" % name)
2173 continue
2174 else:
2175 changelist = values['change']
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)
2192 if not isAnnotated:
2193 body = ["lightweight tag imported by git p4\n"]
2195 # Create the label - use the same view as the client spec we are using
2196 clientSpec = getClientSpec()
2198 labelTemplate = "Label: %s\n" % name
2199 labelTemplate += "Description:\n"
2200 for b in body:
2201 labelTemplate += "\t" + b + "\n"
2202 labelTemplate += "View:\n"
2203 for depot_side in clientSpec.mappings:
2204 labelTemplate += "\t%s\n" % depot_side
2206 if self.dry_run:
2207 print("Would create p4 label %s for tag" % name)
2208 elif self.prepare_p4_only:
2209 print("Not creating p4 label %s for tag due to option" \
2210 " --prepare-p4-only" % name)
2211 else:
2212 p4_write_pipe(["label", "-i"], labelTemplate)
2214 # Use the label
2215 p4_system(["tag", "-l", name] +
2216 ["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings])
2218 if verbose:
2219 print("created p4 label for tag %s" % name)
2221 def run(self, args):
2222 if len(args) == 0:
2223 self.master = currentGitBranch()
2224 elif len(args) == 1:
2225 self.master = args[0]
2226 if not branchExists(self.master):
2227 die("Branch %s does not exist" % self.master)
2228 else:
2229 return False
2231 for i in self.update_shelve:
2232 if i <= 0:
2233 sys.exit("invalid changelist %d" % i)
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)
2240 [upstream, settings] = findUpstreamBranchPoint()
2241 self.depotPath = settings['depot-paths'][0]
2242 if len(self.origin) == 0:
2243 self.origin = upstream
2245 if len(self.update_shelve) > 0:
2246 self.shelve = True
2248 if self.preserveUser:
2249 if not self.canChangeChangelists():
2250 die("Cannot preserve user names without p4 super-user or admin permissions")
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
2262 if self.verbose:
2263 print("Origin branch is " + self.origin)
2265 if len(self.depotPath) == 0:
2266 print("Internal error: cannot locate perforce depot path from existing branches")
2267 sys.exit(128)
2269 self.useClientSpec = False
2270 if gitConfigBool("git-p4.useclientspec"):
2271 self.useClientSpec = True
2272 if self.useClientSpec:
2273 self.clientSpecDirs = getClientSpec()
2275 # Check for the existence of P4 branches
2276 branchesDetected = (len(p4BranchesInGit().keys()) > 1)
2278 if self.useClientSpec and not branchesDetected:
2279 # all files are relative to the client spec
2280 self.clientPath = getClientRoot()
2281 else:
2282 self.clientPath = p4Where(self.depotPath)
2284 if self.clientPath == "":
2285 die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
2287 print("Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath))
2288 self.oldWorkingDirectory = os.getcwd()
2290 # ensure the clientPath exists
2291 new_client_dir = False
2292 if not os.path.exists(self.clientPath):
2293 new_client_dir = True
2294 os.makedirs(self.clientPath)
2296 chdir(self.clientPath, is_client_path=True)
2297 if self.dry_run:
2298 print("Would synchronize p4 checkout in %s" % self.clientPath)
2299 else:
2300 print("Synchronizing p4 checkout...")
2301 if new_client_dir:
2302 # old one was destroyed, and maybe nobody told p4
2303 p4_sync("...", "-f")
2304 else:
2305 p4_sync("...")
2306 self.check()
2308 commits = []
2309 if self.master:
2310 committish = self.master
2311 else:
2312 committish = 'HEAD'
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:
2323 for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, committish)]):
2324 commits.append(line.strip())
2325 commits.reverse()
2327 if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"):
2328 self.checkAuthorship = False
2329 else:
2330 self.checkAuthorship = True
2332 if self.preserveUser:
2333 self.checkValidP4Users(commits)
2336 # Build up a set of options to be passed to diff when
2337 # submitting each commit to p4.
2339 if self.detectRenames:
2340 # command-line -M arg
2341 self.diffOpts = ["-M"]
2342 else:
2343 # If not explicitly set check the config variable
2344 detectRenames = gitConfig("git-p4.detectRenames")
2346 if detectRenames.lower() == "false" or detectRenames == "":
2347 self.diffOpts = []
2348 elif detectRenames.lower() == "true":
2349 self.diffOpts = ["-M"]
2350 else:
2351 self.diffOpts = ["-M{}".format(detectRenames)]
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":
2359 self.diffOpts.append("-C")
2360 else:
2361 self.diffOpts.append("-C{}".format(detectCopies))
2363 if gitConfigBool("git-p4.detectCopiesHarder"):
2364 self.diffOpts.append("--find-copies-harder")
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))
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) )
2381 sys.exit(1)
2384 # Apply the commits, one at a time. On failure, ask if should
2385 # continue to try the rest of the patches, or quit.
2387 if self.dry_run:
2388 print("Would apply")
2389 applied = []
2390 last = len(commits) - 1
2391 for i, commit in enumerate(commits):
2392 if self.dry_run:
2393 print(" ", read_pipe(["git", "show", "-s",
2394 "--format=format:%h %s", commit]))
2395 ok = True
2396 else:
2397 ok = self.applyCommit(commit)
2398 if ok:
2399 applied.append(commit)
2400 if self.prepare_p4_only:
2401 if i < last:
2402 print("Processing only the first commit due to option" \
2403 " --prepare-p4-only")
2404 break
2405 else:
2406 if i < last:
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)
2419 if response == "s":
2420 print("Skipping this commit, but applying the rest")
2421 if response == "q":
2422 print("Quitting")
2423 break
2425 chdir(self.oldWorkingDirectory)
2426 shelved_applied = "shelved" if self.shelve else "applied"
2427 if self.dry_run:
2428 pass
2429 elif self.prepare_p4_only:
2430 pass
2431 elif len(commits) == len(applied):
2432 print("All commits {0}!".format(shelved_applied))
2434 sync = P4Sync()
2435 if self.branch:
2436 sync.branch = self.branch
2437 if self.disable_p4sync:
2438 sync.sync_origin_only()
2439 else:
2440 sync.run([])
2442 if not self.disable_rebase:
2443 rebase = P4Rebase()
2444 rebase.rebase()
2446 else:
2447 if len(applied) == 0:
2448 print("No commits {0}.".format(shelved_applied))
2449 else:
2450 print("{0} only the commits marked with '*':".format(shelved_applied.capitalize()))
2451 for c in commits:
2452 if c in applied:
2453 star = "*"
2454 else:
2455 star = " "
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.")
2460 if gitConfigBool("git-p4.exportLabels"):
2461 self.exportLabels = True
2463 if self.exportLabels:
2464 p4Labels = getP4Labels(self.depotPath)
2465 gitTags = getGitTags()
2467 missingGitTags = gitTags - p4Labels
2468 self.exportGitTags(missingGitTags)
2470 # exit with error unless everything applied perfectly
2471 if len(commits) != len(applied):
2472 sys.exit(1)
2474 return True
2476 class View(object):
2477 """Represent a p4 view ("p4 help views"), and map files in a
2478 repo according to the view."""
2480 def __init__(self, client_name):
2481 self.mappings = []
2482 self.client_prefix = "//%s/" % client_name
2483 # cache results of "p4 where" to lookup client file locations
2484 self.client_spec_path_cache = {}
2486 def append(self, view_line):
2487 """Parse a view line, splitting it into depot and client
2488 sides. Append to self.mappings, preserving order. This
2489 is only needed for tag creation."""
2491 # Split the view line into exactly two words. P4 enforces
2492 # structure on these lines that simplifies this quite a bit.
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.
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
2517 # prefix + means overlay on previous mapping
2518 if depot_side.startswith("+"):
2519 depot_side = depot_side[1:]
2521 # prefix - means exclude this path, leave out of mappings
2522 exclude = False
2523 if depot_side.startswith("-"):
2524 exclude = True
2525 depot_side = depot_side[1:]
2527 if not exclude:
2528 self.mappings.append(depot_side)
2530 def convert_client_path(self, clientFile):
2531 # chop off //client/ part to make it relative
2532 if not decode_path(clientFile).startswith(self.client_prefix):
2533 die("No prefix '%s' on clientFile '%s'" %
2534 (self.client_prefix, clientFile))
2535 return clientFile[len(self.client_prefix):]
2537 def update_client_spec_path_cache(self, files):
2538 """ Caching file paths by "p4 where" batch query """
2540 # List depot file paths exclude that already cached
2541 fileArgs = [f['path'] for f in files if decode_path(f['path']) not in self.client_spec_path_cache]
2543 if len(fileArgs) == 0:
2544 return # All files in cache
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:
2552 die("No clientFile in 'p4 where' output")
2553 if "unmap" in res:
2554 # it will list all of them, but only one not unmap-ped
2555 continue
2556 depot_path = decode_path(res['depotFile'])
2557 if gitConfigBool("core.ignorecase"):
2558 depot_path = depot_path.lower()
2559 self.client_spec_path_cache[depot_path] = self.convert_client_path(res["clientFile"])
2561 # not found files or unmap files set to ""
2562 for depotFile in fileArgs:
2563 depotFile = decode_path(depotFile)
2564 if gitConfigBool("core.ignorecase"):
2565 depotFile = depotFile.lower()
2566 if depotFile not in self.client_spec_path_cache:
2567 self.client_spec_path_cache[depotFile] = b''
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."""
2574 if gitConfigBool("core.ignorecase"):
2575 depot_path = depot_path.lower()
2577 if depot_path in self.client_spec_path_cache:
2578 return self.client_spec_path_cache[depot_path]
2580 die( "Error: %s is not found in client spec path" % depot_path )
2581 return ""
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)]
2588 class P4Sync(Command, P4UserMap):
2590 def __init__(self):
2591 Command.__init__(self)
2592 P4UserMap.__init__(self)
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"),
2598 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
2599 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
2600 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
2601 help="Import into refs/heads/ , not refs/remotes"),
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"),
2606 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
2607 help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
2608 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
2609 help="Only sync files that are included in the Perforce Client Spec"),
2610 optparse.make_option("-/", dest="cloneExclude",
2611 action="callback", callback=cloneExcludeCallback, type="string",
2612 help="exclude depot path"),
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
2620 (a ... is not needed in the path p4 specification, it's added implicitly)"""
2622 self.usage += " //depot/path[@revRange]"
2623 self.silent = False
2624 self.createdBranches = set()
2625 self.committedChanges = set()
2626 self.branch = ""
2627 self.detectBranches = False
2628 self.detectLabels = False
2629 self.importLabels = False
2630 self.changesFile = ""
2631 self.syncWithOrigin = True
2632 self.importIntoRemotes = True
2633 self.maxChanges = ""
2634 self.changes_block_size = None
2635 self.keepRepoPath = False
2636 self.depotPaths = None
2637 self.p4BranchesInGit = []
2638 self.cloneExclude = []
2639 self.useClientSpec = False
2640 self.useClientSpec_from_options = False
2641 self.clientSpecDirs = None
2642 self.tempBranches = []
2643 self.tempBranchLocation = "refs/git-p4-tmp"
2644 self.largeFileSystem = None
2645 self.suppress_meta_comment = False
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)
2653 if gitConfig("git-p4.syncFromOrigin") == "false":
2654 self.syncWithOrigin = False
2656 self.depotPaths = []
2657 self.changeRange = ""
2658 self.previousDepotPaths = []
2659 self.hasOrigin = False
2661 # map from branch depot path to parent branch
2662 self.knownBranches = {}
2663 self.initialParents = {}
2665 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
2666 self.labels = {}
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")
2672 self.gitStream.flush()
2673 out = self.gitOutput.readline()
2674 if self.verbose:
2675 print("checkpoint finished: " + out)
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:
2686 if p4PathStartsWith(path, decode_path(p)):
2687 return True
2688 return False
2690 def extractFilesFromCommit(self, commit, shelved=False, shelved_cl = 0):
2691 files = []
2692 fnum = 0
2693 while "depotFile%s" % fnum in commit:
2694 path = commit["depotFile%s" % fnum]
2695 found = self.isPathWanted(decode_path(path))
2696 if not found:
2697 fnum = fnum + 1
2698 continue
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]
2705 if shelved:
2706 file["shelved_cl"] = int(shelved_cl)
2707 files.append(file)
2708 fnum = fnum + 1
2709 return files
2711 def extractJobsFromCommit(self, commit):
2712 jobs = []
2713 jnum = 0
2714 while "job%s" % jnum in commit:
2715 job = commit["job%s" % jnum]
2716 jobs.append(job)
2717 jnum = jnum + 1
2718 return jobs
2720 def stripRepoPath(self, path, prefixes):
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."""
2726 if self.useClientSpec:
2727 # branch detection moves files up a level (the branch name)
2728 # from what client spec interpretation gives
2729 path = decode_path(self.clientSpecDirs.map_in_client(path))
2730 if self.detectBranches:
2731 for b in self.knownBranches:
2732 if p4PathStartsWith(path, b + "/"):
2733 path = path[len(b)+1:]
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):]
2743 else:
2744 for p in prefixes:
2745 if p4PathStartsWith(path, p):
2746 path = path[len(p):]
2747 break
2749 path = wildcard_decode(path)
2750 return path
2752 def splitFilesIntoBranches(self, commit):
2753 """Look at each depotFile in the commit to figure out to what
2754 branch it belongs."""
2756 if self.clientSpecDirs:
2757 files = self.extractFilesFromCommit(commit)
2758 self.clientSpecDirs.update_client_spec_path_cache(files)
2760 branches = {}
2761 fnum = 0
2762 while "depotFile%s" % fnum in commit:
2763 raw_path = commit["depotFile%s" % fnum]
2764 path = decode_path(raw_path)
2765 found = self.isPathWanted(path)
2766 if not found:
2767 fnum = fnum + 1
2768 continue
2770 file = {}
2771 file["path"] = raw_path
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
2777 # start with the full relative path where this file would
2778 # go in a p4 client
2779 if self.useClientSpec:
2780 relPath = decode_path(self.clientSpecDirs.map_in_client(path))
2781 else:
2782 relPath = self.stripRepoPath(path, self.depotPaths)
2784 for branch in self.knownBranches.keys():
2785 # add a trailing slash so that a commit into qt/4.2foo
2786 # doesn't end up in qt/4.2, e.g.
2787 if p4PathStartsWith(relPath, branch + "/"):
2788 if branch not in branches:
2789 branches[branch] = []
2790 branches[branch].append(file)
2791 break
2793 return branches
2795 def writeToGitStream(self, gitMode, relPath, contents):
2796 self.gitStream.write(encode_text_stream(u'M {} inline {}\n'.format(gitMode, relPath)))
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')
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:
2811 print('Path with non-ASCII characters detected. Used %s to encode: %s ' % (encoding, path))
2812 return path
2814 # output one file from the P4 stream
2815 # - helper for streamP4Files
2817 def streamOneP4File(self, file, contents):
2818 file_path = file['depotFile']
2819 relPath = self.stripRepoPath(decode_path(file_path), self.branchPrefixes)
2821 if verbose:
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
2826 sys.stdout.write('\r%s --> %s (%s)\n' % (
2827 file_path, relPath, format_size_human_readable(size)))
2828 sys.stdout.flush()
2830 (type_base, type_mods) = split_p4_type(file["type"])
2832 git_mode = "100644"
2833 if "x" in type_mods:
2834 git_mode = "100755"
2835 if type_base == "symlink":
2836 git_mode = "120000"
2837 # p4 print on a symlink sometimes contains "target\n";
2838 # if it does, remove the newline
2839 data = ''.join(decode_text_stream(c) for c in contents)
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.
2845 print("\nIgnoring empty symlink in %s" % file_path)
2846 return
2847 elif data[-1] == '\n':
2848 contents = [data[:-1]]
2849 else:
2850 contents = [data]
2852 if type_base == "utf16":
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.
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.
2863 try:
2864 text = p4_read_pipe(['print', '-q', '-o', '-', '%s@%s' % (decode_path(file['depotFile']), file['change'])], raw=True)
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:
2872 text = text.replace(b'\r\n', b'\n')
2873 contents = [ text ]
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.
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.
2885 print("\nIgnoring apple filetype file %s" % file['depotFile'])
2886 return
2888 # Note that we do not try to de-mangle keywords on utf16 files,
2889 # even though in theory somebody may want that.
2890 regexp = p4_keywords_regexp_for_type(type_base, type_mods)
2891 if regexp:
2892 contents = [regexp.sub(br'$\1$', c) for c in contents]
2894 if self.largeFileSystem:
2895 (git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)
2897 self.writeToGitStream(git_mode, relPath, contents)
2899 def streamOneP4Deletion(self, file):
2900 relPath = self.stripRepoPath(decode_path(file['path']), self.branchPrefixes)
2901 if verbose:
2902 sys.stdout.write("delete %s\n" % relPath)
2903 sys.stdout.flush()
2904 self.gitStream.write(encode_text_stream(u'D {}\n'.format(relPath)))
2906 if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):
2907 self.largeFileSystem.removeLargeFile(relPath)
2909 # handle another chunk of streaming data
2910 def streamP4FilesCb(self, marshalled):
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()
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:
2922 err = 'Not enough space left on %s! Free at least %s.' % (
2923 os.getcwd(), format_size_human_readable(required_bytes))
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)
2942 if 'depotFile' in marshalled and self.stream_have_file_info:
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
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':
2953 if 'streamContentSize' not in self.stream_file:
2954 self.stream_file['streamContentSize'] = 0
2955 self.stream_file['streamContentSize'] += len(marshalled['data'])
2956 self.stream_contents.append(marshalled['data'])
2957 else:
2958 self.stream_file[k] = marshalled[k]
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
2967 sys.stdout.write('\r%s %d%% (%s)' % (
2968 self.stream_file['depotFile'], progress,
2969 format_size_human_readable(size)))
2970 sys.stdout.flush()
2972 self.stream_have_file_info = True
2974 # Stream directly from "p4 files" into "git fast-import"
2975 def streamP4Files(self, files):
2976 filesForCommit = []
2977 filesToRead = []
2978 filesToDelete = []
2980 for f in files:
2981 filesForCommit.append(f)
2982 if f['action'] in self.delete_actions:
2983 filesToDelete.append(f)
2984 else:
2985 filesToRead.append(f)
2987 # deleted files...
2988 for f in filesToDelete:
2989 self.streamOneP4Deletion(f)
2991 if len(filesToRead) > 0:
2992 self.stream_file = {}
2993 self.stream_contents = []
2994 self.stream_have_file_info = False
2996 # curry self argument
2997 def streamP4FilesCbSelf(entry):
2998 self.streamP4FilesCb(entry)
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
3005 fileArg = f['path'] + encode_text_stream('@={}'.format(f['shelved_cl']))
3006 else:
3007 fileArg = f['path'] + encode_text_stream('#{}'.format(f['rev']))
3009 fileArgs.append(fileArg)
3011 p4CmdList(["-x", "-", "print"],
3012 stdin=fileArgs,
3013 cb=streamP4FilesCbSelf)
3015 # do the last chunk
3016 if 'depotFile' in self.stream_file:
3017 self.streamOneP4File(self.stream_file, self.stream_contents)
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
3025 def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
3026 """ Stream a p4 tag.
3027 commit is either a git commit, or a fast-import mark, ":<p4commit>"
3030 if verbose:
3031 print("writing tag %s for commit %s" % (labelName, commit))
3032 gitStream.write("tag %s\n" % labelName)
3033 gitStream.write("from %s\n" % commit)
3035 if 'Owner' in labelDetails:
3036 owner = labelDetails["Owner"]
3037 else:
3038 owner = None
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)
3048 gitStream.write("tagger %s\n" % tagger)
3050 print("labelDetails=",labelDetails)
3051 if 'Description' in labelDetails:
3052 description = labelDetails['Description']
3053 else:
3054 description = 'Label from git p4'
3056 gitStream.write("data %d\n" % len(description))
3057 gitStream.write(description)
3058 gitStream.write("\n")
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
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)]
3073 if not hasPrefix and self.verbose:
3074 print('Ignoring file outside of prefix: {0}'.format(path))
3075 return hasPrefix
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.
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']})
3113 def commit(self, details, files, branch, parent = "", allow_empty=False):
3114 epoch = details["time"]
3115 author = details["user"]
3116 jobs = self.extractJobsFromCommit(details)
3118 if self.verbose:
3119 print('commit into {0}'.format(branch))
3121 files = [f for f in files
3122 if self.hasBranchPrefix(decode_path(f['path']))]
3123 self.findShadowedFiles(files, details['change'])
3125 if self.clientSpecDirs:
3126 self.clientSpecDirs.update_client_spec_path_cache(files)
3128 files = [f for f in files if self.inClientSpec(decode_path(f['path']))]
3130 if gitConfigBool('git-p4.keepEmptyCommits'):
3131 allow_empty = True
3133 if not files and not allow_empty:
3134 print('Ignoring revision {0} as it would produce an empty commit.'
3135 .format(details['change']))
3136 return
3138 self.gitStream.write("commit %s\n" % branch)
3139 self.gitStream.write("mark :%s\n" % details["change"])
3140 self.committedChanges.add(int(details["change"]))
3141 committer = ""
3142 if author not in self.users:
3143 self.getUserMapFromPerforceServer()
3144 committer = "%s %s %s" % (self.make_email(author), epoch, self.tz)
3146 self.gitStream.write("committer %s\n" % committer)
3148 self.gitStream.write("data <<EOT\n")
3149 self.gitStream.write(details["desc"])
3150 if len(jobs) > 0:
3151 self.gitStream.write("\nJobs: %s" % (' '.join(jobs)))
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")
3160 self.gitStream.write("EOT\n\n")
3162 if len(parent) > 0:
3163 if self.verbose:
3164 print("parent %s" % parent)
3165 self.gitStream.write("from %s\n" % parent)
3167 self.streamP4Files(files)
3168 self.gitStream.write("\n")
3170 change = int(details["change"])
3172 if change in self.labels:
3173 label = self.labels[change]
3174 labelDetails = label[0]
3175 labelRevisions = label[1]
3176 if self.verbose:
3177 print("Change %s is labelled %s" % (change, labelDetails))
3179 files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
3180 for p in self.branchPrefixes])
3182 if len(files) == len(labelRevisions):
3184 cleanedFiles = {}
3185 for info in files:
3186 if info["action"] in self.delete_actions:
3187 continue
3188 cleanedFiles[info["depotFile"]] = info["rev"]
3190 if cleanedFiles == labelRevisions:
3191 self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
3193 else:
3194 if not self.silent:
3195 print("Tag %s does not match with change %s: files do not match."
3196 % (labelDetails["label"], change))
3198 else:
3199 if not self.silent:
3200 print("Tag %s does not match with change %s: file count is different."
3201 % (labelDetails["label"], change))
3203 # Build a dictionary of changelists and labels, for "detect-labels" option.
3204 def getLabels(self):
3205 self.labels = {}
3207 l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
3208 if len(l) > 0 and not self.silent:
3209 print("Finding files belonging to labels in %s" % self.depotPaths)
3211 for output in l:
3212 label = output["label"]
3213 revisions = {}
3214 newestChange = 0
3215 if self.verbose:
3216 print("Querying files for label %s" % label)
3217 for file in p4CmdList(["files"] +
3218 ["%s...@%s" % (p, label)
3219 for p in self.depotPaths]):
3220 revisions[file["depotFile"]] = file["rev"]
3221 change = int(file["change"])
3222 if change > newestChange:
3223 newestChange = change
3225 self.labels[newestChange] = [output, revisions]
3227 if self.verbose:
3228 print("Label changes: %s" % self.labels.keys())
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:
3236 print("import p4 labels: " + ' '.join(p4Labels))
3238 ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
3239 validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
3240 if len(validLabelRegexp) == 0:
3241 validLabelRegexp = defaultLabelRegexp
3242 m = re.compile(validLabelRegexp)
3244 for name in p4Labels:
3245 commitFound = False
3247 if not m.match(name):
3248 if verbose:
3249 print("label %s does not match regexp %s" % (name,validLabelRegexp))
3250 continue
3252 if name in ignoredP4Labels:
3253 continue
3255 labelDetails = p4CmdList(['label', "-o", name])[0]
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])
3261 if 'change' in change:
3262 # find the corresponding git commit; take the oldest commit
3263 changelist = int(change['change'])
3264 if changelist in self.committedChanges:
3265 gitCommit = ":%d" % changelist # use a fast-import mark
3266 commitFound = True
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:
3271 print("importing label %s: could not find git commit for changelist %d" % (name, changelist))
3272 else:
3273 commitFound = True
3274 gitCommit = gitCommit.strip()
3276 if commitFound:
3277 # Convert from p4 time format
3278 try:
3279 tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
3280 except ValueError:
3281 print("Could not convert label time %s" % labelDetails['Update'])
3282 tmwhen = 1
3284 when = int(time.mktime(tmwhen))
3285 self.streamTag(stream, name, labelDetails, gitCommit, when)
3286 if verbose:
3287 print("p4 label %s mapped to git commit %s" % (name, gitCommit))
3288 else:
3289 if verbose:
3290 print("Label %s has no changelists - possibly deleted?" % name)
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])
3299 def guessProjectName(self):
3300 for p in self.depotPaths:
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
3308 def getBranchMapping(self):
3309 lostAndFoundBranches = set()
3311 user = gitConfig("git-p4.branchUser")
3313 for info in p4CmdList(
3314 ["branches"] + (["-u", user] if len(user) > 0 else [])):
3315 details = p4Cmd(["branch", "-o", info["branch"]])
3316 viewIdx = 0
3317 while "View%s" % viewIdx in details:
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]
3325 ## HACK
3326 if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
3327 source = source[len(self.depotPaths[0]):-4]
3328 destination = destination[len(self.depotPaths[0]):-4]
3330 if destination in self.knownBranches:
3331 if not self.silent:
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))
3334 continue
3336 self.knownBranches[destination] = source
3338 lostAndFoundBranches.discard(destination)
3340 if source not in self.knownBranches:
3341 lostAndFoundBranches.add(source)
3343 # Perforce does not strictly require branches to be defined, so we also
3344 # check git config for a branch list.
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
3357 lostAndFoundBranches.discard(destination)
3359 if source not in self.knownBranches:
3360 lostAndFoundBranches.add(source)
3363 for branch in lostAndFoundBranches:
3364 self.knownBranches[branch] = branch
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
3375 def updateOptionDict(self, d):
3376 option_keys = {}
3377 if self.keepRepoPath:
3378 option_keys['keepRepoPath'] = 1
3380 d["options"] = ' '.join(sorted(option_keys.keys()))
3382 def readOptions(self, d):
3383 self.keepRepoPath = ('options' in d
3384 and ('keepRepoPath' in d['options']))
3386 def gitRefForBranch(self, branch):
3387 if branch == "main":
3388 return self.refPrefix + "master"
3390 if len(branch) <= 0:
3391 return branch
3393 return self.refPrefix + self.projectName + branch
3395 def gitCommitByP4Change(self, ref, change):
3396 if self.verbose:
3397 print("looking in ref " + ref + " for change %s using bisect..." % change)
3399 earliestCommit = ""
3400 latestCommit = parseRevision(ref)
3402 while True:
3403 if self.verbose:
3404 print("trying: earliest %s latest %s" % (earliestCommit, latestCommit))
3405 next = read_pipe(["git", "rev-list", "--bisect",
3406 latestCommit, earliestCommit]).strip()
3407 if len(next) == 0:
3408 if self.verbose:
3409 print("argh")
3410 return ""
3411 log = extractLogMessageFromGitCommit(next)
3412 settings = extractSettingsGitLog(log)
3413 currentChange = int(settings['change'])
3414 if self.verbose:
3415 print("current change %s" % currentChange)
3417 if currentChange == change:
3418 if self.verbose:
3419 print("found %s" % next)
3420 return next
3422 if currentChange < change:
3423 earliestCommit = "^%s" % next
3424 else:
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
3429 return ""
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
3439 changes = p4ChangesForPaths([branchPrefix], range, self.changes_block_size)
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
3449 branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
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
3456 self.importChanges(changes)
3457 return True
3459 def searchParent(self, parent, branch, target):
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",
3463 "--no-merges", parent]):
3464 if line.startswith("commit "):
3465 continue
3466 commit, tree = line.strip().split(" ")
3467 if tree == targetTree:
3468 if self.verbose:
3469 print("Found parent of %s in commit %s" % (branch, commit))
3470 return commit
3471 return None
3473 def importChanges(self, changes, origin_revision=0):
3474 cnt = 1
3475 for change in changes:
3476 description = p4_describe(change)
3477 self.updateOptionDict(description)
3479 if not self.silent:
3480 sys.stdout.write("\rImporting revision %s (%d%%)" % (
3481 change, (cnt * 100) // len(changes)))
3482 sys.stdout.flush()
3483 cnt = cnt + 1
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 + "/"
3491 self.branchPrefixes = [ branchPrefix ]
3493 parent = ""
3495 filesForCommit = branches[branch]
3497 if self.verbose:
3498 print("branch is %s" % branch)
3500 self.updatedBranches.add(branch)
3502 if branch not in self.createdBranches:
3503 self.createdBranches.add(branch)
3504 parent = self.knownBranches[branch]
3505 if parent == branch:
3506 parent = ""
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);
3518 if self.verbose:
3519 print("parent determined through known branches: %s" % parent)
3521 branch = self.gitRefForBranch(branch)
3522 parent = self.gitRefForBranch(parent)
3524 if self.verbose:
3525 print("looking for initial parent for %s; current parent is %s" % (branch, parent))
3527 if len(parent) == 0 and branch in self.initialParents:
3528 parent = self.initialParents[branch]
3529 del self.initialParents[branch]
3531 blob = None
3532 if len(parent) > 0:
3533 tempBranch = "%s/%d" % (self.tempBranchLocation, change)
3534 if self.verbose:
3535 print("Creating temporary branch: " + tempBranch)
3536 self.commit(description, filesForCommit, tempBranch)
3537 self.tempBranches.append(tempBranch)
3538 self.checkpoint()
3539 blob = self.searchParent(parent, branch, tempBranch)
3540 if blob:
3541 self.commit(description, filesForCommit, branch, blob)
3542 else:
3543 if self.verbose:
3544 print("Parent of %s not found. Committing into head of %s" % (branch, parent))
3545 self.commit(description, filesForCommit, branch, parent)
3546 else:
3547 files = self.extractFilesFromCommit(description)
3548 self.commit(description, files, self.branch,
3549 self.initialParent)
3550 # only needed once, to connect to the previous commit
3551 self.initialParent = ""
3552 except IOError:
3553 print(self.gitError.read())
3554 sys.exit(1)
3556 def sync_origin_only(self):
3557 if self.syncWithOrigin:
3558 self.hasOrigin = originP4BranchesExist()
3559 if self.hasOrigin:
3560 if not self.silent:
3561 print('Syncing with origin first, using "git fetch origin"')
3562 system(["git", "fetch", "origin"])
3564 def importHeadRevision(self, revision):
3565 print("Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch))
3567 details = {}
3568 details["user"] = "git perforce import user"
3569 details["desc"] = ("Initial import of %s from the state at revision %s\n"
3570 % (' '.join(self.depotPaths), revision))
3571 details["change"] = revision
3572 newestRevision = 0
3574 fileCnt = 0
3575 fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
3577 for info in p4CmdList(["files"] + fileArgs):
3579 if 'code' in info and info['code'] == 'error':
3580 sys.stderr.write("p4 returned an error: %s\n"
3581 % info['data'])
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))
3586 sys.exit(1)
3587 if 'p4ExitCode' in info:
3588 sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
3589 sys.exit(1)
3592 change = int(info["change"])
3593 if change > newestRevision:
3594 newestRevision = change
3596 if info["action"] in self.delete_actions:
3597 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
3598 #fileCnt = fileCnt + 1
3599 continue
3601 for prop in ["depotFile", "rev", "action", "type" ]:
3602 details["%s%s" % (prop, fileCnt)] = info[prop]
3604 fileCnt = fileCnt + 1
3606 details["change"] = newestRevision
3608 # Use time from top-most change so that all git p4 clones of
3609 # the same p4 repo have the same commit SHA1s.
3610 res = p4_describe(newestRevision)
3611 details["time"] = res["time"]
3613 self.updateOptionDict(details)
3614 try:
3615 self.commit(details, self.extractFilesFromCommit(details), self.branch)
3616 except IOError as err:
3617 print("IO error with git fast-import. Is your git version recent enough?")
3618 print("IO error details: {}".format(err))
3619 print(self.gitError.read())
3622 def importRevisions(self, args, branch_arg_given):
3623 changes = []
3625 if len(self.changesFile) > 0:
3626 with open(self.changesFile) as f:
3627 output = f.readlines()
3628 changeSet = set()
3629 for line in output:
3630 changeSet.add(int(line))
3632 for change in changeSet:
3633 changes.append(change)
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:
3641 raise P4CommandException("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.")
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:
3649 raise P4CommandException("Error: branch %s does not exist." % self.branch)
3650 else:
3651 raise P4CommandException("Error: no branch %s; perhaps specify one with --branch." %
3652 self.branch)
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)
3659 if len(self.maxChanges) > 0:
3660 changes = changes[:min(int(self.maxChanges), len(changes))]
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)
3669 self.updatedBranches = set()
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)
3679 self.importChanges(changes)
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")
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
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
3705 self.gitStream.write = make_encoded_write(self.gitStream.write)
3707 def closeStreams(self):
3708 if self.gitStream is None:
3709 return
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()
3715 self.gitStream = None
3717 def run(self, args):
3718 if self.importIntoRemotes:
3719 self.refPrefix = "refs/remotes/p4/"
3720 else:
3721 self.refPrefix = "refs/heads/p4/"
3723 self.sync_origin_only()
3725 branch_arg_given = bool(self.branch)
3726 if len(self.branch) == 0:
3727 self.branch = self.refPrefix + "master"
3728 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
3729 system(["git", "update-ref", self.branch, "refs/heads/p4"])
3730 system(["git", "branch", "-D", "p4"])
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:
3737 if gitConfigBool("git-p4.useclientspec"):
3738 self.useClientSpec = True
3739 if self.useClientSpec:
3740 self.clientSpecDirs = getClientSpec()
3742 # TODO: should always look at previous commits,
3743 # merge with previous imports, if possible.
3744 if args == []:
3745 if self.hasOrigin:
3746 createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
3748 # branches holds mapping from branch name to sha1
3749 branches = p4BranchesInGit(self.importIntoRemotes)
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()
3759 if len(self.p4BranchesInGit) > 1:
3760 if not self.silent:
3761 print("Importing from/into multiple branches")
3762 self.detectBranches = True
3763 for branch in branches.keys():
3764 self.initialParents[self.refPrefix + branch] = \
3765 branches[branch]
3767 if self.verbose:
3768 print("branches: %s" % self.p4BranchesInGit)
3770 p4Change = 0
3771 for branch in self.p4BranchesInGit:
3772 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
3774 settings = extractSettingsGitLog(logMsg)
3776 self.readOptions(settings)
3777 if ('depot-paths' in settings
3778 and 'change' in settings):
3779 change = int(settings['change']) + 1
3780 p4Change = max(p4Change, change)
3782 depotPaths = sorted(settings['depot-paths'])
3783 if self.previousDepotPaths == []:
3784 self.previousDepotPaths = depotPaths
3785 else:
3786 paths = []
3787 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
3788 prev_list = prev.split("/")
3789 cur_list = cur.split("/")
3790 for i in range(0, min(len(cur_list), len(prev_list))):
3791 if cur_list[i] != prev_list[i]:
3792 i = i - 1
3793 break
3795 paths.append ("/".join(cur_list[:i + 1]))
3797 self.previousDepotPaths = paths
3799 if p4Change > 0:
3800 self.depotPaths = sorted(self.previousDepotPaths)
3801 self.changeRange = "@%s,#head" % p4Change
3802 if not self.silent and not self.detectBranches:
3803 print("Performing incremental import into %s git branch" % self.branch)
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/
3809 if not self.branch.startswith("refs/"):
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
3818 if len(args) == 0 and self.depotPaths:
3819 if not self.silent:
3820 print("Depot paths: %s" % ' '.join(self.depotPaths))
3821 else:
3822 if self.depotPaths and self.depotPaths != args:
3823 print("previous import used depot path %s and now %s was specified. "
3824 "This doesn't work!" % (' '.join (self.depotPaths),
3825 ' '.join (args)))
3826 sys.exit(1)
3828 self.depotPaths = sorted(args)
3830 revision = ""
3831 self.users = {}
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")
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 = ""
3851 elif ',' not in self.changeRange:
3852 revision = self.changeRange
3853 self.changeRange = ""
3854 p = p[:atIdx]
3855 elif p.find("#") != -1:
3856 hashIdx = p.index("#")
3857 revision = p[hashIdx:]
3858 p = p[:hashIdx]
3859 elif self.previousDepotPaths == []:
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"
3865 p = re.sub ("\.\.\.$", "", p)
3866 if not p.endswith("/"):
3867 p += "/"
3869 newPaths.append(p)
3871 self.depotPaths = newPaths
3873 # --detect-branches may change this for each branch
3874 self.branchPrefixes = self.depotPaths
3876 self.loadUserMapFromCache()
3877 self.labels = {}
3878 if self.detectLabels:
3879 self.getLabels();
3881 if self.detectBranches:
3882 ## FIXME - what's a P4 projectName ?
3883 self.projectName = self.guessProjectName()
3885 if self.hasOrigin:
3886 self.getBranchMappingFromGitBranches()
3887 else:
3888 self.getBranchMapping()
3889 if self.verbose:
3890 print("p4-git branches: %s" % self.p4BranchesInGit)
3891 print("initial parents: %s" % self.initialParents)
3892 for b in self.p4BranchesInGit:
3893 if b != "master":
3895 ## FIXME
3896 b = b[len(self.projectName):]
3897 self.createdBranches.add(b)
3899 p4_check_access()
3901 self.openStreams()
3903 err = None
3905 try:
3906 if revision:
3907 self.importHeadRevision(revision)
3908 else:
3909 self.importRevisions(args, branch_arg_given)
3911 if gitConfigBool("git-p4.importLabels"):
3912 self.importLabels = True
3914 if self.importLabels:
3915 p4Labels = getP4Labels(self.depotPaths)
3916 gitTags = getGitTags()
3918 missingP4Labels = p4Labels - gitTags
3919 self.importP4Labels(self.gitStream, missingP4Labels)
3921 except P4CommandException as e:
3922 err = e
3924 finally:
3925 self.closeStreams()
3927 if err:
3928 die(str(err))
3930 # Cleanup temporary branches created during import
3931 if self.tempBranches != []:
3932 for branch in self.tempBranches:
3933 read_pipe(["git", "update-ref", "-d", branch])
3934 os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
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])
3943 return True
3945 class P4Rebase(Command):
3946 def __init__(self):
3947 Command.__init__(self)
3948 self.options = [
3949 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
3951 self.importLabels = False
3952 self.description = ("Fetches the latest revision from perforce and "
3953 + "rebases the current work (branch) against it")
3955 def run(self, args):
3956 sync = P4Sync()
3957 sync.importLabels = self.importLabels
3958 sync.run([])
3960 return self.rebase()
3962 def rebase(self):
3963 if os.system("git update-index --refresh") != 0:
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.");
3965 if len(read_pipe(["git", "diff-index", "HEAD", "--"])) > 0:
3966 die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");
3968 [upstream, settings] = findUpstreamBranchPoint()
3969 if len(upstream) == 0:
3970 die("Cannot find upstream branchpoint for rebase")
3972 # the branchpoint may be p4/foo~3, so strip off the parent
3973 upstream = re.sub("~[0-9]+$", "", upstream)
3975 print("Rebasing the current branch onto %s" % upstream)
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", "--"])
3980 return True
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"
3986 self.usage = "usage: %prog [options] //depot/path[@revRange]"
3987 self.options += [
3988 optparse.make_option("--destination", dest="cloneDestination",
3989 action='store', default=None,
3990 help="where to leave result of the clone"),
3991 optparse.make_option("--bare", dest="cloneBare",
3992 action="store_true", default=False),
3994 self.cloneDestination = None
3995 self.needsGit = False
3996 self.cloneBare = False
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)
4003 depotDir = re.sub(r"\.\.\.$", "", depotDir)
4004 depotDir = re.sub(r"/$", "", depotDir)
4005 return os.path.split(depotDir)[1]
4007 def run(self, args):
4008 if len(args) < 1:
4009 return False
4011 if self.keepRepoPath and not self.cloneDestination:
4012 sys.stderr.write("Must specify destination for --keep-path\n")
4013 sys.exit(1)
4015 depotPaths = args
4017 if not self.cloneDestination and len(depotPaths) > 1:
4018 self.cloneDestination = depotPaths[-1]
4019 depotPaths = depotPaths[:-1]
4021 for p in depotPaths:
4022 if not p.startswith("//"):
4023 sys.stderr.write('Depot paths must start with "//": %s\n' % p)
4024 return False
4026 if not self.cloneDestination:
4027 self.cloneDestination = self.defaultDestination(args)
4029 print("Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination))
4031 if not os.path.exists(self.cloneDestination):
4032 os.makedirs(self.cloneDestination)
4033 chdir(self.cloneDestination)
4035 init_cmd = [ "git", "init" ]
4036 if self.cloneBare:
4037 init_cmd.append("--bare")
4038 retcode = subprocess.call(init_cmd)
4039 if retcode:
4040 raise subprocess.CalledProcessError(retcode, init_cmd)
4042 if not P4Sync.run(self, depotPaths):
4043 return False
4045 # create a master branch and check out a work tree
4046 if gitBranchExists(self.branch):
4047 system([ "git", "branch", currentGitBranch(), self.branch ])
4048 if not self.cloneBare:
4049 system([ "git", "checkout", "-f" ])
4050 else:
4051 print('Not checking out any branch, use ' \
4052 '"git checkout -q -b master <branch>"')
4054 # auto-set this variable if invoked with --use-client-spec
4055 if self.useClientSpec_from_options:
4056 system(["git", "config", "--bool", "git-p4.useclientspec", "true"])
4058 return True
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),
4071 self.verbose = False
4072 self.noCommit = False
4073 self.destbranch = "refs/remotes/p4-unshelved"
4075 def renameBranch(self, branch_name):
4076 """ Rename the existing branch to branch_name.N
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
4089 if not found:
4090 sys.exit("gave up trying to rename existing branch {0}".format(sync.branch))
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.
4097 for parent in (range(65535)):
4098 log = extractLogMessageFromGitCommit("{0}~{1}".format(starting_point, parent))
4099 settings = extractSettingsGitLog(log)
4100 if 'change' in settings:
4101 return settings
4103 sys.exit("could not find git-p4 commits in {0}".format(self.origin))
4105 def createShelveParent(self, change, branch_name, sync, origin):
4106 """ Create a commit matching the parent of the shelved changelist 'change'
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)
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
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'
4124 parent_files.append(f)
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))
4131 def run(self, args):
4132 if len(args) != 1:
4133 return False
4135 if not gitBranchExists(self.origin):
4136 sys.exit("origin branch {0} does not exist".format(self.origin))
4138 sync = P4Sync()
4139 changes = args
4141 # only one change at a time
4142 change = changes[0]
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
4150 sync.verbose = self.verbose
4151 sync.suppress_meta_comment = True
4153 settings = self.findLastP4Revision(self.origin)
4154 sync.depotPaths = settings['depot-paths']
4155 sync.branchPrefixes = sync.depotPaths
4157 sync.openStreams()
4158 sync.loadUserMapFromCache()
4159 sync.silent = True
4161 # create a commit for the parent of the shelved changelist
4162 self.createShelveParent(change, branch_name, sync, self.origin)
4164 # create the commit for the shelved changelist itself
4165 description = p4_describe(change, True)
4166 files = sync.extractFilesFromCommit(description, True, change)
4168 sync.commit(description, files, branch_name, "")
4169 sync.closeStreams()
4171 print("unshelved changelist {0} into {1}".format(change, branch_name))
4173 return True
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
4183 def run(self, args):
4184 if originP4BranchesExist():
4185 createOrUpdateBranchesFromOrigin()
4187 for line in read_pipe_lines(["git", "rev-parse", "--symbolic", "--remotes"]):
4188 line = line.strip()
4190 if not line.startswith('p4/') or line == "p4/HEAD":
4191 continue
4192 branch = line
4194 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
4195 settings = extractSettingsGitLog(log)
4197 print("%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]))
4198 return True
4200 class HelpFormatter(optparse.IndentedHelpFormatter):
4201 def __init__(self):
4202 optparse.IndentedHelpFormatter.__init__(self)
4204 def format_description(self, description):
4205 if description:
4206 return description + "\n"
4207 else:
4208 return ""
4210 def printUsage(commands):
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("")
4218 commands = {
4219 "submit" : P4Submit,
4220 "commit" : P4Submit,
4221 "sync" : P4Sync,
4222 "rebase" : P4Rebase,
4223 "clone" : P4Clone,
4224 "branches" : P4Branches,
4225 "unshelve" : P4Unshelve,
4228 def main():
4229 if len(sys.argv[1:]) == 0:
4230 printUsage(commands.keys())
4231 sys.exit(2)
4233 cmdName = sys.argv[1]
4234 try:
4235 klass = commands[cmdName]
4236 cmd = klass()
4237 except KeyError:
4238 print("unknown command %s" % cmdName)
4239 print("")
4240 printUsage(commands.keys())
4241 sys.exit(2)
4243 options = cmd.options
4244 cmd.gitdir = os.environ.get("GIT_DIR", None)
4246 args = sys.argv[2:]
4248 options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
4249 if cmd.needsGit:
4250 options.append(optparse.make_option("--git-dir", dest="gitdir"))
4252 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
4253 options,
4254 description = cmd.description,
4255 formatter = HelpFormatter())
4257 try:
4258 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
4259 except:
4260 parser.print_help()
4261 raise
4263 global verbose
4264 verbose = cmd.verbose
4265 if cmd.needsGit:
4266 if cmd.gitdir == None:
4267 cmd.gitdir = os.path.abspath(".git")
4268 if not isValidGitDir(cmd.gitdir):
4269 # "rev-parse --git-dir" without arguments will try $PWD/.git
4270 cmd.gitdir = read_pipe(["git", "rev-parse", "--git-dir"]).strip()
4271 if os.path.exists(cmd.gitdir):
4272 cdup = read_pipe(["git", "rev-parse", "--show-cdup"]).strip()
4273 if len(cdup) > 0:
4274 chdir(cdup);
4276 if not isValidGitDir(cmd.gitdir):
4277 if isValidGitDir(cmd.gitdir + "/.git"):
4278 cmd.gitdir += "/.git"
4279 else:
4280 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
4282 # so git commands invoked from the P4 workspace will succeed
4283 os.environ["GIT_DIR"] = cmd.gitdir
4285 if not cmd.run(args):
4286 parser.print_help()
4287 sys.exit(2)
4290 if __name__ == '__main__':
4291 main()