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