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