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>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
10 # pylint: disable=invalid-name,missing-docstring,too-many-arguments,broad-except
11 # pylint: disable=no-self-use,wrong-import-position,consider-iterating-dictionary
12 # pylint: disable=wrong-import-order,unused-import,too-few-public-methods
13 # pylint: disable=too-many-lines,ungrouped-imports,fixme,too-many-locals
14 # pylint: disable=line-too-long,bad-whitespace,superfluous-parens
15 # pylint: disable=too-many-statements,too-many-instance-attributes
16 # pylint: disable=too-many-branches,too-many-nested-blocks
19 if sys.version_info.major < 3 and sys.version_info.minor < 7:
20 sys.stderr.write("git-p4: requires Python 2.7 or later.\n")
39 # On python2.7 where raw_input() and input() are both availble,
40 # we want raw_input's semantics, but aliased to input for python3
42 # support basestring in python3
44 if raw_input and input:
51 # Only labels/tags matching this will be imported/exported
52 defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
54 # The block size is reduced automatically if required
55 defaultBlockSize = 1<<20
57 p4_access_checked = False
59 def p4_build_cmd(cmd):
60 """Build a suitable p4 command line.
62 This consolidates building and returning a p4 command line into one
63 location. It means that hooking into the environment, or other configuration
64 can be done more easily.
68 user = gitConfig("git-p4.user")
70 real_cmd += ["-u",user]
72 password = gitConfig("git-p4.password")
74 real_cmd += ["-P", password]
76 port = gitConfig("git-p4.port")
78 real_cmd += ["-p", port]
80 host = gitConfig("git-p4.host")
82 real_cmd += ["-H", host]
84 client = gitConfig("git-p4.client")
86 real_cmd += ["-c", client]
88 retries = gitConfigInt("git-p4.retries")
90 # Perform 3 retries by default
93 # Provide a way to not pass this option by setting git-p4.retries to 0
94 real_cmd += ["-r", str(retries)]
96 if not isinstance(cmd, list):
97 real_cmd = ' '.join(real_cmd) + ' ' + cmd
101 # now check that we can actually talk to the server
102 global p4_access_checked
103 if not p4_access_checked:
104 p4_access_checked = True # suppress access checks in p4_check_access itself
110 """ Return TRUE if the given path is a git directory (/path/to/dir/.git).
111 This won't automatically add ".git" to a directory.
113 d = read_pipe(["git", "--git-dir", path, "rev-parse", "--git-dir"], True).strip()
114 if not d or len(d) == 0:
119 def chdir(path, is_client_path=False):
120 """Do chdir to the given path, and set the PWD environment
121 variable for use by P4. It does not look at getcwd() output.
122 Since we're not using the shell, it is necessary to set the
123 PWD environment variable explicitly.
125 Normally, expand the path to force it to be absolute. This
126 addresses the use of relative path names inside P4 settings,
127 e.g. P4CONFIG=.p4config. P4 does not simply open the filename
128 as given; it looks for .p4config using PWD.
130 If is_client_path, the path was handed to us directly by p4,
131 and may be a symbolic link. Do not call os.getcwd() in this
132 case, because it will cause p4 to think that PWD is not inside
137 if not is_client_path:
139 os.environ['PWD'] = path
142 """Return free space in bytes on the disk of the given dirname."""
143 if platform.system() == 'Windows':
144 free_bytes = ctypes.c_ulonglong(0)
145 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()), None, None, ctypes.pointer(free_bytes))
146 return free_bytes.value
148 st = os.statvfs(os.getcwd())
149 return st.f_bavail * st.f_frsize
152 """ Terminate execution. Make sure that any running child processes have been wait()ed for before
158 sys.stderr.write(msg + "\n")
161 def prompt(prompt_text):
162 """ Prompt the user to choose one of the choices
164 Choices are identified in the prompt_text by square brackets around
165 a single letter option.
167 choices = set(m.group(1) for m in re.finditer(r"\[(.)\]", prompt_text))
170 sys.stdout.write(prompt_text)
172 response=sys.stdin.readline().strip().lower()
175 response = response[0]
176 if response in choices:
179 # We need different encoding/decoding strategies for text data being passed
180 # around in pipes depending on python version
182 # For python3, always encode and decode as appropriate
183 def decode_text_stream(s):
184 return s.decode() if isinstance(s, bytes) else s
185 def encode_text_stream(s):
186 return s.encode() if isinstance(s, str) else s
188 # For python2.7, pass read strings as-is, but also allow writing unicode
189 def decode_text_stream(s):
191 def encode_text_stream(s):
192 return s.encode('utf_8') if isinstance(s, unicode) else s
194 def decode_path(path):
195 """Decode a given string (bytes or otherwise) using configured path encoding options
197 encoding = gitConfig('git-p4.pathEncoding') or 'utf_8'
199 return path.decode(encoding, errors='replace') if isinstance(path, bytes) else path
204 path = path.decode(encoding, errors='replace')
206 print('Path with non-ASCII characters detected. Used {} to decode: {}'.format(encoding, path))
209 def run_git_hook(cmd, param=[]):
210 """Execute a hook if the hook exists."""
212 sys.stderr.write("Looking for hook: %s\n" % cmd)
215 hooks_path = gitConfig("core.hooksPath")
216 if len(hooks_path) <= 0:
217 hooks_path = os.path.join(os.environ["GIT_DIR"], "hooks")
219 if not isinstance(param, list):
222 # resolve hook file name, OS depdenent
223 hook_file = os.path.join(hooks_path, cmd)
224 if platform.system() == 'Windows':
225 if not os.path.isfile(hook_file):
226 # look for the file with an extension
227 files = glob.glob(hook_file + ".*")
231 hook_file = files.pop()
232 while hook_file.upper().endswith(".SAMPLE"):
233 # The file is a sample hook. We don't want it
235 hook_file = files.pop()
239 if not os.path.isfile(hook_file) or not os.access(hook_file, os.X_OK):
242 return run_hook_command(hook_file, param) == 0
244 def run_hook_command(cmd, param):
245 """Executes a git hook command
246 cmd = the command line file to be executed. This can be
247 a file that is run by OS association.
249 param = a list of parameters to pass to the cmd command
251 On windows, the extension is checked to see if it should
252 be run with the Git for Windows Bash shell. If there
253 is no file extension, the file is deemed a bash shell
254 and will be handed off to sh.exe. Otherwise, Windows
255 will be called with the shell to handle the file assocation.
257 For non Windows operating systems, the file is called
262 if platform.system() == 'Windows':
263 (root,ext) = os.path.splitext(cmd)
265 exe_path = os.environ.get("EXEPATH")
269 exe_path = os.path.join(exe_path, "bin")
270 cli = [os.path.join(exe_path, "SH.EXE")] + cli
273 return subprocess.call(cli, shell=use_shell)
276 def write_pipe(c, stdin):
278 sys.stderr.write('Writing pipe: %s\n' % str(c))
280 expand = not isinstance(c, list)
281 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
283 val = pipe.write(stdin)
286 die('Command failed: %s' % str(c))
290 def p4_write_pipe(c, stdin):
291 real_cmd = p4_build_cmd(c)
292 if bytes is not str and isinstance(stdin, str):
293 stdin = encode_text_stream(stdin)
294 return write_pipe(real_cmd, stdin)
296 def read_pipe_full(c):
297 """ Read output from command. Returns a tuple
298 of the return status, stdout text and stderr
302 sys.stderr.write('Reading pipe: %s\n' % str(c))
304 expand = not isinstance(c, list)
305 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand)
306 (out, err) = p.communicate()
307 return (p.returncode, out, decode_text_stream(err))
309 def read_pipe(c, ignore_error=False, raw=False):
310 """ Read output from command. Returns the output text on
311 success. On failure, terminates execution, unless
312 ignore_error is True, when it returns an empty string.
314 If raw is True, do not attempt to decode output text.
316 (retcode, out, err) = read_pipe_full(c)
321 die('Command failed: %s\nError: %s' % (str(c), err))
323 out = decode_text_stream(out)
326 def read_pipe_text(c):
327 """ Read output from a command with trailing whitespace stripped.
328 On error, returns None.
330 (retcode, out, err) = read_pipe_full(c)
334 return decode_text_stream(out).rstrip()
336 def p4_read_pipe(c, ignore_error=False, raw=False):
337 real_cmd = p4_build_cmd(c)
338 return read_pipe(real_cmd, ignore_error, raw=raw)
340 def read_pipe_lines(c):
342 sys.stderr.write('Reading pipe: %s\n' % str(c))
344 expand = not isinstance(c, list)
345 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
347 val = [decode_text_stream(line) for line in pipe.readlines()]
348 if pipe.close() or p.wait():
349 die('Command failed: %s' % str(c))
352 def p4_read_pipe_lines(c):
353 """Specifically invoke p4 on the command supplied. """
354 real_cmd = p4_build_cmd(c)
355 return read_pipe_lines(real_cmd)
357 def p4_has_command(cmd):
358 """Ask p4 for help on this command. If it returns an error, the
359 command does not exist in this version of p4."""
360 real_cmd = p4_build_cmd(["help", cmd])
361 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
362 stderr=subprocess.PIPE)
364 return p.returncode == 0
366 def p4_has_move_command():
367 """See if the move command exists, that it supports -k, and that
368 it has not been administratively disabled. The arguments
369 must be correct, but the filenames do not have to exist. Use
370 ones with wildcards so even if they exist, it will fail."""
372 if not p4_has_command("move"):
374 cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
375 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
376 (out, err) = p.communicate()
377 err = decode_text_stream(err)
378 # return code will be 1 in either case
379 if err.find("Invalid option") >= 0:
381 if err.find("disabled") >= 0:
383 # assume it failed because @... was invalid changelist
386 def system(cmd, ignore_error=False):
387 expand = not isinstance(cmd, list)
389 sys.stderr.write("executing %s\n" % str(cmd))
390 retcode = subprocess.call(cmd, shell=expand)
391 if retcode and not ignore_error:
392 raise CalledProcessError(retcode, cmd)
397 """Specifically invoke p4 as the system command. """
398 real_cmd = p4_build_cmd(cmd)
399 expand = not isinstance(real_cmd, list)
400 retcode = subprocess.call(real_cmd, shell=expand)
402 raise CalledProcessError(retcode, real_cmd)
404 def die_bad_access(s):
405 die("failure accessing depot: {0}".format(s.rstrip()))
407 def p4_check_access(min_expiration=1):
408 """ Check if we can access Perforce - account still logged in
410 results = p4CmdList(["login", "-s"])
412 if len(results) == 0:
413 # should never get here: always get either some results, or a p4ExitCode
414 assert("could not parse response from perforce")
418 if 'p4ExitCode' in result:
419 # p4 returned non-zero status, e.g. P4PORT invalid, or p4 not in path
420 die_bad_access("could not run p4")
422 code = result.get("code")
424 # we get here if we couldn't connect and there was nothing to unmarshal
425 die_bad_access("could not connect")
428 expiry = result.get("TicketExpiration")
431 if expiry > min_expiration:
435 die_bad_access("perforce ticket expires in {0} seconds".format(expiry))
438 # account without a timeout - all ok
441 elif code == "error":
442 data = result.get("data")
444 die_bad_access("p4 error: {0}".format(data))
446 die_bad_access("unknown error")
450 die_bad_access("unknown error code {0}".format(code))
452 _p4_version_string = None
453 def p4_version_string():
454 """Read the version string, showing just the last line, which
455 hopefully is the interesting version bit.
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
468 def p4_integrate(src, dest):
469 p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
471 def p4_sync(f, *options):
472 p4_system(["sync"] + list(options) + [wildcard_encode(f)])
475 # forcibly add file names with wildcards
476 if wildcard_present(f):
477 p4_system(["add", "-f", f])
479 p4_system(["add", f])
482 p4_system(["delete", wildcard_encode(f)])
484 def p4_edit(f, *options):
485 p4_system(["edit"] + list(options) + [wildcard_encode(f)])
488 p4_system(["revert", wildcard_encode(f)])
490 def p4_reopen(type, f):
491 p4_system(["reopen", "-t", type, wildcard_encode(f)])
493 def p4_reopen_in_change(changelist, files):
494 cmd = ["reopen", "-c", str(changelist)] + files
497 def p4_move(src, dest):
498 p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
500 def p4_last_change():
501 results = p4CmdList(["changes", "-m", "1"], skip_info=True)
502 return int(results[0]['change'])
504 def p4_describe(change, shelved=False):
505 """Make sure it returns a valid result by checking for
506 the presence of field "time". Return a dict of the
509 cmd = ["describe", "-s"]
514 ds = p4CmdList(cmd, skip_info=True)
516 die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
520 if "p4ExitCode" in d:
521 die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
524 if d["code"] == "error":
525 die("p4 describe -s %d returned error code: %s" % (change, str(d)))
528 die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
533 # Canonicalize the p4 type and return a tuple of the
534 # base type, plus any modifiers. See "p4 help filetypes"
535 # for a list and explanation.
537 def split_p4_type(p4type):
539 p4_filetypes_historical = {
540 "ctempobj": "binary+Sw",
546 "tempobj": "binary+FSw",
547 "ubinary": "binary+F",
548 "uresource": "resource+F",
549 "uxbinary": "binary+Fx",
550 "xbinary": "binary+x",
552 "xtempobj": "binary+Swx",
554 "xunicode": "unicode+x",
557 if p4type in p4_filetypes_historical:
558 p4type = p4_filetypes_historical[p4type]
560 s = p4type.split("+")
568 # return the raw p4 type of a file (text, text+ko, etc)
571 results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)])
572 return results[0]['headType']
575 # Given a type base and modifier, return a regexp matching
576 # the keywords that can be expanded in the file
578 def p4_keywords_regexp_for_type(base, type_mods):
579 if base in ("text", "unicode", "binary"):
581 if "ko" in type_mods:
583 elif "k" in type_mods:
584 kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
588 \$ # Starts with a dollar, followed by...
589 (%s) # one of the keywords, followed by...
590 (:[^$\n]+)? # possibly an old expansion, followed by...
598 # Given a file, return a regexp matching the possible
599 # RCS keywords that will be expanded, or None for files
600 # with kw expansion turned off.
602 def p4_keywords_regexp_for_file(file):
603 if not os.path.exists(file):
606 (type_base, type_mods) = split_p4_type(p4_type(file))
607 return p4_keywords_regexp_for_type(type_base, type_mods)
609 def setP4ExecBit(file, mode):
610 # Reopens an already open file and changes the execute bit to match
611 # the execute bit setting in the passed in mode.
615 if not isModeExec(mode):
616 p4Type = getP4OpenedType(file)
617 p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
618 p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
619 if p4Type[-1] == "+":
620 p4Type = p4Type[0:-1]
622 p4_reopen(p4Type, file)
624 def getP4OpenedType(file):
625 # Returns the perforce file type for the given file.
627 result = p4_read_pipe(["opened", wildcard_encode(file)])
628 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result)
630 return match.group(1)
632 die("Could not determine file type for %s (result: '%s')" % (file, result))
634 # Return the set of all p4 labels
635 def getP4Labels(depotPaths):
637 if not isinstance(depotPaths, list):
638 depotPaths = [depotPaths]
640 for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
646 # Return the set of all git tags
649 for line in read_pipe_lines(["git", "tag"]):
654 _diff_tree_pattern = None
656 def parseDiffTreeEntry(entry):
657 """Parses a single diff tree entry into its component elements.
659 See git-diff-tree(1) manpage for details about the format of the diff
660 output. This method returns a dictionary with the following elements:
662 src_mode - The mode of the source file
663 dst_mode - The mode of the destination file
664 src_sha1 - The sha1 for the source file
665 dst_sha1 - The sha1 fr the destination file
666 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
667 status_score - The score for the status (applicable for 'C' and 'R'
668 statuses). This is None if there is no score.
669 src - The path for the source file.
670 dst - The path for the destination file. This is only present for
671 copy or renames. If it is not present, this is None.
673 If the pattern is not matched, None is returned."""
675 global _diff_tree_pattern
676 if not _diff_tree_pattern:
677 _diff_tree_pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
679 match = _diff_tree_pattern.match(entry)
682 'src_mode': match.group(1),
683 'dst_mode': match.group(2),
684 'src_sha1': match.group(3),
685 'dst_sha1': match.group(4),
686 'status': match.group(5),
687 'status_score': match.group(6),
688 'src': match.group(7),
689 'dst': match.group(10)
693 def isModeExec(mode):
694 # Returns True if the given git mode represents an executable file,
696 return mode[-3:] == "755"
698 class P4Exception(Exception):
699 """ Base class for exceptions from the p4 client """
700 def __init__(self, exit_code):
701 self.p4ExitCode = exit_code
703 class P4ServerException(P4Exception):
704 """ Base class for exceptions where we get some kind of marshalled up result from the server """
705 def __init__(self, exit_code, p4_result):
706 super(P4ServerException, self).__init__(exit_code)
707 self.p4_result = p4_result
708 self.code = p4_result[0]['code']
709 self.data = p4_result[0]['data']
711 class P4RequestSizeException(P4ServerException):
712 """ One of the maxresults or maxscanrows errors """
713 def __init__(self, exit_code, p4_result, limit):
714 super(P4RequestSizeException, self).__init__(exit_code, p4_result)
717 class P4CommandException(P4Exception):
718 """ Something went wrong calling p4 which means we have to give up """
719 def __init__(self, msg):
725 def isModeExecChanged(src_mode, dst_mode):
726 return isModeExec(src_mode) != isModeExec(dst_mode)
728 def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,
729 errors_as_exceptions=False):
731 if not isinstance(cmd, list):
738 cmd = p4_build_cmd(cmd)
740 sys.stderr.write("Opening pipe: %s\n" % str(cmd))
742 # Use a temporary file to avoid deadlocks without
743 # subprocess.communicate(), which would put another copy
744 # of stdout into memory.
746 if stdin is not None:
747 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
748 if not isinstance(stdin, list):
749 stdin_file.write(stdin)
752 stdin_file.write(encode_text_stream(i))
753 stdin_file.write(b'\n')
757 p4 = subprocess.Popen(cmd,
760 stdout=subprocess.PIPE)
765 entry = marshal.load(p4.stdout)
767 # Decode unmarshalled dict to use str keys and values where it
768 # is expected that the data is always valid UTF-8.
769 text_keys = ('action', 'change', 'Change', 'Client', 'code',
770 'fileSize', 'headAction', 'headRev', 'headType',
771 'Jobs', 'label', 'options', 'perm', 'rev', 'Root',
772 'Status', 'type', 'Update')
773 text_key_prefixes = ('action', 'File', 'job', 'rev', 'type',
776 for key, value in entry.items():
778 if isinstance(value, bytes) and (key in text_keys or
779 any(filter(key.startswith, text_key_prefixes))):
781 value = value.decode()
782 except UnicodeDecodeError:
783 fallbackEncoding = gitConfig("git-p4.fallbackEncoding").lower() or 'none'
784 if fallbackEncoding == 'none':
785 raise Exception("UTF-8 decoding failed. Consider using git config git-p4.fallbackEncoding")
786 elif fallbackEncoding == 'replace':
787 value = value.decode(errors='replace')
789 value = value.decode(encoding=fallbackEncoding)
790 decoded_entry[key] = value
791 # Parse out data if it's an error response
792 if decoded_entry.get('code') == 'error' and 'data' in decoded_entry:
793 decoded_entry['data'] = decoded_entry['data'].decode()
794 entry = decoded_entry
796 if 'code' in entry and entry['code'] == 'info':
806 if errors_as_exceptions:
808 data = result[0].get('data')
810 m = re.search('Too many rows scanned \(over (\d+)\)', data)
812 m = re.search('Request too large \(over (\d+)\)', data)
815 limit = int(m.group(1))
816 raise P4RequestSizeException(exitCode, result, limit)
818 raise P4ServerException(exitCode, result)
820 raise P4Exception(exitCode)
823 entry["p4ExitCode"] = exitCode
829 list = p4CmdList(cmd)
835 def p4Where(depotPath):
836 if not depotPath.endswith("/"):
838 depotPathLong = depotPath + "..."
839 outputList = p4CmdList(["where", depotPathLong])
841 for entry in outputList:
842 if "depotFile" in entry:
843 # Search for the base client side depot path, as long as it starts with the branch's P4 path.
844 # The base path always ends with "/...".
845 entry_path = decode_path(entry['depotFile'])
846 if entry_path.find(depotPath) == 0 and entry_path[-4:] == "/...":
849 elif "data" in entry:
850 data = entry.get("data")
851 space = data.find(" ")
852 if data[:space] == depotPath:
857 if output["code"] == "error":
861 clientPath = decode_path(output['path'])
862 elif "data" in output:
863 data = output.get("data")
864 lastSpace = data.rfind(b" ")
865 clientPath = decode_path(data[lastSpace + 1:])
867 if clientPath.endswith("..."):
868 clientPath = clientPath[:-3]
871 def currentGitBranch():
872 return read_pipe_text(["git", "symbolic-ref", "--short", "-q", "HEAD"])
874 def isValidGitDir(path):
875 return git_dir(path) != None
877 def parseRevision(ref):
878 return read_pipe("git rev-parse %s" % ref).strip()
880 def branchExists(ref):
881 rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
885 def extractLogMessageFromGitCommit(commit):
888 ## fixme: title is first line of commit, not 1st paragraph.
890 for log in read_pipe_lines(["git", "cat-file", "commit", commit]):
899 def extractSettingsGitLog(log):
901 for line in log.split("\n"):
903 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
907 assignments = m.group(1).split (':')
908 for a in assignments:
910 key = vals[0].strip()
911 val = ('='.join (vals[1:])).strip()
912 if val.endswith ('\"') and val.startswith('"'):
917 paths = values.get("depot-paths")
919 paths = values.get("depot-path")
921 values['depot-paths'] = paths.split(',')
924 def gitBranchExists(branch):
925 proc = subprocess.Popen(["git", "rev-parse", branch],
926 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
927 return proc.wait() == 0;
929 def gitUpdateRef(ref, newvalue):
930 subprocess.check_call(["git", "update-ref", ref, newvalue])
932 def gitDeleteRef(ref):
933 subprocess.check_call(["git", "update-ref", "-d", ref])
937 def gitConfig(key, typeSpecifier=None):
938 if key not in _gitConfig:
939 cmd = [ "git", "config" ]
941 cmd += [ typeSpecifier ]
943 s = read_pipe(cmd, ignore_error=True)
944 _gitConfig[key] = s.strip()
945 return _gitConfig[key]
947 def gitConfigBool(key):
948 """Return a bool, using git config --bool. It is True only if the
949 variable is set to true, and False if set to false or not present
952 if key not in _gitConfig:
953 _gitConfig[key] = gitConfig(key, '--bool') == "true"
954 return _gitConfig[key]
956 def gitConfigInt(key):
957 if key not in _gitConfig:
958 cmd = [ "git", "config", "--int", key ]
959 s = read_pipe(cmd, ignore_error=True)
962 _gitConfig[key] = int(gitConfig(key, '--int'))
964 _gitConfig[key] = None
965 return _gitConfig[key]
967 def gitConfigList(key, raw=False):
968 if key not in _gitConfig:
969 s = read_pipe(["git", "config", "--get-all", key], ignore_error=True, raw=raw)
970 _gitConfig[key] = s.strip().splitlines()
971 if _gitConfig[key] == [''] or _gitConfig[key] == [b'']:
973 return _gitConfig[key]
975 def p4BranchesInGit(branchesAreInRemotes=True):
976 """Find all the branches whose names start with "p4/", looking
977 in remotes or heads as specified by the argument. Return
978 a dictionary of { branch: revision } for each one found.
979 The branch names are the short names, without any
984 cmdline = "git rev-parse --symbolic "
985 if branchesAreInRemotes:
986 cmdline += "--remotes"
988 cmdline += "--branches"
990 for line in read_pipe_lines(cmdline):
994 if not line.startswith('p4/'):
996 # special symbolic ref to p4/master
997 if line == "p4/HEAD":
1000 # strip off p4/ prefix
1001 branch = line[len("p4/"):]
1003 branches[branch] = parseRevision(line)
1007 def branch_exists(branch):
1008 """Make sure that the given ref name really exists."""
1010 cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
1011 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
1012 out, _ = p.communicate()
1013 out = decode_text_stream(out)
1016 # expect exactly one line of output: the branch name
1017 return out.rstrip() == branch
1019 def findUpstreamBranchPoint(head = "HEAD"):
1020 branches = p4BranchesInGit()
1021 # map from depot-path to branch name
1022 branchByDepotPath = {}
1023 for branch in branches.keys():
1024 tip = branches[branch]
1025 log = extractLogMessageFromGitCommit(tip)
1026 settings = extractSettingsGitLog(log)
1027 if "depot-paths" in settings:
1028 paths = ",".join(settings["depot-paths"])
1029 branchByDepotPath[paths] = "remotes/p4/" + branch
1033 while parent < 65535:
1034 commit = head + "~%s" % parent
1035 log = extractLogMessageFromGitCommit(commit)
1036 settings = extractSettingsGitLog(log)
1037 if "depot-paths" in settings:
1038 paths = ",".join(settings["depot-paths"])
1039 if paths in branchByDepotPath:
1040 return [branchByDepotPath[paths], settings]
1044 return ["", settings]
1046 def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
1048 print("Creating/updating branch(es) in %s based on origin branch(es)"
1051 originPrefix = "origin/p4/"
1053 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
1055 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
1058 headName = line[len(originPrefix):]
1059 remoteHead = localRefPrefix + headName
1062 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
1063 if ('depot-paths' not in original
1064 or 'change' not in original):
1068 if not gitBranchExists(remoteHead):
1070 print("creating %s" % remoteHead)
1073 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
1074 if 'change' in settings:
1075 if settings['depot-paths'] == original['depot-paths']:
1076 originP4Change = int(original['change'])
1077 p4Change = int(settings['change'])
1078 if originP4Change > p4Change:
1079 print("%s (%s) is newer than %s (%s). "
1080 "Updating p4 branch from origin."
1081 % (originHead, originP4Change,
1082 remoteHead, p4Change))
1085 print("Ignoring: %s was imported from %s while "
1086 "%s was imported from %s"
1087 % (originHead, ','.join(original['depot-paths']),
1088 remoteHead, ','.join(settings['depot-paths'])))
1091 system("git update-ref %s %s" % (remoteHead, originHead))
1093 def originP4BranchesExist():
1094 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
1097 def p4ParseNumericChangeRange(parts):
1098 changeStart = int(parts[0][1:])
1099 if parts[1] == '#head':
1100 changeEnd = p4_last_change()
1102 changeEnd = int(parts[1])
1104 return (changeStart, changeEnd)
1106 def chooseBlockSize(blockSize):
1110 return defaultBlockSize
1112 def p4ChangesForPaths(depotPaths, changeRange, requestedBlockSize):
1115 # Parse the change range into start and end. Try to find integer
1116 # revision ranges as these can be broken up into blocks to avoid
1117 # hitting server-side limits (maxrows, maxscanresults). But if
1118 # that doesn't work, fall back to using the raw revision specifier
1119 # strings, without using block mode.
1121 if changeRange is None or changeRange == '':
1123 changeEnd = p4_last_change()
1124 block_size = chooseBlockSize(requestedBlockSize)
1126 parts = changeRange.split(',')
1127 assert len(parts) == 2
1129 (changeStart, changeEnd) = p4ParseNumericChangeRange(parts)
1130 block_size = chooseBlockSize(requestedBlockSize)
1132 changeStart = parts[0][1:]
1133 changeEnd = parts[1]
1134 if requestedBlockSize:
1135 die("cannot use --changes-block-size with non-numeric revisions")
1140 # Retrieve changes a block at a time, to prevent running
1141 # into a MaxResults/MaxScanRows error from the server. If
1142 # we _do_ hit one of those errors, turn down the block size
1148 end = min(changeEnd, changeStart + block_size)
1149 revisionRange = "%d,%d" % (changeStart, end)
1151 revisionRange = "%s,%s" % (changeStart, changeEnd)
1153 for p in depotPaths:
1154 cmd += ["%s...@%s" % (p, revisionRange)]
1158 result = p4CmdList(cmd, errors_as_exceptions=True)
1159 except P4RequestSizeException as e:
1161 block_size = e.limit
1162 elif block_size > e.limit:
1163 block_size = e.limit
1165 block_size = max(2, block_size // 2)
1167 if verbose: print("block size error, retrying with block size {0}".format(block_size))
1169 except P4Exception as e:
1170 die('Error retrieving changes description ({0})'.format(e.p4ExitCode))
1172 # Insert changes in chronological order
1173 for entry in reversed(result):
1174 if 'change' not in entry:
1176 changes.add(int(entry['change']))
1181 if end >= changeEnd:
1184 changeStart = end + 1
1186 changes = sorted(changes)
1189 def p4PathStartsWith(path, prefix):
1190 # This method tries to remedy a potential mixed-case issue:
1192 # If UserA adds //depot/DirA/file1
1193 # and UserB adds //depot/dira/file2
1195 # we may or may not have a problem. If you have core.ignorecase=true,
1196 # we treat DirA and dira as the same directory
1197 if gitConfigBool("core.ignorecase"):
1198 return path.lower().startswith(prefix.lower())
1199 return path.startswith(prefix)
1201 def getClientSpec():
1202 """Look at the p4 client spec, create a View() object that contains
1203 all the mappings, and return it."""
1205 specList = p4CmdList("client -o")
1206 if len(specList) != 1:
1207 die('Output from "client -o" is %d lines, expecting 1' %
1210 # dictionary of all client parameters
1213 # the //client/ name
1214 client_name = entry["Client"]
1216 # just the keys that start with "View"
1217 view_keys = [ k for k in entry.keys() if k.startswith("View") ]
1219 # hold this new View
1220 view = View(client_name)
1222 # append the lines, in order, to the view
1223 for view_num in range(len(view_keys)):
1224 k = "View%d" % view_num
1225 if k not in view_keys:
1226 die("Expected view key %s missing" % k)
1227 view.append(entry[k])
1231 def getClientRoot():
1232 """Grab the client directory."""
1234 output = p4CmdList("client -o")
1235 if len(output) != 1:
1236 die('Output from "client -o" is %d lines, expecting 1' % len(output))
1239 if "Root" not in entry:
1240 die('Client has no "Root"')
1242 return entry["Root"]
1245 # P4 wildcards are not allowed in filenames. P4 complains
1246 # if you simply add them, but you can force it with "-f", in
1247 # which case it translates them into %xx encoding internally.
1249 def wildcard_decode(path):
1250 # Search for and fix just these four characters. Do % last so
1251 # that fixing it does not inadvertently create new %-escapes.
1252 # Cannot have * in a filename in windows; untested as to
1253 # what p4 would do in such a case.
1254 if not platform.system() == "Windows":
1255 path = path.replace("%2A", "*")
1256 path = path.replace("%23", "#") \
1257 .replace("%40", "@") \
1258 .replace("%25", "%")
1261 def wildcard_encode(path):
1262 # do % first to avoid double-encoding the %s introduced here
1263 path = path.replace("%", "%25") \
1264 .replace("*", "%2A") \
1265 .replace("#", "%23") \
1266 .replace("@", "%40")
1269 def wildcard_present(path):
1270 m = re.search("[*#@%]", path)
1271 return m is not None
1273 class LargeFileSystem(object):
1274 """Base class for large file system support."""
1276 def __init__(self, writeToGitStream):
1277 self.largeFiles = set()
1278 self.writeToGitStream = writeToGitStream
1280 def generatePointer(self, cloneDestination, contentFile):
1281 """Return the content of a pointer file that is stored in Git instead of
1282 the actual content."""
1283 assert False, "Method 'generatePointer' required in " + self.__class__.__name__
1285 def pushFile(self, localLargeFile):
1286 """Push the actual content which is not stored in the Git repository to
1288 assert False, "Method 'pushFile' required in " + self.__class__.__name__
1290 def hasLargeFileExtension(self, relPath):
1291 return functools.reduce(
1292 lambda a, b: a or b,
1293 [relPath.endswith('.' + e) for e in gitConfigList('git-p4.largeFileExtensions')],
1297 def generateTempFile(self, contents):
1298 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False)
1300 contentFile.write(d)
1302 return contentFile.name
1304 def exceedsLargeFileThreshold(self, relPath, contents):
1305 if gitConfigInt('git-p4.largeFileThreshold'):
1306 contentsSize = sum(len(d) for d in contents)
1307 if contentsSize > gitConfigInt('git-p4.largeFileThreshold'):
1309 if gitConfigInt('git-p4.largeFileCompressedThreshold'):
1310 contentsSize = sum(len(d) for d in contents)
1311 if contentsSize <= gitConfigInt('git-p4.largeFileCompressedThreshold'):
1313 contentTempFile = self.generateTempFile(contents)
1314 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=True)
1315 with zipfile.ZipFile(compressedContentFile, mode='w') as zf:
1316 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED)
1317 compressedContentsSize = zf.infolist()[0].compress_size
1318 os.remove(contentTempFile)
1319 if compressedContentsSize > gitConfigInt('git-p4.largeFileCompressedThreshold'):
1323 def addLargeFile(self, relPath):
1324 self.largeFiles.add(relPath)
1326 def removeLargeFile(self, relPath):
1327 self.largeFiles.remove(relPath)
1329 def isLargeFile(self, relPath):
1330 return relPath in self.largeFiles
1332 def processContent(self, git_mode, relPath, contents):
1333 """Processes the content of git fast import. This method decides if a
1334 file is stored in the large file system and handles all necessary
1336 if self.exceedsLargeFileThreshold(relPath, contents) or self.hasLargeFileExtension(relPath):
1337 contentTempFile = self.generateTempFile(contents)
1338 (pointer_git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)
1339 if pointer_git_mode:
1340 git_mode = pointer_git_mode
1342 # Move temp file to final location in large file system
1343 largeFileDir = os.path.dirname(localLargeFile)
1344 if not os.path.isdir(largeFileDir):
1345 os.makedirs(largeFileDir)
1346 shutil.move(contentTempFile, localLargeFile)
1347 self.addLargeFile(relPath)
1348 if gitConfigBool('git-p4.largeFilePush'):
1349 self.pushFile(localLargeFile)
1351 sys.stderr.write("%s moved to large file system (%s)\n" % (relPath, localLargeFile))
1352 return (git_mode, contents)
1354 class MockLFS(LargeFileSystem):
1355 """Mock large file system for testing."""
1357 def generatePointer(self, contentFile):
1358 """The pointer content is the original content prefixed with "pointer-".
1359 The local filename of the large file storage is derived from the file content.
1361 with open(contentFile, 'r') as f:
1364 pointerContents = 'pointer-' + content
1365 localLargeFile = os.path.join(os.getcwd(), '.git', 'mock-storage', 'local', content[:-1])
1366 return (gitMode, pointerContents, localLargeFile)
1368 def pushFile(self, localLargeFile):
1369 """The remote filename of the large file storage is the same as the local
1370 one but in a different directory.
1372 remotePath = os.path.join(os.path.dirname(localLargeFile), '..', 'remote')
1373 if not os.path.exists(remotePath):
1374 os.makedirs(remotePath)
1375 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))
1377 class GitLFS(LargeFileSystem):
1378 """Git LFS as backend for the git-p4 large file system.
1379 See https://git-lfs.github.com/ for details."""
1381 def __init__(self, *args):
1382 LargeFileSystem.__init__(self, *args)
1383 self.baseGitAttributes = []
1385 def generatePointer(self, contentFile):
1386 """Generate a Git LFS pointer for the content. Return LFS Pointer file
1387 mode and content which is stored in the Git repository instead of
1388 the actual content. Return also the new location of the actual
1391 if os.path.getsize(contentFile) == 0:
1392 return (None, '', None)
1394 pointerProcess = subprocess.Popen(
1395 ['git', 'lfs', 'pointer', '--file=' + contentFile],
1396 stdout=subprocess.PIPE
1398 pointerFile = decode_text_stream(pointerProcess.stdout.read())
1399 if pointerProcess.wait():
1400 os.remove(contentFile)
1401 die('git-lfs pointer command failed. Did you install the extension?')
1403 # Git LFS removed the preamble in the output of the 'pointer' command
1404 # starting from version 1.2.0. Check for the preamble here to support
1406 # c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b43
1407 if pointerFile.startswith('Git LFS pointer for'):
1408 pointerFile = re.sub(r'Git LFS pointer for.*\n\n', '', pointerFile)
1410 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)
1411 # if someone use external lfs.storage ( not in local repo git )
1412 lfs_path = gitConfig('lfs.storage')
1415 if not os.path.isabs(lfs_path):
1416 lfs_path = os.path.join(os.getcwd(), '.git', lfs_path)
1417 localLargeFile = os.path.join(
1419 'objects', oid[:2], oid[2:4],
1422 # LFS Spec states that pointer files should not have the executable bit set.
1424 return (gitMode, pointerFile, localLargeFile)
1426 def pushFile(self, localLargeFile):
1427 uploadProcess = subprocess.Popen(
1428 ['git', 'lfs', 'push', '--object-id', 'origin', os.path.basename(localLargeFile)]
1430 if uploadProcess.wait():
1431 die('git-lfs push command failed. Did you define a remote?')
1433 def generateGitAttributes(self):
1435 self.baseGitAttributes +
1439 '# Git LFS (see https://git-lfs.github.com/)\n',
1442 ['*.' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1443 for f in sorted(gitConfigList('git-p4.largeFileExtensions'))
1445 ['/' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1446 for f in sorted(self.largeFiles) if not self.hasLargeFileExtension(f)
1450 def addLargeFile(self, relPath):
1451 LargeFileSystem.addLargeFile(self, relPath)
1452 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
1454 def removeLargeFile(self, relPath):
1455 LargeFileSystem.removeLargeFile(self, relPath)
1456 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
1458 def processContent(self, git_mode, relPath, contents):
1459 if relPath == '.gitattributes':
1460 self.baseGitAttributes = contents
1461 return (git_mode, self.generateGitAttributes())
1463 return LargeFileSystem.processContent(self, git_mode, relPath, contents)
1466 delete_actions = ( "delete", "move/delete", "purge" )
1467 add_actions = ( "add", "branch", "move/add" )
1470 self.usage = "usage: %prog [options]"
1471 self.needsGit = True
1472 self.verbose = False
1474 # This is required for the "append" update_shelve action
1475 def ensure_value(self, attr, value):
1476 if not hasattr(self, attr) or getattr(self, attr) is None:
1477 setattr(self, attr, value)
1478 return getattr(self, attr)
1482 self.userMapFromPerforceServer = False
1483 self.myP4UserId = None
1487 return self.myP4UserId
1489 results = p4CmdList("user -o")
1492 self.myP4UserId = r['User']
1494 die("Could not find your p4 user id")
1496 def p4UserIsMe(self, p4User):
1497 # return True if the given p4 user is actually me
1498 me = self.p4UserId()
1499 if not p4User or p4User != me:
1504 def getUserCacheFilename(self):
1505 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
1506 return home + "/.gitp4-usercache.txt"
1508 def getUserMapFromPerforceServer(self):
1509 if self.userMapFromPerforceServer:
1514 for output in p4CmdList("users"):
1515 if "User" not in output:
1517 self.users[output["User"]] = output["FullName"] + b" <" + output["Email"] + b">"
1518 self.emails[output["Email"]] = output["User"]
1520 mapUserConfigRegex = re.compile(br"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE)
1521 for mapUserConfig in gitConfigList("git-p4.mapUser", raw=True):
1522 mapUser = mapUserConfigRegex.findall(mapUserConfig)
1523 if mapUser and len(mapUser[0]) == 3:
1524 user = mapUser[0][0]
1525 fullname = mapUser[0][1]
1526 email = mapUser[0][2]
1527 self.users[user] = fullname + b" <" + email + b">"
1528 self.emails[email] = user
1531 for (key, val) in self.users.items():
1532 s += b"%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
1534 open(self.getUserCacheFilename(), 'wb').write(s)
1535 self.userMapFromPerforceServer = True
1537 def loadUserMapFromCache(self):
1539 self.userMapFromPerforceServer = False
1541 cache = open(self.getUserCacheFilename(), 'rb')
1542 lines = cache.readlines()
1545 entry = line.strip().split(b"\t")
1546 self.users[entry[0]] = entry[1]
1548 self.getUserMapFromPerforceServer()
1550 class P4Debug(Command):
1552 Command.__init__(self)
1554 self.description = "A tool to debug the output of p4 -G."
1555 self.needsGit = False
1557 def run(self, args):
1559 for output in p4CmdList(args):
1560 print('Element: %d' % j)
1565 class P4RollBack(Command):
1567 Command.__init__(self)
1569 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
1571 self.description = "A tool to debug the multi-branch import. Don't use :)"
1572 self.rollbackLocalBranches = False
1574 def run(self, args):
1577 maxChange = int(args[0])
1579 if "p4ExitCode" in p4Cmd("changes -m 1"):
1580 die("Problems executing p4");
1582 if self.rollbackLocalBranches:
1583 refPrefix = "refs/heads/"
1584 lines = read_pipe_lines("git rev-parse --symbolic --branches")
1586 refPrefix = "refs/remotes/"
1587 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
1590 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
1592 ref = refPrefix + line
1593 log = extractLogMessageFromGitCommit(ref)
1594 settings = extractSettingsGitLog(log)
1596 depotPaths = settings['depot-paths']
1597 change = settings['change']
1601 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
1602 for p in depotPaths]))) == 0:
1603 print("Branch %s did not exist at change %s, deleting." % (ref, maxChange))
1604 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
1607 while change and int(change) > maxChange:
1610 print("%s is at %s ; rewinding towards %s" % (ref, change, maxChange))
1611 system("git update-ref %s \"%s^\"" % (ref, ref))
1612 log = extractLogMessageFromGitCommit(ref)
1613 settings = extractSettingsGitLog(log)
1616 depotPaths = settings['depot-paths']
1617 change = settings['change']
1620 print("%s rewound to %s" % (ref, change))
1624 class P4Submit(Command, P4UserMap):
1626 conflict_behavior_choices = ("ask", "skip", "quit")
1629 Command.__init__(self)
1630 P4UserMap.__init__(self)
1632 optparse.make_option("--origin", dest="origin"),
1633 optparse.make_option("-M", dest="detectRenames", action="store_true"),
1634 # preserve the user, requires relevant p4 permissions
1635 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
1636 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
1637 optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
1638 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
1639 optparse.make_option("--conflict", dest="conflict_behavior",
1640 choices=self.conflict_behavior_choices),
1641 optparse.make_option("--branch", dest="branch"),
1642 optparse.make_option("--shelve", dest="shelve", action="store_true",
1643 help="Shelve instead of submit. Shelved files are reverted, "
1644 "restoring the workspace to the state before the shelve"),
1645 optparse.make_option("--update-shelve", dest="update_shelve", action="append", type="int",
1646 metavar="CHANGELIST",
1647 help="update an existing shelved changelist, implies --shelve, "
1648 "repeat in-order for multiple shelved changelists"),
1649 optparse.make_option("--commit", dest="commit", metavar="COMMIT",
1650 help="submit only the specified commit(s), one commit or xxx..xxx"),
1651 optparse.make_option("--disable-rebase", dest="disable_rebase", action="store_true",
1652 help="Disable rebase after submit is completed. Can be useful if you "
1653 "work from a local git branch that is not master"),
1654 optparse.make_option("--disable-p4sync", dest="disable_p4sync", action="store_true",
1655 help="Skip Perforce sync of p4/master after submit or shelve"),
1656 optparse.make_option("--no-verify", dest="no_verify", action="store_true",
1657 help="Bypass p4-pre-submit and p4-changelist hooks"),
1659 self.description = """Submit changes from git to the perforce depot.\n
1660 The `p4-pre-submit` hook is executed if it exists and is executable. It
1661 can be bypassed with the `--no-verify` command line option. The hook takes
1662 no parameters and nothing from standard input. Exiting with a non-zero status
1663 from this script prevents `git-p4 submit` from launching.
1665 One usage scenario is to run unit tests in the hook.
1667 The `p4-prepare-changelist` hook is executed right after preparing the default
1668 changelist message and before the editor is started. It takes one parameter,
1669 the name of the file that contains the changelist text. Exiting with a non-zero
1670 status from the script will abort the process.
1672 The purpose of the hook is to edit the message file in place, and it is not
1673 supressed by the `--no-verify` option. This hook is called even if
1674 `--prepare-p4-only` is set.
1676 The `p4-changelist` hook is executed after the changelist message has been
1677 edited by the user. It can be bypassed with the `--no-verify` option. It
1678 takes a single parameter, the name of the file that holds the proposed
1679 changelist text. Exiting with a non-zero status causes the command to abort.
1681 The hook is allowed to edit the changelist file and can be used to normalize
1682 the text into some project standard format. It can also be used to refuse the
1683 Submit after inspect the message file.
1685 The `p4-post-changelist` hook is invoked after the submit has successfully
1686 occurred in P4. It takes no parameters and is meant primarily for notification
1687 and cannot affect the outcome of the git p4 submit action.
1690 self.usage += " [name of git branch to submit into perforce depot]"
1692 self.detectRenames = False
1693 self.preserveUser = gitConfigBool("git-p4.preserveUser")
1694 self.dry_run = False
1696 self.update_shelve = list()
1698 self.disable_rebase = gitConfigBool("git-p4.disableRebase")
1699 self.disable_p4sync = gitConfigBool("git-p4.disableP4Sync")
1700 self.prepare_p4_only = False
1701 self.conflict_behavior = None
1702 self.isWindows = (platform.system() == "Windows")
1703 self.exportLabels = False
1704 self.p4HasMoveCommand = p4_has_move_command()
1706 self.no_verify = False
1708 if gitConfig('git-p4.largeFileSystem'):
1709 die("Large file system not supported for git-p4 submit command. Please remove it from config.")
1712 if len(p4CmdList("opened ...")) > 0:
1713 die("You have files opened with perforce! Close them before starting the sync.")
1715 def separate_jobs_from_description(self, message):
1716 """Extract and return a possible Jobs field in the commit
1717 message. It goes into a separate section in the p4 change
1720 A jobs line starts with "Jobs:" and looks like a new field
1721 in a form. Values are white-space separated on the same
1722 line or on following lines that start with a tab.
1724 This does not parse and extract the full git commit message
1725 like a p4 form. It just sees the Jobs: line as a marker
1726 to pass everything from then on directly into the p4 form,
1727 but outside the description section.
1729 Return a tuple (stripped log message, jobs string)."""
1731 m = re.search(r'^Jobs:', message, re.MULTILINE)
1733 return (message, None)
1735 jobtext = message[m.start():]
1736 stripped_message = message[:m.start()].rstrip()
1737 return (stripped_message, jobtext)
1739 def prepareLogMessage(self, template, message, jobs):
1740 """Edits the template returned from "p4 change -o" to insert
1741 the message in the Description field, and the jobs text in
1745 inDescriptionSection = False
1747 for line in template.split("\n"):
1748 if line.startswith("#"):
1749 result += line + "\n"
1752 if inDescriptionSection:
1753 if line.startswith("Files:") or line.startswith("Jobs:"):
1754 inDescriptionSection = False
1755 # insert Jobs section
1757 result += jobs + "\n"
1761 if line.startswith("Description:"):
1762 inDescriptionSection = True
1764 for messageLine in message.split("\n"):
1765 line += "\t" + messageLine + "\n"
1767 result += line + "\n"
1771 def patchRCSKeywords(self, file, pattern):
1772 # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
1773 (handle, outFileName) = tempfile.mkstemp(dir='.')
1775 outFile = os.fdopen(handle, "w+")
1776 inFile = open(file, "r")
1777 regexp = re.compile(pattern, re.VERBOSE)
1778 for line in inFile.readlines():
1779 line = regexp.sub(r'$\1$', line)
1783 # Forcibly overwrite the original file
1785 shutil.move(outFileName, file)
1787 # cleanup our temporary file
1788 os.unlink(outFileName)
1789 print("Failed to strip RCS keywords in %s" % file)
1792 print("Patched up RCS keywords in %s" % file)
1794 def p4UserForCommit(self,id):
1795 # Return the tuple (perforce user,git email) for a given git commit id
1796 self.getUserMapFromPerforceServer()
1797 gitEmail = read_pipe(["git", "log", "--max-count=1",
1798 "--format=%ae", id], raw=True)
1799 gitEmail = gitEmail.strip()
1800 if gitEmail not in self.emails:
1801 return (None,gitEmail)
1803 return (self.emails[gitEmail],gitEmail)
1805 def checkValidP4Users(self,commits):
1806 # check if any git authors cannot be mapped to p4 users
1808 (user,email) = self.p4UserForCommit(id)
1810 msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
1811 if gitConfigBool("git-p4.allowMissingP4Users"):
1814 die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
1816 def lastP4Changelist(self):
1817 # Get back the last changelist number submitted in this client spec. This
1818 # then gets used to patch up the username in the change. If the same
1819 # client spec is being used by multiple processes then this might go
1821 results = p4CmdList("client -o") # find the current client
1825 client = r['Client']
1828 die("could not get client spec")
1829 results = p4CmdList(["changes", "-c", client, "-m", "1"])
1833 die("Could not get changelist number for last submit - cannot patch up user details")
1835 def modifyChangelistUser(self, changelist, newUser):
1836 # fixup the user field of a changelist after it has been submitted.
1837 changes = p4CmdList("change -o %s" % changelist)
1838 if len(changes) != 1:
1839 die("Bad output from p4 change modifying %s to user %s" %
1840 (changelist, newUser))
1843 if c['User'] == newUser: return # nothing to do
1845 # p4 does not understand format version 3 and above
1846 input = marshal.dumps(c, 2)
1848 result = p4CmdList("change -f -i", stdin=input)
1851 if r['code'] == 'error':
1852 die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
1854 print("Updated user field for changelist %s to %s" % (changelist, newUser))
1856 die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
1858 def canChangeChangelists(self):
1859 # check to see if we have p4 admin or super-user permissions, either of
1860 # which are required to modify changelists.
1861 results = p4CmdList(["protects", self.depotPath])
1864 if r['perm'] == 'admin':
1866 if r['perm'] == 'super':
1870 def prepareSubmitTemplate(self, changelist=None):
1871 """Run "p4 change -o" to grab a change specification template.
1872 This does not use "p4 -G", as it is nice to keep the submission
1873 template in original order, since a human might edit it.
1875 Remove lines in the Files section that show changes to files
1876 outside the depot path we're committing into."""
1878 [upstream, settings] = findUpstreamBranchPoint()
1881 # A Perforce Change Specification.
1883 # Change: The change number. 'new' on a new changelist.
1884 # Date: The date this specification was last modified.
1885 # Client: The client on which the changelist was created. Read-only.
1886 # User: The user who created the changelist.
1887 # Status: Either 'pending' or 'submitted'. Read-only.
1888 # Type: Either 'public' or 'restricted'. Default is 'public'.
1889 # Description: Comments about the changelist. Required.
1890 # Jobs: What opened jobs are to be closed by this changelist.
1891 # You may delete jobs from this list. (New changelists only.)
1892 # Files: What opened files from the default changelist are to be added
1893 # to this changelist. You may delete files from this list.
1894 # (New changelists only.)
1897 inFilesSection = False
1899 args = ['change', '-o']
1901 args.append(str(changelist))
1902 for entry in p4CmdList(args):
1903 if 'code' not in entry:
1905 if entry['code'] == 'stat':
1906 change_entry = entry
1908 if not change_entry:
1909 die('Failed to decode output of p4 change -o')
1910 for key, value in change_entry.items():
1911 if key.startswith('File'):
1912 if 'depot-paths' in settings:
1913 if not [p for p in settings['depot-paths']
1914 if p4PathStartsWith(value, p)]:
1917 if not p4PathStartsWith(value, self.depotPath):
1919 files_list.append(value)
1921 # Output in the order expected by prepareLogMessage
1922 for key in ['Change', 'Client', 'User', 'Status', 'Description', 'Jobs']:
1923 if key not in change_entry:
1926 template += key + ':'
1927 if key == 'Description':
1929 for field_line in decode_text_stream(change_entry[key]).splitlines():
1930 template += '\t'+field_line+'\n'
1931 if len(files_list) > 0:
1933 template += 'Files:\n'
1934 for path in files_list:
1935 template += '\t'+path+'\n'
1938 def edit_template(self, template_file):
1939 """Invoke the editor to let the user change the submission
1940 message. Return true if okay to continue with the submit."""
1942 # if configured to skip the editing part, just submit
1943 if gitConfigBool("git-p4.skipSubmitEdit"):
1946 # look at the modification time, to check later if the user saved
1948 mtime = os.stat(template_file).st_mtime
1951 if "P4EDITOR" in os.environ and (os.environ.get("P4EDITOR") != ""):
1952 editor = os.environ.get("P4EDITOR")
1954 editor = read_pipe("git var GIT_EDITOR").strip()
1955 system(["sh", "-c", ('%s "$@"' % editor), editor, template_file])
1957 # If the file was not saved, prompt to see if this patch should
1958 # be skipped. But skip this verification step if configured so.
1959 if gitConfigBool("git-p4.skipSubmitEditCheck"):
1962 # modification time updated means user saved the file
1963 if os.stat(template_file).st_mtime > mtime:
1966 response = prompt("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
1972 def get_diff_description(self, editedFiles, filesToAdd, symlinks):
1974 if "P4DIFF" in os.environ:
1975 del(os.environ["P4DIFF"])
1977 for editedFile in editedFiles:
1978 diff += p4_read_pipe(['diff', '-du',
1979 wildcard_encode(editedFile)])
1983 for newFile in filesToAdd:
1984 newdiff += "==== new file ====\n"
1985 newdiff += "--- /dev/null\n"
1986 newdiff += "+++ %s\n" % newFile
1988 is_link = os.path.islink(newFile)
1989 expect_link = newFile in symlinks
1991 if is_link and expect_link:
1992 newdiff += "+%s\n" % os.readlink(newFile)
1994 f = open(newFile, "r")
1995 for line in f.readlines():
1996 newdiff += "+" + line
1999 return (diff + newdiff).replace('\r\n', '\n')
2001 def applyCommit(self, id):
2002 """Apply one commit, return True if it succeeded."""
2004 print("Applying", read_pipe(["git", "show", "-s",
2005 "--format=format:%h %s", id]))
2007 (p4User, gitEmail) = self.p4UserForCommit(id)
2009 diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
2011 filesToChangeType = set()
2012 filesToDelete = set()
2014 pureRenameCopy = set()
2016 filesToChangeExecBit = {}
2020 diff = parseDiffTreeEntry(line)
2021 modifier = diff['status']
2023 all_files.append(path)
2027 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
2028 filesToChangeExecBit[path] = diff['dst_mode']
2029 editedFiles.add(path)
2030 elif modifier == "A":
2031 filesToAdd.add(path)
2032 filesToChangeExecBit[path] = diff['dst_mode']
2033 if path in filesToDelete:
2034 filesToDelete.remove(path)
2036 dst_mode = int(diff['dst_mode'], 8)
2037 if dst_mode == 0o120000:
2040 elif modifier == "D":
2041 filesToDelete.add(path)
2042 if path in filesToAdd:
2043 filesToAdd.remove(path)
2044 elif modifier == "C":
2045 src, dest = diff['src'], diff['dst']
2046 all_files.append(dest)
2047 p4_integrate(src, dest)
2048 pureRenameCopy.add(dest)
2049 if diff['src_sha1'] != diff['dst_sha1']:
2051 pureRenameCopy.discard(dest)
2052 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
2054 pureRenameCopy.discard(dest)
2055 filesToChangeExecBit[dest] = diff['dst_mode']
2057 # turn off read-only attribute
2058 os.chmod(dest, stat.S_IWRITE)
2060 editedFiles.add(dest)
2061 elif modifier == "R":
2062 src, dest = diff['src'], diff['dst']
2063 all_files.append(dest)
2064 if self.p4HasMoveCommand:
2065 p4_edit(src) # src must be open before move
2066 p4_move(src, dest) # opens for (move/delete, move/add)
2068 p4_integrate(src, dest)
2069 if diff['src_sha1'] != diff['dst_sha1']:
2072 pureRenameCopy.add(dest)
2073 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
2074 if not self.p4HasMoveCommand:
2075 p4_edit(dest) # with move: already open, writable
2076 filesToChangeExecBit[dest] = diff['dst_mode']
2077 if not self.p4HasMoveCommand:
2079 os.chmod(dest, stat.S_IWRITE)
2081 filesToDelete.add(src)
2082 editedFiles.add(dest)
2083 elif modifier == "T":
2084 filesToChangeType.add(path)
2086 die("unknown modifier %s for %s" % (modifier, path))
2088 diffcmd = "git diff-tree --full-index -p \"%s\"" % (id)
2089 patchcmd = diffcmd + " | git apply "
2090 tryPatchCmd = patchcmd + "--check -"
2091 applyPatchCmd = patchcmd + "--check --apply -"
2092 patch_succeeded = True
2095 print("TryPatch: %s" % tryPatchCmd)
2097 if os.system(tryPatchCmd) != 0:
2098 fixed_rcs_keywords = False
2099 patch_succeeded = False
2100 print("Unfortunately applying the change failed!")
2102 # Patch failed, maybe it's just RCS keyword woes. Look through
2103 # the patch to see if that's possible.
2104 if gitConfigBool("git-p4.attemptRCSCleanup"):
2108 for file in editedFiles | filesToDelete:
2109 # did this file's delta contain RCS keywords?
2110 pattern = p4_keywords_regexp_for_file(file)
2113 # this file is a possibility...look for RCS keywords.
2114 regexp = re.compile(pattern, re.VERBOSE)
2115 for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
2116 if regexp.search(line):
2118 print("got keyword match on %s in %s in %s" % (pattern, line, file))
2119 kwfiles[file] = pattern
2122 for file in kwfiles:
2124 print("zapping %s with %s" % (line,pattern))
2125 # File is being deleted, so not open in p4. Must
2126 # disable the read-only bit on windows.
2127 if self.isWindows and file not in editedFiles:
2128 os.chmod(file, stat.S_IWRITE)
2129 self.patchRCSKeywords(file, kwfiles[file])
2130 fixed_rcs_keywords = True
2132 if fixed_rcs_keywords:
2133 print("Retrying the patch with RCS keywords cleaned up")
2134 if os.system(tryPatchCmd) == 0:
2135 patch_succeeded = True
2136 print("Patch succeesed this time with RCS keywords cleaned")
2138 if not patch_succeeded:
2139 for f in editedFiles:
2144 # Apply the patch for real, and do add/delete/+x handling.
2146 system(applyPatchCmd)
2148 for f in filesToChangeType:
2149 p4_edit(f, "-t", "auto")
2150 for f in filesToAdd:
2152 for f in filesToDelete:
2156 # Set/clear executable bits
2157 for f in filesToChangeExecBit.keys():
2158 mode = filesToChangeExecBit[f]
2159 setP4ExecBit(f, mode)
2162 if len(self.update_shelve) > 0:
2163 update_shelve = self.update_shelve.pop(0)
2164 p4_reopen_in_change(update_shelve, all_files)
2167 # Build p4 change description, starting with the contents
2168 # of the git commit message.
2170 logMessage = extractLogMessageFromGitCommit(id)
2171 logMessage = logMessage.strip()
2172 (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
2174 template = self.prepareSubmitTemplate(update_shelve)
2175 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
2177 if self.preserveUser:
2178 submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
2180 if self.checkAuthorship and not self.p4UserIsMe(p4User):
2181 submitTemplate += "######## git author %s does not match your p4 account.\n" % decode_text_stream(gitEmail)
2182 submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
2183 submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
2185 separatorLine = "######## everything below this line is just the diff #######\n"
2186 if not self.prepare_p4_only:
2187 submitTemplate += separatorLine
2188 submitTemplate += self.get_diff_description(editedFiles, filesToAdd, symlinks)
2190 (handle, fileName) = tempfile.mkstemp()
2191 tmpFile = os.fdopen(handle, "w+b")
2193 submitTemplate = submitTemplate.replace("\n", "\r\n")
2194 tmpFile.write(encode_text_stream(submitTemplate))
2200 # Allow the hook to edit the changelist text before presenting it
2202 if not run_git_hook("p4-prepare-changelist", [fileName]):
2205 if self.prepare_p4_only:
2207 # Leave the p4 tree prepared, and the submit template around
2208 # and let the user decide what to do next
2212 print("P4 workspace prepared for submission.")
2213 print("To submit or revert, go to client workspace")
2214 print(" " + self.clientPath)
2216 print("To submit, use \"p4 submit\" to write a new description,")
2217 print("or \"p4 submit -i <%s\" to use the one prepared by" \
2218 " \"git p4\"." % fileName)
2219 print("You can delete the file \"%s\" when finished." % fileName)
2221 if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
2222 print("To preserve change ownership by user %s, you must\n" \
2223 "do \"p4 change -f <change>\" after submitting and\n" \
2224 "edit the User field.")
2226 print("After submitting, renamed files must be re-synced.")
2227 print("Invoke \"p4 sync -f\" on each of these files:")
2228 for f in pureRenameCopy:
2232 print("To revert the changes, use \"p4 revert ...\", and delete")
2233 print("the submit template file \"%s\"" % fileName)
2235 print("Since the commit adds new files, they must be deleted:")
2236 for f in filesToAdd:
2242 if self.edit_template(fileName):
2243 if not self.no_verify:
2244 if not run_git_hook("p4-changelist", [fileName]):
2245 print("The p4-changelist hook failed.")
2249 # read the edited message and submit
2250 tmpFile = open(fileName, "rb")
2251 message = decode_text_stream(tmpFile.read())
2254 message = message.replace("\r\n", "\n")
2255 if message.find(separatorLine) != -1:
2256 submitTemplate = message[:message.index(separatorLine)]
2258 submitTemplate = message
2260 if len(submitTemplate.strip()) == 0:
2261 print("Changelist is empty, aborting this changelist.")
2266 p4_write_pipe(['shelve', '-r', '-i'], submitTemplate)
2268 p4_write_pipe(['shelve', '-i'], submitTemplate)
2270 p4_write_pipe(['submit', '-i'], submitTemplate)
2271 # The rename/copy happened by applying a patch that created a
2272 # new file. This leaves it writable, which confuses p4.
2273 for f in pureRenameCopy:
2276 if self.preserveUser:
2278 # Get last changelist number. Cannot easily get it from
2279 # the submit command output as the output is
2281 changelist = self.lastP4Changelist()
2282 self.modifyChangelistUser(changelist, p4User)
2286 run_git_hook("p4-post-changelist")
2288 # Revert changes if we skip this patch
2289 if not submitted or self.shelve:
2291 print ("Reverting shelved files.")
2293 print ("Submission cancelled, undoing p4 changes.")
2295 for f in editedFiles | filesToDelete:
2297 for f in filesToAdd:
2301 if not self.prepare_p4_only:
2305 # Export git tags as p4 labels. Create a p4 label and then tag
2307 def exportGitTags(self, gitTags):
2308 validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
2309 if len(validLabelRegexp) == 0:
2310 validLabelRegexp = defaultLabelRegexp
2311 m = re.compile(validLabelRegexp)
2313 for name in gitTags:
2315 if not m.match(name):
2317 print("tag %s does not match regexp %s" % (name, validLabelRegexp))
2320 # Get the p4 commit this corresponds to
2321 logMessage = extractLogMessageFromGitCommit(name)
2322 values = extractSettingsGitLog(logMessage)
2324 if 'change' not in values:
2325 # a tag pointing to something not sent to p4; ignore
2327 print("git tag %s does not give a p4 commit" % name)
2330 changelist = values['change']
2332 # Get the tag details.
2336 for l in read_pipe_lines(["git", "cat-file", "-p", name]):
2339 if re.match(r'tag\s+', l):
2341 elif re.match(r'\s*$', l):
2348 body = ["lightweight tag imported by git p4\n"]
2350 # Create the label - use the same view as the client spec we are using
2351 clientSpec = getClientSpec()
2353 labelTemplate = "Label: %s\n" % name
2354 labelTemplate += "Description:\n"
2356 labelTemplate += "\t" + b + "\n"
2357 labelTemplate += "View:\n"
2358 for depot_side in clientSpec.mappings:
2359 labelTemplate += "\t%s\n" % depot_side
2362 print("Would create p4 label %s for tag" % name)
2363 elif self.prepare_p4_only:
2364 print("Not creating p4 label %s for tag due to option" \
2365 " --prepare-p4-only" % name)
2367 p4_write_pipe(["label", "-i"], labelTemplate)
2370 p4_system(["tag", "-l", name] +
2371 ["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings])
2374 print("created p4 label for tag %s" % name)
2376 def run(self, args):
2378 self.master = currentGitBranch()
2379 elif len(args) == 1:
2380 self.master = args[0]
2381 if not branchExists(self.master):
2382 die("Branch %s does not exist" % self.master)
2386 for i in self.update_shelve:
2388 sys.exit("invalid changelist %d" % i)
2391 allowSubmit = gitConfig("git-p4.allowSubmit")
2392 if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
2393 die("%s is not in git-p4.allowSubmit" % self.master)
2395 [upstream, settings] = findUpstreamBranchPoint()
2396 self.depotPath = settings['depot-paths'][0]
2397 if len(self.origin) == 0:
2398 self.origin = upstream
2400 if len(self.update_shelve) > 0:
2403 if self.preserveUser:
2404 if not self.canChangeChangelists():
2405 die("Cannot preserve user names without p4 super-user or admin permissions")
2407 # if not set from the command line, try the config file
2408 if self.conflict_behavior is None:
2409 val = gitConfig("git-p4.conflict")
2411 if val not in self.conflict_behavior_choices:
2412 die("Invalid value '%s' for config git-p4.conflict" % val)
2415 self.conflict_behavior = val
2418 print("Origin branch is " + self.origin)
2420 if len(self.depotPath) == 0:
2421 print("Internal error: cannot locate perforce depot path from existing branches")
2424 self.useClientSpec = False
2425 if gitConfigBool("git-p4.useclientspec"):
2426 self.useClientSpec = True
2427 if self.useClientSpec:
2428 self.clientSpecDirs = getClientSpec()
2430 # Check for the existence of P4 branches
2431 branchesDetected = (len(p4BranchesInGit().keys()) > 1)
2433 if self.useClientSpec and not branchesDetected:
2434 # all files are relative to the client spec
2435 self.clientPath = getClientRoot()
2437 self.clientPath = p4Where(self.depotPath)
2439 if self.clientPath == "":
2440 die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
2442 print("Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath))
2443 self.oldWorkingDirectory = os.getcwd()
2445 # ensure the clientPath exists
2446 new_client_dir = False
2447 if not os.path.exists(self.clientPath):
2448 new_client_dir = True
2449 os.makedirs(self.clientPath)
2451 chdir(self.clientPath, is_client_path=True)
2453 print("Would synchronize p4 checkout in %s" % self.clientPath)
2455 print("Synchronizing p4 checkout...")
2457 # old one was destroyed, and maybe nobody told p4
2458 p4_sync("...", "-f")
2465 committish = self.master
2469 if self.commit != "":
2470 if self.commit.find("..") != -1:
2471 limits_ish = self.commit.split("..")
2472 for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (limits_ish[0], limits_ish[1])]):
2473 commits.append(line.strip())
2476 commits.append(self.commit)
2478 for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, committish)]):
2479 commits.append(line.strip())
2482 if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"):
2483 self.checkAuthorship = False
2485 self.checkAuthorship = True
2487 if self.preserveUser:
2488 self.checkValidP4Users(commits)
2491 # Build up a set of options to be passed to diff when
2492 # submitting each commit to p4.
2494 if self.detectRenames:
2495 # command-line -M arg
2496 self.diffOpts = "-M"
2498 # If not explicitly set check the config variable
2499 detectRenames = gitConfig("git-p4.detectRenames")
2501 if detectRenames.lower() == "false" or detectRenames == "":
2503 elif detectRenames.lower() == "true":
2504 self.diffOpts = "-M"
2506 self.diffOpts = "-M%s" % detectRenames
2508 # no command-line arg for -C or --find-copies-harder, just
2510 detectCopies = gitConfig("git-p4.detectCopies")
2511 if detectCopies.lower() == "false" or detectCopies == "":
2513 elif detectCopies.lower() == "true":
2514 self.diffOpts += " -C"
2516 self.diffOpts += " -C%s" % detectCopies
2518 if gitConfigBool("git-p4.detectCopiesHarder"):
2519 self.diffOpts += " --find-copies-harder"
2521 num_shelves = len(self.update_shelve)
2522 if num_shelves > 0 and num_shelves != len(commits):
2523 sys.exit("number of commits (%d) must match number of shelved changelist (%d)" %
2524 (len(commits), num_shelves))
2526 if not self.no_verify:
2528 if not run_git_hook("p4-pre-submit"):
2529 print("\nThe p4-pre-submit hook failed, aborting the submit.\n\nYou can skip " \
2530 "this pre-submission check by adding\nthe command line option '--no-verify', " \
2531 "however,\nthis will also skip the p4-changelist hook as well.")
2533 except Exception as e:
2534 print("\nThe p4-pre-submit hook failed, aborting the submit.\n\nThe hook failed "\
2535 "with the error '{0}'".format(e.message) )
2539 # Apply the commits, one at a time. On failure, ask if should
2540 # continue to try the rest of the patches, or quit.
2543 print("Would apply")
2545 last = len(commits) - 1
2546 for i, commit in enumerate(commits):
2548 print(" ", read_pipe(["git", "show", "-s",
2549 "--format=format:%h %s", commit]))
2552 ok = self.applyCommit(commit)
2554 applied.append(commit)
2555 if self.prepare_p4_only:
2557 print("Processing only the first commit due to option" \
2558 " --prepare-p4-only")
2562 # prompt for what to do, or use the option/variable
2563 if self.conflict_behavior == "ask":
2564 print("What do you want to do?")
2565 response = prompt("[s]kip this commit but apply the rest, or [q]uit? ")
2566 elif self.conflict_behavior == "skip":
2568 elif self.conflict_behavior == "quit":
2571 die("Unknown conflict_behavior '%s'" %
2572 self.conflict_behavior)
2575 print("Skipping this commit, but applying the rest")
2580 chdir(self.oldWorkingDirectory)
2581 shelved_applied = "shelved" if self.shelve else "applied"
2584 elif self.prepare_p4_only:
2586 elif len(commits) == len(applied):
2587 print("All commits {0}!".format(shelved_applied))
2591 sync.branch = self.branch
2592 if self.disable_p4sync:
2593 sync.sync_origin_only()
2597 if not self.disable_rebase:
2602 if len(applied) == 0:
2603 print("No commits {0}.".format(shelved_applied))
2605 print("{0} only the commits marked with '*':".format(shelved_applied.capitalize()))
2611 print(star, read_pipe(["git", "show", "-s",
2612 "--format=format:%h %s", c]))
2613 print("You will have to do 'git p4 sync' and rebase.")
2615 if gitConfigBool("git-p4.exportLabels"):
2616 self.exportLabels = True
2618 if self.exportLabels:
2619 p4Labels = getP4Labels(self.depotPath)
2620 gitTags = getGitTags()
2622 missingGitTags = gitTags - p4Labels
2623 self.exportGitTags(missingGitTags)
2625 # exit with error unless everything applied perfectly
2626 if len(commits) != len(applied):
2632 """Represent a p4 view ("p4 help views"), and map files in a
2633 repo according to the view."""
2635 def __init__(self, client_name):
2637 self.client_prefix = "//%s/" % client_name
2638 # cache results of "p4 where" to lookup client file locations
2639 self.client_spec_path_cache = {}
2641 def append(self, view_line):
2642 """Parse a view line, splitting it into depot and client
2643 sides. Append to self.mappings, preserving order. This
2644 is only needed for tag creation."""
2646 # Split the view line into exactly two words. P4 enforces
2647 # structure on these lines that simplifies this quite a bit.
2649 # Either or both words may be double-quoted.
2650 # Single quotes do not matter.
2651 # Double-quote marks cannot occur inside the words.
2652 # A + or - prefix is also inside the quotes.
2653 # There are no quotes unless they contain a space.
2654 # The line is already white-space stripped.
2655 # The two words are separated by a single space.
2657 if view_line[0] == '"':
2658 # First word is double quoted. Find its end.
2659 close_quote_index = view_line.find('"', 1)
2660 if close_quote_index <= 0:
2661 die("No first-word closing quote found: %s" % view_line)
2662 depot_side = view_line[1:close_quote_index]
2663 # skip closing quote and space
2664 rhs_index = close_quote_index + 1 + 1
2666 space_index = view_line.find(" ")
2667 if space_index <= 0:
2668 die("No word-splitting space found: %s" % view_line)
2669 depot_side = view_line[0:space_index]
2670 rhs_index = space_index + 1
2672 # prefix + means overlay on previous mapping
2673 if depot_side.startswith("+"):
2674 depot_side = depot_side[1:]
2676 # prefix - means exclude this path, leave out of mappings
2678 if depot_side.startswith("-"):
2680 depot_side = depot_side[1:]
2683 self.mappings.append(depot_side)
2685 def convert_client_path(self, clientFile):
2686 # chop off //client/ part to make it relative
2687 if not decode_path(clientFile).startswith(self.client_prefix):
2688 die("No prefix '%s' on clientFile '%s'" %
2689 (self.client_prefix, clientFile))
2690 return clientFile[len(self.client_prefix):]
2692 def update_client_spec_path_cache(self, files):
2693 """ Caching file paths by "p4 where" batch query """
2695 # List depot file paths exclude that already cached
2696 fileArgs = [f['path'] for f in files if decode_path(f['path']) not in self.client_spec_path_cache]
2698 if len(fileArgs) == 0:
2699 return # All files in cache
2701 where_result = p4CmdList(["-x", "-", "where"], stdin=fileArgs)
2702 for res in where_result:
2703 if "code" in res and res["code"] == "error":
2704 # assume error is "... file(s) not in client view"
2706 if "clientFile" not in res:
2707 die("No clientFile in 'p4 where' output")
2709 # it will list all of them, but only one not unmap-ped
2711 depot_path = decode_path(res['depotFile'])
2712 if gitConfigBool("core.ignorecase"):
2713 depot_path = depot_path.lower()
2714 self.client_spec_path_cache[depot_path] = self.convert_client_path(res["clientFile"])
2716 # not found files or unmap files set to ""
2717 for depotFile in fileArgs:
2718 depotFile = decode_path(depotFile)
2719 if gitConfigBool("core.ignorecase"):
2720 depotFile = depotFile.lower()
2721 if depotFile not in self.client_spec_path_cache:
2722 self.client_spec_path_cache[depotFile] = b''
2724 def map_in_client(self, depot_path):
2725 """Return the relative location in the client where this
2726 depot file should live. Returns "" if the file should
2727 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 )
2738 def cloneExcludeCallback(option, opt_str, value, parser):
2739 # prepend "/" because the first "/" was consumed as part of the option itself.
2740 # ("-//depot/A/..." becomes "/depot/A/..." after option parsing)
2741 parser.values.cloneExclude += ["/" + re.sub(r"\.\.\.$", "", value)]
2743 class P4Sync(Command, P4UserMap):
2746 Command.__init__(self)
2747 P4UserMap.__init__(self)
2749 optparse.make_option("--branch", dest="branch"),
2750 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
2751 optparse.make_option("--changesfile", dest="changesFile"),
2752 optparse.make_option("--silent", dest="silent", action="store_true"),
2753 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
2754 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
2755 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
2756 help="Import into refs/heads/ , not refs/remotes"),
2757 optparse.make_option("--max-changes", dest="maxChanges",
2758 help="Maximum number of changes to import"),
2759 optparse.make_option("--changes-block-size", dest="changes_block_size", type="int",
2760 help="Internal block size to use when iteratively calling p4 changes"),
2761 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
2762 help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
2763 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
2764 help="Only sync files that are included in the Perforce Client Spec"),
2765 optparse.make_option("-/", dest="cloneExclude",
2766 action="callback", callback=cloneExcludeCallback, type="string",
2767 help="exclude depot path"),
2769 self.description = """Imports from Perforce into a git repository.\n
2771 //depot/my/project/ -- to import the current head
2772 //depot/my/project/@all -- to import everything
2773 //depot/my/project/@1,6 -- to import only from revision 1 to 6
2775 (a ... is not needed in the path p4 specification, it's added implicitly)"""
2777 self.usage += " //depot/path[@revRange]"
2779 self.createdBranches = set()
2780 self.committedChanges = set()
2782 self.detectBranches = False
2783 self.detectLabels = False
2784 self.importLabels = False
2785 self.changesFile = ""
2786 self.syncWithOrigin = True
2787 self.importIntoRemotes = True
2788 self.maxChanges = ""
2789 self.changes_block_size = None
2790 self.keepRepoPath = False
2791 self.depotPaths = None
2792 self.p4BranchesInGit = []
2793 self.cloneExclude = []
2794 self.useClientSpec = False
2795 self.useClientSpec_from_options = False
2796 self.clientSpecDirs = None
2797 self.tempBranches = []
2798 self.tempBranchLocation = "refs/git-p4-tmp"
2799 self.largeFileSystem = None
2800 self.suppress_meta_comment = False
2802 if gitConfig('git-p4.largeFileSystem'):
2803 largeFileSystemConstructor = globals()[gitConfig('git-p4.largeFileSystem')]
2804 self.largeFileSystem = largeFileSystemConstructor(
2805 lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)
2808 if gitConfig("git-p4.syncFromOrigin") == "false":
2809 self.syncWithOrigin = False
2811 self.depotPaths = []
2812 self.changeRange = ""
2813 self.previousDepotPaths = []
2814 self.hasOrigin = False
2816 # map from branch depot path to parent branch
2817 self.knownBranches = {}
2818 self.initialParents = {}
2820 self.tz = b"%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
2823 # Force a checkpoint in fast-import and wait for it to finish
2824 def checkpoint(self):
2825 self.gitStream.write("checkpoint\n\n")
2826 self.gitStream.write("progress checkpoint\n\n")
2827 self.gitStream.flush()
2828 out = self.gitOutput.readline()
2830 print("checkpoint finished: " + out)
2832 def isPathWanted(self, path):
2833 for p in self.cloneExclude:
2835 if p4PathStartsWith(path, p):
2837 # "-//depot/file1" without a trailing "/" should only exclude "file1", but not "file111" or "file1_dir/file2"
2838 elif path.lower() == p.lower():
2840 for p in self.depotPaths:
2841 if p4PathStartsWith(path, decode_path(p)):
2845 def extractFilesFromCommit(self, commit, shelved=False, shelved_cl = 0):
2848 while "depotFile%s" % fnum in commit:
2849 path = commit["depotFile%s" % fnum]
2850 found = self.isPathWanted(decode_path(path))
2857 file["rev"] = commit["rev%s" % fnum]
2858 file["action"] = commit["action%s" % fnum]
2859 file["type"] = commit["type%s" % fnum]
2861 file["shelved_cl"] = int(shelved_cl)
2866 def extractJobsFromCommit(self, commit):
2869 while "job%s" % jnum in commit:
2870 job = commit["job%s" % jnum]
2875 def stripRepoPath(self, path, prefixes):
2876 """When streaming files, this is called to map a p4 depot path
2877 to where it should go in git. The prefixes are either
2878 self.depotPaths, or self.branchPrefixes in the case of
2879 branch detection."""
2881 if self.useClientSpec:
2882 # branch detection moves files up a level (the branch name)
2883 # from what client spec interpretation gives
2884 path = decode_path(self.clientSpecDirs.map_in_client(path))
2885 if self.detectBranches:
2886 for b in self.knownBranches:
2887 if p4PathStartsWith(path, b + "/"):
2888 path = path[len(b)+1:]
2890 elif self.keepRepoPath:
2891 # Preserve everything in relative path name except leading
2892 # //depot/; just look at first prefix as they all should
2893 # be in the same depot.
2894 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])
2895 if p4PathStartsWith(path, depot):
2896 path = path[len(depot):]
2900 if p4PathStartsWith(path, p):
2901 path = path[len(p):]
2904 path = wildcard_decode(path)
2907 def splitFilesIntoBranches(self, commit):
2908 """Look at each depotFile in the commit to figure out to what
2909 branch it belongs."""
2911 if self.clientSpecDirs:
2912 files = self.extractFilesFromCommit(commit)
2913 self.clientSpecDirs.update_client_spec_path_cache(files)
2917 while "depotFile%s" % fnum in commit:
2918 raw_path = commit["depotFile%s" % fnum]
2919 path = decode_path(raw_path)
2920 found = self.isPathWanted(path)
2926 file["path"] = raw_path
2927 file["rev"] = commit["rev%s" % fnum]
2928 file["action"] = commit["action%s" % fnum]
2929 file["type"] = commit["type%s" % fnum]
2932 # start with the full relative path where this file would
2934 if self.useClientSpec:
2935 relPath = decode_path(self.clientSpecDirs.map_in_client(path))
2937 relPath = self.stripRepoPath(path, self.depotPaths)
2939 for branch in self.knownBranches.keys():
2940 # add a trailing slash so that a commit into qt/4.2foo
2941 # doesn't end up in qt/4.2, e.g.
2942 if p4PathStartsWith(relPath, branch + "/"):
2943 if branch not in branches:
2944 branches[branch] = []
2945 branches[branch].append(file)
2950 def writeToGitStream(self, gitMode, relPath, contents):
2951 self.gitStream.write(encode_text_stream(u'M {} inline {}\n'.format(gitMode, relPath)))
2952 self.gitStream.write('data %d\n' % sum(len(d) for d in contents))
2954 self.gitStream.write(d)
2955 self.gitStream.write('\n')
2957 def encodeWithUTF8(self, path):
2959 path.decode('ascii')
2962 if gitConfig('git-p4.pathEncoding'):
2963 encoding = gitConfig('git-p4.pathEncoding')
2964 path = path.decode(encoding, 'replace').encode('utf8', 'replace')
2966 print('Path with non-ASCII characters detected. Used %s to encode: %s ' % (encoding, path))
2969 # output one file from the P4 stream
2970 # - helper for streamP4Files
2972 def streamOneP4File(self, file, contents):
2973 file_path = file['depotFile']
2974 relPath = self.stripRepoPath(decode_path(file_path), self.branchPrefixes)
2977 if 'fileSize' in self.stream_file:
2978 size = int(self.stream_file['fileSize'])
2980 size = 0 # deleted files don't get a fileSize apparently
2981 sys.stdout.write('\r%s --> %s (%i MB)\n' % (file_path, relPath, size/1024/1024))
2984 (type_base, type_mods) = split_p4_type(file["type"])
2987 if "x" in type_mods:
2989 if type_base == "symlink":
2991 # p4 print on a symlink sometimes contains "target\n";
2992 # if it does, remove the newline
2993 data = ''.join(decode_text_stream(c) for c in contents)
2995 # Some version of p4 allowed creating a symlink that pointed
2996 # to nothing. This causes p4 errors when checking out such
2997 # a change, and errors here too. Work around it by ignoring
2998 # the bad symlink; hopefully a future change fixes it.
2999 print("\nIgnoring empty symlink in %s" % file_path)
3001 elif data[-1] == '\n':
3002 contents = [data[:-1]]
3006 if type_base == "utf16":
3007 # p4 delivers different text in the python output to -G
3008 # than it does when using "print -o", or normal p4 client
3009 # operations. utf16 is converted to ascii or utf8, perhaps.
3010 # But ascii text saved as -t utf16 is completely mangled.
3011 # Invoke print -o to get the real contents.
3013 # On windows, the newlines will always be mangled by print, so put
3014 # them back too. This is not needed to the cygwin windows version,
3015 # just the native "NT" type.
3018 text = p4_read_pipe(['print', '-q', '-o', '-', '%s@%s' % (decode_path(file['depotFile']), file['change'])], raw=True)
3019 except Exception as e:
3020 if 'Translation of file content failed' in str(e):
3021 type_base = 'binary'
3025 if p4_version_string().find('/NT') >= 0:
3026 text = text.replace(b'\r\n', b'\n')
3029 if type_base == "apple":
3030 # Apple filetype files will be streamed as a concatenation of
3031 # its appledouble header and the contents. This is useless
3032 # on both macs and non-macs. If using "print -q -o xx", it
3033 # will create "xx" with the data, and "%xx" with the header.
3034 # This is also not very useful.
3036 # Ideally, someday, this script can learn how to generate
3037 # appledouble files directly and import those to git, but
3038 # non-mac machines can never find a use for apple filetype.
3039 print("\nIgnoring apple filetype file %s" % file['depotFile'])
3042 # Note that we do not try to de-mangle keywords on utf16 files,
3043 # even though in theory somebody may want that.
3044 pattern = p4_keywords_regexp_for_type(type_base, type_mods)
3046 regexp = re.compile(pattern, re.VERBOSE)
3047 text = ''.join(decode_text_stream(c) for c in contents)
3048 text = regexp.sub(r'$\1$', text)
3049 contents = [ encode_text_stream(text) ]
3051 if self.largeFileSystem:
3052 (git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)
3054 self.writeToGitStream(git_mode, relPath, contents)
3056 def streamOneP4Deletion(self, file):
3057 relPath = self.stripRepoPath(decode_path(file['path']), self.branchPrefixes)
3059 sys.stdout.write("delete %s\n" % relPath)
3061 self.gitStream.write(encode_text_stream(u'D {}\n'.format(relPath)))
3063 if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):
3064 self.largeFileSystem.removeLargeFile(relPath)
3066 # handle another chunk of streaming data
3067 def streamP4FilesCb(self, marshalled):
3069 # catch p4 errors and complain
3071 if "code" in marshalled:
3072 if marshalled["code"] == "error":
3073 if "data" in marshalled:
3074 err = marshalled["data"].rstrip()
3076 if not err and 'fileSize' in self.stream_file:
3077 required_bytes = int((4 * int(self.stream_file["fileSize"])) - calcDiskFree())
3078 if required_bytes > 0:
3079 err = 'Not enough space left on %s! Free at least %i MB.' % (
3080 os.getcwd(), required_bytes/1024/1024
3085 if self.stream_have_file_info:
3086 if "depotFile" in self.stream_file:
3087 f = self.stream_file["depotFile"]
3088 # force a failure in fast-import, else an empty
3089 # commit will be made
3090 self.gitStream.write("\n")
3091 self.gitStream.write("die-now\n")
3092 self.gitStream.close()
3093 # ignore errors, but make sure it exits first
3094 self.importProcess.wait()
3096 die("Error from p4 print for %s: %s" % (f, err))
3098 die("Error from p4 print: %s" % err)
3100 if 'depotFile' in marshalled and self.stream_have_file_info:
3101 # start of a new file - output the old one first
3102 self.streamOneP4File(self.stream_file, self.stream_contents)
3103 self.stream_file = {}
3104 self.stream_contents = []
3105 self.stream_have_file_info = False
3107 # pick up the new file information... for the
3108 # 'data' field we need to append to our array
3109 for k in marshalled.keys():
3111 if 'streamContentSize' not in self.stream_file:
3112 self.stream_file['streamContentSize'] = 0
3113 self.stream_file['streamContentSize'] += len(marshalled['data'])
3114 self.stream_contents.append(marshalled['data'])
3116 self.stream_file[k] = marshalled[k]
3119 'streamContentSize' in self.stream_file and
3120 'fileSize' in self.stream_file and
3121 'depotFile' in self.stream_file):
3122 size = int(self.stream_file["fileSize"])
3124 progress = 100*self.stream_file['streamContentSize']/size
3125 sys.stdout.write('\r%s %d%% (%i MB)' % (self.stream_file['depotFile'], progress, int(size/1024/1024)))
3128 self.stream_have_file_info = True
3130 # Stream directly from "p4 files" into "git fast-import"
3131 def streamP4Files(self, files):
3137 filesForCommit.append(f)
3138 if f['action'] in self.delete_actions:
3139 filesToDelete.append(f)
3141 filesToRead.append(f)
3144 for f in filesToDelete:
3145 self.streamOneP4Deletion(f)
3147 if len(filesToRead) > 0:
3148 self.stream_file = {}
3149 self.stream_contents = []
3150 self.stream_have_file_info = False
3152 # curry self argument
3153 def streamP4FilesCbSelf(entry):
3154 self.streamP4FilesCb(entry)
3157 for f in filesToRead:
3158 if 'shelved_cl' in f:
3159 # Handle shelved CLs using the "p4 print file@=N" syntax to print
3161 fileArg = f['path'] + encode_text_stream('@={}'.format(f['shelved_cl']))
3163 fileArg = f['path'] + encode_text_stream('#{}'.format(f['rev']))
3165 fileArgs.append(fileArg)
3167 p4CmdList(["-x", "-", "print"],
3169 cb=streamP4FilesCbSelf)
3172 if 'depotFile' in self.stream_file:
3173 self.streamOneP4File(self.stream_file, self.stream_contents)
3175 def make_email(self, userid):
3176 if userid in self.users:
3177 return self.users[userid]
3179 return b"%s <a@b>" % userid
3181 def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
3182 """ Stream a p4 tag.
3183 commit is either a git commit, or a fast-import mark, ":<p4commit>"
3187 print("writing tag %s for commit %s" % (labelName, commit))
3188 gitStream.write("tag %s\n" % labelName)
3189 gitStream.write("from %s\n" % commit)
3191 if 'Owner' in labelDetails:
3192 owner = labelDetails["Owner"]
3196 # Try to use the owner of the p4 label, or failing that,
3197 # the current p4 user id.
3199 email = self.make_email(owner)
3201 email = self.make_email(self.p4UserId())
3202 tagger = b"%s %s %s" % (email, epoch, self.tz)
3204 gitStream.write(b"tagger %s\n" % tagger)
3206 print("labelDetails=",labelDetails)
3207 if 'Description' in labelDetails:
3208 description = labelDetails['Description']
3210 description = 'Label from git p4'
3212 gitStream.write("data %d\n" % len(description))
3213 gitStream.write(description)
3214 gitStream.write("\n")
3216 def inClientSpec(self, path):
3217 if not self.clientSpecDirs:
3219 inClientSpec = self.clientSpecDirs.map_in_client(path)
3220 if not inClientSpec and self.verbose:
3221 print('Ignoring file outside of client spec: {0}'.format(path))
3224 def hasBranchPrefix(self, path):
3225 if not self.branchPrefixes:
3227 hasPrefix = [p for p in self.branchPrefixes
3228 if p4PathStartsWith(path, p)]
3229 if not hasPrefix and self.verbose:
3230 print('Ignoring file outside of prefix: {0}'.format(path))
3233 def findShadowedFiles(self, files, change):
3234 # Perforce allows you commit files and directories with the same name,
3235 # so you could have files //depot/foo and //depot/foo/bar both checked
3236 # in. A p4 sync of a repository in this state fails. Deleting one of
3237 # the files recovers the repository.
3239 # Git will not allow the broken state to exist and only the most recent
3240 # of the conflicting names is left in the repository. When one of the
3241 # conflicting files is deleted we need to re-add the other one to make
3242 # sure the git repository recovers in the same way as perforce.
3243 deleted = [f for f in files if f['action'] in self.delete_actions]
3246 path = decode_path(f['path'])
3247 to_check.add(path + '/...')
3249 path = path.rsplit("/", 1)[0]
3250 if path == "/" or path in to_check:
3253 to_check = ['%s@%s' % (wildcard_encode(p), change) for p in to_check
3254 if self.hasBranchPrefix(p)]
3256 stat_result = p4CmdList(["-x", "-", "fstat", "-T",
3257 "depotFile,headAction,headRev,headType"], stdin=to_check)
3258 for record in stat_result:
3259 if record['code'] != 'stat':
3261 if record['headAction'] in self.delete_actions:
3265 'path': record['depotFile'],
3266 'rev': record['headRev'],
3267 'type': record['headType']})
3269 def commit(self, details, files, branch, parent = "", allow_empty=False):
3270 epoch = details["time"]
3271 author = details["user"]
3272 jobs = self.extractJobsFromCommit(details)
3275 print('commit into {0}'.format(branch))
3277 files = [f for f in files
3278 if self.hasBranchPrefix(decode_path(f['path']))]
3279 self.findShadowedFiles(files, details['change'])
3281 if self.clientSpecDirs:
3282 self.clientSpecDirs.update_client_spec_path_cache(files)
3284 files = [f for f in files if self.inClientSpec(decode_path(f['path']))]
3286 if gitConfigBool('git-p4.keepEmptyCommits'):
3289 if not files and not allow_empty:
3290 print('Ignoring revision {0} as it would produce an empty commit.'
3291 .format(details['change']))
3294 self.gitStream.write("commit %s\n" % branch)
3295 self.gitStream.write("mark :%s\n" % details["change"])
3296 self.committedChanges.add(int(details["change"]))
3297 if author not in self.users:
3298 self.getUserMapFromPerforceServer()
3299 committer = b"%s %s %s" % (self.make_email(author), epoch, self.tz)
3301 self.gitStream.write(b"committer %s\n" % committer)
3303 self.gitStream.write("data <<EOT\n")
3304 self.gitStream.write(details["desc"])
3306 self.gitStream.write("\nJobs: %s" % (' '.join(jobs)))
3308 if not self.suppress_meta_comment:
3309 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" %
3310 (','.join(self.branchPrefixes), details["change"]))
3311 if len(details['options']) > 0:
3312 self.gitStream.write(": options = %s" % details['options'])
3313 self.gitStream.write("]\n")
3315 self.gitStream.write("EOT\n\n")
3319 print("parent %s" % parent)
3320 self.gitStream.write("from %s\n" % parent)
3322 self.streamP4Files(files)
3323 self.gitStream.write("\n")
3325 change = int(details["change"])
3327 if change in self.labels:
3328 label = self.labels[change]
3329 labelDetails = label[0]
3330 labelRevisions = label[1]
3332 print("Change %s is labelled %s" % (change, labelDetails))
3334 files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
3335 for p in self.branchPrefixes])
3337 if len(files) == len(labelRevisions):
3341 if info["action"] in self.delete_actions:
3343 cleanedFiles[info["depotFile"]] = info["rev"]
3345 if cleanedFiles == labelRevisions:
3346 self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
3350 print("Tag %s does not match with change %s: files do not match."
3351 % (labelDetails["label"], change))
3355 print("Tag %s does not match with change %s: file count is different."
3356 % (labelDetails["label"], change))
3358 # Build a dictionary of changelists and labels, for "detect-labels" option.
3359 def getLabels(self):
3362 l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
3363 if len(l) > 0 and not self.silent:
3364 print("Finding files belonging to labels in %s" % self.depotPaths)
3367 label = output["label"]
3371 print("Querying files for label %s" % label)
3372 for file in p4CmdList(["files"] +
3373 ["%s...@%s" % (p, label)
3374 for p in self.depotPaths]):
3375 revisions[file["depotFile"]] = file["rev"]
3376 change = int(file["change"])
3377 if change > newestChange:
3378 newestChange = change
3380 self.labels[newestChange] = [output, revisions]
3383 print("Label changes: %s" % self.labels.keys())
3385 # Import p4 labels as git tags. A direct mapping does not
3386 # exist, so assume that if all the files are at the same revision
3387 # then we can use that, or it's something more complicated we should
3389 def importP4Labels(self, stream, p4Labels):
3391 print("import p4 labels: " + ' '.join(p4Labels))
3393 ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
3394 validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
3395 if len(validLabelRegexp) == 0:
3396 validLabelRegexp = defaultLabelRegexp
3397 m = re.compile(validLabelRegexp)
3399 for name in p4Labels:
3402 if not m.match(name):
3404 print("label %s does not match regexp %s" % (name,validLabelRegexp))
3407 if name in ignoredP4Labels:
3410 labelDetails = p4CmdList(['label', "-o", name])[0]
3412 # get the most recent changelist for each file in this label
3413 change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name)
3414 for p in self.depotPaths])
3416 if 'change' in change:
3417 # find the corresponding git commit; take the oldest commit
3418 changelist = int(change['change'])
3419 if changelist in self.committedChanges:
3420 gitCommit = ":%d" % changelist # use a fast-import mark
3423 gitCommit = read_pipe(["git", "rev-list", "--max-count=1",
3424 "--reverse", ":/\[git-p4:.*change = %d\]" % changelist], ignore_error=True)
3425 if len(gitCommit) == 0:
3426 print("importing label %s: could not find git commit for changelist %d" % (name, changelist))
3429 gitCommit = gitCommit.strip()
3432 # Convert from p4 time format
3434 tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
3436 print("Could not convert label time %s" % labelDetails['Update'])
3439 when = b"%i" % int(time.mktime(tmwhen))
3440 self.streamTag(stream, name, labelDetails, gitCommit, when)
3442 print("p4 label %s mapped to git commit %s" % (name, gitCommit))
3445 print("Label %s has no changelists - possibly deleted?" % name)
3448 # We can't import this label; don't try again as it will get very
3449 # expensive repeatedly fetching all the files for labels that will
3450 # never be imported. If the label is moved in the future, the
3451 # ignore will need to be removed manually.
3452 system(["git", "config", "--add", "git-p4.ignoredP4Labels", name])
3454 def guessProjectName(self):
3455 for p in self.depotPaths:
3458 p = p[p.strip().rfind("/") + 1:]
3459 if not p.endswith("/"):
3463 def getBranchMapping(self):
3464 lostAndFoundBranches = set()
3466 user = gitConfig("git-p4.branchUser")
3468 command = "branches -u %s" % user
3470 command = "branches"
3472 for info in p4CmdList(command):
3473 details = p4Cmd(["branch", "-o", info["branch"]])
3475 while "View%s" % viewIdx in details:
3476 paths = details["View%s" % viewIdx].split(" ")
3477 viewIdx = viewIdx + 1
3478 # require standard //depot/foo/... //depot/bar/... mapping
3479 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
3482 destination = paths[1]
3484 if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
3485 source = source[len(self.depotPaths[0]):-4]
3486 destination = destination[len(self.depotPaths[0]):-4]
3488 if destination in self.knownBranches:
3490 print("p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination))
3491 print("but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination))
3494 self.knownBranches[destination] = source
3496 lostAndFoundBranches.discard(destination)
3498 if source not in self.knownBranches:
3499 lostAndFoundBranches.add(source)
3501 # Perforce does not strictly require branches to be defined, so we also
3502 # check git config for a branch list.
3504 # Example of branch definition in git config file:
3506 # branchList=main:branchA
3507 # branchList=main:branchB
3508 # branchList=branchA:branchC
3509 configBranches = gitConfigList("git-p4.branchList")
3510 for branch in configBranches:
3512 (source, destination) = branch.split(":")
3513 self.knownBranches[destination] = source
3515 lostAndFoundBranches.discard(destination)
3517 if source not in self.knownBranches:
3518 lostAndFoundBranches.add(source)
3521 for branch in lostAndFoundBranches:
3522 self.knownBranches[branch] = branch
3524 def getBranchMappingFromGitBranches(self):
3525 branches = p4BranchesInGit(self.importIntoRemotes)
3526 for branch in branches.keys():
3527 if branch == "master":
3530 branch = branch[len(self.projectName):]
3531 self.knownBranches[branch] = branch
3533 def updateOptionDict(self, d):
3535 if self.keepRepoPath:
3536 option_keys['keepRepoPath'] = 1
3538 d["options"] = ' '.join(sorted(option_keys.keys()))
3540 def readOptions(self, d):
3541 self.keepRepoPath = ('options' in d
3542 and ('keepRepoPath' in d['options']))
3544 def gitRefForBranch(self, branch):
3545 if branch == "main":
3546 return self.refPrefix + "master"
3548 if len(branch) <= 0:
3551 return self.refPrefix + self.projectName + branch
3553 def gitCommitByP4Change(self, ref, change):
3555 print("looking in ref " + ref + " for change %s using bisect..." % change)
3558 latestCommit = parseRevision(ref)
3562 print("trying: earliest %s latest %s" % (earliestCommit, latestCommit))
3563 next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
3568 log = extractLogMessageFromGitCommit(next)
3569 settings = extractSettingsGitLog(log)
3570 currentChange = int(settings['change'])
3572 print("current change %s" % currentChange)
3574 if currentChange == change:
3576 print("found %s" % next)
3579 if currentChange < change:
3580 earliestCommit = "^%s" % next
3582 if next == latestCommit:
3583 die("Infinite loop while looking in ref %s for change %s. Check your branch mappings" % (ref, change))
3584 latestCommit = "%s^@" % next
3588 def importNewBranch(self, branch, maxChange):
3589 # make fast-import flush all changes to disk and update the refs using the checkpoint
3590 # command so that we can try to find the branch parent in the git history
3591 self.gitStream.write("checkpoint\n\n");
3592 self.gitStream.flush();
3593 branchPrefix = self.depotPaths[0] + branch + "/"
3594 range = "@1,%s" % maxChange
3595 #print "prefix" + branchPrefix
3596 changes = p4ChangesForPaths([branchPrefix], range, self.changes_block_size)
3597 if len(changes) <= 0:
3599 firstChange = changes[0]
3600 #print "first change in branch: %s" % firstChange
3601 sourceBranch = self.knownBranches[branch]
3602 sourceDepotPath = self.depotPaths[0] + sourceBranch
3603 sourceRef = self.gitRefForBranch(sourceBranch)
3604 #print "source " + sourceBranch
3606 branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
3607 #print "branch parent: %s" % branchParentChange
3608 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
3609 if len(gitParent) > 0:
3610 self.initialParents[self.gitRefForBranch(branch)] = gitParent
3611 #print "parent git commit: %s" % gitParent
3613 self.importChanges(changes)
3616 def searchParent(self, parent, branch, target):
3617 targetTree = read_pipe(["git", "rev-parse",
3618 "{}^{{tree}}".format(target)]).strip()
3619 for line in read_pipe_lines(["git", "rev-list", "--format=%H %T",
3620 "--no-merges", parent]):
3621 if line.startswith("commit "):
3623 commit, tree = line.strip().split(" ")
3624 if tree == targetTree:
3626 print("Found parent of %s in commit %s" % (branch, commit))
3630 def importChanges(self, changes, origin_revision=0):
3632 for change in changes:
3633 description = p4_describe(change)
3634 self.updateOptionDict(description)
3637 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
3642 if self.detectBranches:
3643 branches = self.splitFilesIntoBranches(description)
3644 for branch in branches.keys():
3646 branchPrefix = self.depotPaths[0] + branch + "/"
3647 self.branchPrefixes = [ branchPrefix ]
3651 filesForCommit = branches[branch]
3654 print("branch is %s" % branch)
3656 self.updatedBranches.add(branch)
3658 if branch not in self.createdBranches:
3659 self.createdBranches.add(branch)
3660 parent = self.knownBranches[branch]
3661 if parent == branch:
3664 fullBranch = self.projectName + branch
3665 if fullBranch not in self.p4BranchesInGit:
3667 print("\n Importing new branch %s" % fullBranch);
3668 if self.importNewBranch(branch, change - 1):
3670 self.p4BranchesInGit.append(fullBranch)
3672 print("\n Resuming with change %s" % change);
3675 print("parent determined through known branches: %s" % parent)
3677 branch = self.gitRefForBranch(branch)
3678 parent = self.gitRefForBranch(parent)
3681 print("looking for initial parent for %s; current parent is %s" % (branch, parent))
3683 if len(parent) == 0 and branch in self.initialParents:
3684 parent = self.initialParents[branch]
3685 del self.initialParents[branch]
3689 tempBranch = "%s/%d" % (self.tempBranchLocation, change)
3691 print("Creating temporary branch: " + tempBranch)
3692 self.commit(description, filesForCommit, tempBranch)
3693 self.tempBranches.append(tempBranch)
3695 blob = self.searchParent(parent, branch, tempBranch)
3697 self.commit(description, filesForCommit, branch, blob)
3700 print("Parent of %s not found. Committing into head of %s" % (branch, parent))
3701 self.commit(description, filesForCommit, branch, parent)
3703 files = self.extractFilesFromCommit(description)
3704 self.commit(description, files, self.branch,
3706 # only needed once, to connect to the previous commit
3707 self.initialParent = ""
3709 print(self.gitError.read())
3712 def sync_origin_only(self):
3713 if self.syncWithOrigin:
3714 self.hasOrigin = originP4BranchesExist()
3717 print('Syncing with origin first, using "git fetch origin"')
3718 system("git fetch origin")
3720 def importHeadRevision(self, revision):
3721 print("Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch))
3724 details["user"] = b"git perforce import user"
3725 details["desc"] = ("Initial import of %s from the state at revision %s\n"
3726 % (' '.join(self.depotPaths), revision))
3727 details["change"] = revision
3731 fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
3733 for info in p4CmdList(["files"] + fileArgs):
3735 if 'code' in info and info['code'] == 'error':
3736 sys.stderr.write("p4 returned an error: %s\n"
3738 if info['data'].find("must refer to client") >= 0:
3739 sys.stderr.write("This particular p4 error is misleading.\n")
3740 sys.stderr.write("Perhaps the depot path was misspelled.\n");
3741 sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
3743 if 'p4ExitCode' in info:
3744 sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
3748 change = int(info["change"])
3749 if change > newestRevision:
3750 newestRevision = change
3752 if info["action"] in self.delete_actions:
3753 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
3754 #fileCnt = fileCnt + 1
3757 for prop in ["depotFile", "rev", "action", "type" ]:
3758 details["%s%s" % (prop, fileCnt)] = info[prop]
3760 fileCnt = fileCnt + 1
3762 details["change"] = newestRevision
3764 # Use time from top-most change so that all git p4 clones of
3765 # the same p4 repo have the same commit SHA1s.
3766 res = p4_describe(newestRevision)
3767 details["time"] = res["time"]
3769 self.updateOptionDict(details)
3771 self.commit(details, self.extractFilesFromCommit(details), self.branch)
3772 except IOError as err:
3773 print("IO error with git fast-import. Is your git version recent enough?")
3774 print("IO error details: {}".format(err))
3775 print(self.gitError.read())
3778 def importRevisions(self, args, branch_arg_given):
3781 if len(self.changesFile) > 0:
3782 with open(self.changesFile) as f:
3783 output = f.readlines()
3786 changeSet.add(int(line))
3788 for change in changeSet:
3789 changes.append(change)
3793 # catch "git p4 sync" with no new branches, in a repo that
3794 # does not have any existing p4 branches
3796 if not self.p4BranchesInGit:
3797 raise P4CommandException("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.")
3799 # The default branch is master, unless --branch is used to
3800 # specify something else. Make sure it exists, or complain
3801 # nicely about how to use --branch.
3802 if not self.detectBranches:
3803 if not branch_exists(self.branch):
3804 if branch_arg_given:
3805 raise P4CommandException("Error: branch %s does not exist." % self.branch)
3807 raise P4CommandException("Error: no branch %s; perhaps specify one with --branch." %
3811 print("Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
3813 changes = p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)
3815 if len(self.maxChanges) > 0:
3816 changes = changes[:min(int(self.maxChanges), len(changes))]
3818 if len(changes) == 0:
3820 print("No changes to import!")
3822 if not self.silent and not self.detectBranches:
3823 print("Import destination: %s" % self.branch)
3825 self.updatedBranches = set()
3827 if not self.detectBranches:
3829 # start a new branch
3830 self.initialParent = ""
3832 # build on a previous revision
3833 self.initialParent = parseRevision(self.branch)
3835 self.importChanges(changes)
3839 if len(self.updatedBranches) > 0:
3840 sys.stdout.write("Updated branches: ")
3841 for b in self.updatedBranches:
3842 sys.stdout.write("%s " % b)
3843 sys.stdout.write("\n")
3845 def openStreams(self):
3846 self.importProcess = subprocess.Popen(["git", "fast-import"],
3847 stdin=subprocess.PIPE,
3848 stdout=subprocess.PIPE,
3849 stderr=subprocess.PIPE);
3850 self.gitOutput = self.importProcess.stdout
3851 self.gitStream = self.importProcess.stdin
3852 self.gitError = self.importProcess.stderr
3854 if bytes is not str:
3855 # Wrap gitStream.write() so that it can be called using `str` arguments
3856 def make_encoded_write(write):
3857 def encoded_write(s):
3858 return write(s.encode() if isinstance(s, str) else s)
3859 return encoded_write
3861 self.gitStream.write = make_encoded_write(self.gitStream.write)
3863 def closeStreams(self):
3864 if self.gitStream is None:
3866 self.gitStream.close()
3867 if self.importProcess.wait() != 0:
3868 die("fast-import failed: %s" % self.gitError.read())
3869 self.gitOutput.close()
3870 self.gitError.close()
3871 self.gitStream = None
3873 def run(self, args):
3874 if self.importIntoRemotes:
3875 self.refPrefix = "refs/remotes/p4/"
3877 self.refPrefix = "refs/heads/p4/"
3879 self.sync_origin_only()
3881 branch_arg_given = bool(self.branch)
3882 if len(self.branch) == 0:
3883 self.branch = self.refPrefix + "master"
3884 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
3885 system("git update-ref %s refs/heads/p4" % self.branch)
3886 system("git branch -D p4")
3888 # accept either the command-line option, or the configuration variable
3889 if self.useClientSpec:
3890 # will use this after clone to set the variable
3891 self.useClientSpec_from_options = True
3893 if gitConfigBool("git-p4.useclientspec"):
3894 self.useClientSpec = True
3895 if self.useClientSpec:
3896 self.clientSpecDirs = getClientSpec()
3898 # TODO: should always look at previous commits,
3899 # merge with previous imports, if possible.
3902 createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
3904 # branches holds mapping from branch name to sha1
3905 branches = p4BranchesInGit(self.importIntoRemotes)
3907 # restrict to just this one, disabling detect-branches
3908 if branch_arg_given:
3909 short = self.branch.split("/")[-1]
3910 if short in branches:
3911 self.p4BranchesInGit = [ short ]
3913 self.p4BranchesInGit = branches.keys()
3915 if len(self.p4BranchesInGit) > 1:
3917 print("Importing from/into multiple branches")
3918 self.detectBranches = True
3919 for branch in branches.keys():
3920 self.initialParents[self.refPrefix + branch] = \
3924 print("branches: %s" % self.p4BranchesInGit)
3927 for branch in self.p4BranchesInGit:
3928 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
3930 settings = extractSettingsGitLog(logMsg)
3932 self.readOptions(settings)
3933 if ('depot-paths' in settings
3934 and 'change' in settings):
3935 change = int(settings['change']) + 1
3936 p4Change = max(p4Change, change)
3938 depotPaths = sorted(settings['depot-paths'])
3939 if self.previousDepotPaths == []:
3940 self.previousDepotPaths = depotPaths
3943 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
3944 prev_list = prev.split("/")
3945 cur_list = cur.split("/")
3946 for i in range(0, min(len(cur_list), len(prev_list))):
3947 if cur_list[i] != prev_list[i]:
3951 paths.append ("/".join(cur_list[:i + 1]))
3953 self.previousDepotPaths = paths
3956 self.depotPaths = sorted(self.previousDepotPaths)
3957 self.changeRange = "@%s,#head" % p4Change
3958 if not self.silent and not self.detectBranches:
3959 print("Performing incremental import into %s git branch" % self.branch)
3961 # accept multiple ref name abbreviations:
3962 # refs/foo/bar/branch -> use it exactly
3963 # p4/branch -> prepend refs/remotes/ or refs/heads/
3964 # branch -> prepend refs/remotes/p4/ or refs/heads/p4/
3965 if not self.branch.startswith("refs/"):
3966 if self.importIntoRemotes:
3967 prepend = "refs/remotes/"
3969 prepend = "refs/heads/"
3970 if not self.branch.startswith("p4/"):
3972 self.branch = prepend + self.branch
3974 if len(args) == 0 and self.depotPaths:
3976 print("Depot paths: %s" % ' '.join(self.depotPaths))
3978 if self.depotPaths and self.depotPaths != args:
3979 print("previous import used depot path %s and now %s was specified. "
3980 "This doesn't work!" % (' '.join (self.depotPaths),
3984 self.depotPaths = sorted(args)
3989 # Make sure no revision specifiers are used when --changesfile
3991 bad_changesfile = False
3992 if len(self.changesFile) > 0:
3993 for p in self.depotPaths:
3994 if p.find("@") >= 0 or p.find("#") >= 0:
3995 bad_changesfile = True
3998 die("Option --changesfile is incompatible with revision specifiers")
4001 for p in self.depotPaths:
4002 if p.find("@") != -1:
4003 atIdx = p.index("@")
4004 self.changeRange = p[atIdx:]
4005 if self.changeRange == "@all":
4006 self.changeRange = ""
4007 elif ',' not in self.changeRange:
4008 revision = self.changeRange
4009 self.changeRange = ""
4011 elif p.find("#") != -1:
4012 hashIdx = p.index("#")
4013 revision = p[hashIdx:]
4015 elif self.previousDepotPaths == []:
4016 # pay attention to changesfile, if given, else import
4017 # the entire p4 tree at the head revision
4018 if len(self.changesFile) == 0:
4021 p = re.sub ("\.\.\.$", "", p)
4022 if not p.endswith("/"):
4027 self.depotPaths = newPaths
4029 # --detect-branches may change this for each branch
4030 self.branchPrefixes = self.depotPaths
4032 self.loadUserMapFromCache()
4034 if self.detectLabels:
4037 if self.detectBranches:
4038 ## FIXME - what's a P4 projectName ?
4039 self.projectName = self.guessProjectName()
4042 self.getBranchMappingFromGitBranches()
4044 self.getBranchMapping()
4046 print("p4-git branches: %s" % self.p4BranchesInGit)
4047 print("initial parents: %s" % self.initialParents)
4048 for b in self.p4BranchesInGit:
4052 b = b[len(self.projectName):]
4053 self.createdBranches.add(b)
4063 self.importHeadRevision(revision)
4065 self.importRevisions(args, branch_arg_given)
4067 if gitConfigBool("git-p4.importLabels"):
4068 self.importLabels = True
4070 if self.importLabels:
4071 p4Labels = getP4Labels(self.depotPaths)
4072 gitTags = getGitTags()
4074 missingP4Labels = p4Labels - gitTags
4075 self.importP4Labels(self.gitStream, missingP4Labels)
4077 except P4CommandException as e:
4086 # Cleanup temporary branches created during import
4087 if self.tempBranches != []:
4088 for branch in self.tempBranches:
4089 read_pipe("git update-ref -d %s" % branch)
4090 os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
4092 # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow
4093 # a convenient shortcut refname "p4".
4094 if self.importIntoRemotes:
4095 head_ref = self.refPrefix + "HEAD"
4096 if not gitBranchExists(head_ref) and gitBranchExists(self.branch):
4097 system(["git", "symbolic-ref", head_ref, self.branch])
4101 class P4Rebase(Command):
4103 Command.__init__(self)
4105 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
4107 self.importLabels = False
4108 self.description = ("Fetches the latest revision from perforce and "
4109 + "rebases the current work (branch) against it")
4111 def run(self, args):
4113 sync.importLabels = self.importLabels
4116 return self.rebase()
4119 if os.system("git update-index --refresh") != 0:
4120 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.");
4121 if len(read_pipe("git diff-index HEAD --")) > 0:
4122 die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");
4124 [upstream, settings] = findUpstreamBranchPoint()
4125 if len(upstream) == 0:
4126 die("Cannot find upstream branchpoint for rebase")
4128 # the branchpoint may be p4/foo~3, so strip off the parent
4129 upstream = re.sub("~[0-9]+$", "", upstream)
4131 print("Rebasing the current branch onto %s" % upstream)
4132 oldHead = read_pipe("git rev-parse HEAD").strip()
4133 system("git rebase %s" % upstream)
4134 system("git diff-tree --stat --summary -M %s HEAD --" % oldHead)
4137 class P4Clone(P4Sync):
4139 P4Sync.__init__(self)
4140 self.description = "Creates a new git repository and imports from Perforce into it"
4141 self.usage = "usage: %prog [options] //depot/path[@revRange]"
4143 optparse.make_option("--destination", dest="cloneDestination",
4144 action='store', default=None,
4145 help="where to leave result of the clone"),
4146 optparse.make_option("--bare", dest="cloneBare",
4147 action="store_true", default=False),
4149 self.cloneDestination = None
4150 self.needsGit = False
4151 self.cloneBare = False
4153 def defaultDestination(self, args):
4154 ## TODO: use common prefix of args?
4156 depotDir = re.sub("(@[^@]*)$", "", depotPath)
4157 depotDir = re.sub("(#[^#]*)$", "", depotDir)
4158 depotDir = re.sub(r"\.\.\.$", "", depotDir)
4159 depotDir = re.sub(r"/$", "", depotDir)
4160 return os.path.split(depotDir)[1]
4162 def run(self, args):
4166 if self.keepRepoPath and not self.cloneDestination:
4167 sys.stderr.write("Must specify destination for --keep-path\n")
4172 if not self.cloneDestination and len(depotPaths) > 1:
4173 self.cloneDestination = depotPaths[-1]
4174 depotPaths = depotPaths[:-1]
4176 for p in depotPaths:
4177 if not p.startswith("//"):
4178 sys.stderr.write('Depot paths must start with "//": %s\n' % p)
4181 if not self.cloneDestination:
4182 self.cloneDestination = self.defaultDestination(args)
4184 print("Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination))
4186 if not os.path.exists(self.cloneDestination):
4187 os.makedirs(self.cloneDestination)
4188 chdir(self.cloneDestination)
4190 init_cmd = [ "git", "init" ]
4192 init_cmd.append("--bare")
4193 retcode = subprocess.call(init_cmd)
4195 raise CalledProcessError(retcode, init_cmd)
4197 if not P4Sync.run(self, depotPaths):
4200 # create a master branch and check out a work tree
4201 if gitBranchExists(self.branch):
4202 system([ "git", "branch", currentGitBranch(), self.branch ])
4203 if not self.cloneBare:
4204 system([ "git", "checkout", "-f" ])
4206 print('Not checking out any branch, use ' \
4207 '"git checkout -q -b master <branch>"')
4209 # auto-set this variable if invoked with --use-client-spec
4210 if self.useClientSpec_from_options:
4211 system("git config --bool git-p4.useclientspec true")
4215 class P4Unshelve(Command):
4217 Command.__init__(self)
4219 self.origin = "HEAD"
4220 self.description = "Unshelve a P4 changelist into a git commit"
4221 self.usage = "usage: %prog [options] changelist"
4223 optparse.make_option("--origin", dest="origin",
4224 help="Use this base revision instead of the default (%s)" % self.origin),
4226 self.verbose = False
4227 self.noCommit = False
4228 self.destbranch = "refs/remotes/p4-unshelved"
4230 def renameBranch(self, branch_name):
4231 """ Rename the existing branch to branch_name.N
4235 for i in range(0,1000):
4236 backup_branch_name = "{0}.{1}".format(branch_name, i)
4237 if not gitBranchExists(backup_branch_name):
4238 gitUpdateRef(backup_branch_name, branch_name) # copy ref to backup
4239 gitDeleteRef(branch_name)
4241 print("renamed old unshelve branch to {0}".format(backup_branch_name))
4245 sys.exit("gave up trying to rename existing branch {0}".format(sync.branch))
4247 def findLastP4Revision(self, starting_point):
4248 """ Look back from starting_point for the first commit created by git-p4
4249 to find the P4 commit we are based on, and the depot-paths.
4252 for parent in (range(65535)):
4253 log = extractLogMessageFromGitCommit("{0}~{1}".format(starting_point, parent))
4254 settings = extractSettingsGitLog(log)
4255 if 'change' in settings:
4258 sys.exit("could not find git-p4 commits in {0}".format(self.origin))
4260 def createShelveParent(self, change, branch_name, sync, origin):
4261 """ Create a commit matching the parent of the shelved changelist 'change'
4263 parent_description = p4_describe(change, shelved=True)
4264 parent_description['desc'] = 'parent for shelved changelist {}\n'.format(change)
4265 files = sync.extractFilesFromCommit(parent_description, shelved=False, shelved_cl=change)
4269 # if it was added in the shelved changelist, it won't exist in the parent
4270 if f['action'] in self.add_actions:
4273 # if it was deleted in the shelved changelist it must not be deleted
4274 # in the parent - we might even need to create it if the origin branch
4276 if f['action'] in self.delete_actions:
4279 parent_files.append(f)
4281 sync.commit(parent_description, parent_files, branch_name,
4282 parent=origin, allow_empty=True)
4283 print("created parent commit for {0} based on {1} in {2}".format(
4284 change, self.origin, branch_name))
4286 def run(self, args):
4290 if not gitBranchExists(self.origin):
4291 sys.exit("origin branch {0} does not exist".format(self.origin))
4296 # only one change at a time
4299 # if the target branch already exists, rename it
4300 branch_name = "{0}/{1}".format(self.destbranch, change)
4301 if gitBranchExists(branch_name):
4302 self.renameBranch(branch_name)
4303 sync.branch = branch_name
4305 sync.verbose = self.verbose
4306 sync.suppress_meta_comment = True
4308 settings = self.findLastP4Revision(self.origin)
4309 sync.depotPaths = settings['depot-paths']
4310 sync.branchPrefixes = sync.depotPaths
4313 sync.loadUserMapFromCache()
4316 # create a commit for the parent of the shelved changelist
4317 self.createShelveParent(change, branch_name, sync, self.origin)
4319 # create the commit for the shelved changelist itself
4320 description = p4_describe(change, True)
4321 files = sync.extractFilesFromCommit(description, True, change)
4323 sync.commit(description, files, branch_name, "")
4326 print("unshelved changelist {0} into {1}".format(change, branch_name))
4330 class P4Branches(Command):
4332 Command.__init__(self)
4334 self.description = ("Shows the git branches that hold imports and their "
4335 + "corresponding perforce depot paths")
4336 self.verbose = False
4338 def run(self, args):
4339 if originP4BranchesExist():
4340 createOrUpdateBranchesFromOrigin()
4342 cmdline = "git rev-parse --symbolic "
4343 cmdline += " --remotes"
4345 for line in read_pipe_lines(cmdline):
4348 if not line.startswith('p4/') or line == "p4/HEAD":
4352 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
4353 settings = extractSettingsGitLog(log)
4355 print("%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]))
4358 class HelpFormatter(optparse.IndentedHelpFormatter):
4360 optparse.IndentedHelpFormatter.__init__(self)
4362 def format_description(self, description):
4364 return description + "\n"
4368 def printUsage(commands):
4369 print("usage: %s <command> [options]" % sys.argv[0])
4371 print("valid commands: %s" % ", ".join(commands))
4373 print("Try %s <command> --help for command specific help." % sys.argv[0])
4378 "submit" : P4Submit,
4379 "commit" : P4Submit,
4381 "rebase" : P4Rebase,
4383 "rollback" : P4RollBack,
4384 "branches" : P4Branches,
4385 "unshelve" : P4Unshelve,
4389 if len(sys.argv[1:]) == 0:
4390 printUsage(commands.keys())
4393 cmdName = sys.argv[1]
4395 klass = commands[cmdName]
4398 print("unknown command %s" % cmdName)
4400 printUsage(commands.keys())
4403 options = cmd.options
4404 cmd.gitdir = os.environ.get("GIT_DIR", None)
4408 options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
4410 options.append(optparse.make_option("--git-dir", dest="gitdir"))
4412 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
4414 description = cmd.description,
4415 formatter = HelpFormatter())
4418 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
4424 verbose = cmd.verbose
4426 if cmd.gitdir == None:
4427 cmd.gitdir = os.path.abspath(".git")
4428 if not isValidGitDir(cmd.gitdir):
4429 # "rev-parse --git-dir" without arguments will try $PWD/.git
4430 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
4431 if os.path.exists(cmd.gitdir):
4432 cdup = read_pipe("git rev-parse --show-cdup").strip()
4436 if not isValidGitDir(cmd.gitdir):
4437 if isValidGitDir(cmd.gitdir + "/.git"):
4438 cmd.gitdir += "/.git"
4440 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
4442 # so git commands invoked from the P4 workspace will succeed
4443 os.environ["GIT_DIR"] = cmd.gitdir
4445 if not cmd.run(args):
4450 if __name__ == '__main__':