3 # git-p4.py -- A tool for bidirectional operation between a Perforce depot and git.
5 # Author: Simon Hausmann <simon@lst.de>
6 # Copyright: 2007 Simon Hausmann <simon@lst.de>
8 # License: MIT <http://www.opensource.org/licenses/mit-license.php>
11 if sys.version_info.major < 3 and sys.version_info.minor < 7:
12 sys.stderr.write("git-p4: requires Python 2.7 or later.\n")
29 # support basestring in python3
33 # 'unicode' is undefined, must be Python 3
37 basestring = (str,bytes)
39 # 'unicode' exists, must be Python 2
43 basestring = basestring
47 # Only labels/tags matching this will be imported/exported
48 defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
50 # The block size is reduced automatically if required
51 defaultBlockSize = 1<<20
53 p4_access_checked = False
55 def p4_build_cmd(cmd):
56 """Build a suitable p4 command line.
58 This consolidates building and returning a p4 command line into one
59 location. It means that hooking into the environment, or other configuration
60 can be done more easily.
64 user = gitConfig("git-p4.user")
66 real_cmd += ["-u",user]
68 password = gitConfig("git-p4.password")
70 real_cmd += ["-P", password]
72 port = gitConfig("git-p4.port")
74 real_cmd += ["-p", port]
76 host = gitConfig("git-p4.host")
78 real_cmd += ["-H", host]
80 client = gitConfig("git-p4.client")
82 real_cmd += ["-c", client]
84 retries = gitConfigInt("git-p4.retries")
86 # Perform 3 retries by default
89 # Provide a way to not pass this option by setting git-p4.retries to 0
90 real_cmd += ["-r", str(retries)]
92 if not isinstance(cmd, list):
93 real_cmd = ' '.join(real_cmd) + ' ' + cmd
97 # now check that we can actually talk to the server
98 global p4_access_checked
99 if not p4_access_checked:
100 p4_access_checked = True # suppress access checks in p4_check_access itself
106 """ Return TRUE if the given path is a git directory (/path/to/dir/.git).
107 This won't automatically add ".git" to a directory.
109 d = read_pipe(["git", "--git-dir", path, "rev-parse", "--git-dir"], True).strip()
110 if not d or len(d) == 0:
115 def chdir(path, is_client_path=False):
116 """Do chdir to the given path, and set the PWD environment
117 variable for use by P4. It does not look at getcwd() output.
118 Since we're not using the shell, it is necessary to set the
119 PWD environment variable explicitly.
121 Normally, expand the path to force it to be absolute. This
122 addresses the use of relative path names inside P4 settings,
123 e.g. P4CONFIG=.p4config. P4 does not simply open the filename
124 as given; it looks for .p4config using PWD.
126 If is_client_path, the path was handed to us directly by p4,
127 and may be a symbolic link. Do not call os.getcwd() in this
128 case, because it will cause p4 to think that PWD is not inside
133 if not is_client_path:
135 os.environ['PWD'] = path
138 """Return free space in bytes on the disk of the given dirname."""
139 if platform.system() == 'Windows':
140 free_bytes = ctypes.c_ulonglong(0)
141 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()), None, None, ctypes.pointer(free_bytes))
142 return free_bytes.value
144 st = os.statvfs(os.getcwd())
145 return st.f_bavail * st.f_frsize
151 sys.stderr.write(msg + "\n")
154 def write_pipe(c, stdin):
156 sys.stderr.write('Writing pipe: %s\n' % str(c))
158 expand = not isinstance(c, list)
159 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
161 val = pipe.write(stdin)
164 die('Command failed: %s' % str(c))
168 def p4_write_pipe(c, stdin):
169 real_cmd = p4_build_cmd(c)
170 return write_pipe(real_cmd, stdin)
172 def read_pipe_full(c):
173 """ Read output from command. Returns a tuple
174 of the return status, stdout text and stderr
178 sys.stderr.write('Reading pipe: %s\n' % str(c))
180 expand = not isinstance(c, list)
181 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand)
182 (out, err) = p.communicate()
183 return (p.returncode, out, err)
185 def read_pipe(c, ignore_error=False):
186 """ Read output from command. Returns the output text on
187 success. On failure, terminates execution, unless
188 ignore_error is True, when it returns an empty string.
190 (retcode, out, err) = read_pipe_full(c)
195 die('Command failed: %s\nError: %s' % (str(c), err))
198 def read_pipe_text(c):
199 """ Read output from a command with trailing whitespace stripped.
200 On error, returns None.
202 (retcode, out, err) = read_pipe_full(c)
208 def p4_read_pipe(c, ignore_error=False):
209 real_cmd = p4_build_cmd(c)
210 return read_pipe(real_cmd, ignore_error)
212 def read_pipe_lines(c):
214 sys.stderr.write('Reading pipe: %s\n' % str(c))
216 expand = not isinstance(c, list)
217 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
219 val = pipe.readlines()
220 if pipe.close() or p.wait():
221 die('Command failed: %s' % str(c))
225 def p4_read_pipe_lines(c):
226 """Specifically invoke p4 on the command supplied. """
227 real_cmd = p4_build_cmd(c)
228 return read_pipe_lines(real_cmd)
230 def p4_has_command(cmd):
231 """Ask p4 for help on this command. If it returns an error, the
232 command does not exist in this version of p4."""
233 real_cmd = p4_build_cmd(["help", cmd])
234 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
235 stderr=subprocess.PIPE)
237 return p.returncode == 0
239 def p4_has_move_command():
240 """See if the move command exists, that it supports -k, and that
241 it has not been administratively disabled. The arguments
242 must be correct, but the filenames do not have to exist. Use
243 ones with wildcards so even if they exist, it will fail."""
245 if not p4_has_command("move"):
247 cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
248 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
249 (out, err) = p.communicate()
250 # return code will be 1 in either case
251 if err.find("Invalid option") >= 0:
253 if err.find("disabled") >= 0:
255 # assume it failed because @... was invalid changelist
258 def system(cmd, ignore_error=False):
259 expand = not isinstance(cmd, list)
261 sys.stderr.write("executing %s\n" % str(cmd))
262 retcode = subprocess.call(cmd, shell=expand)
263 if retcode and not ignore_error:
264 raise CalledProcessError(retcode, cmd)
269 """Specifically invoke p4 as the system command. """
270 real_cmd = p4_build_cmd(cmd)
271 expand = not isinstance(real_cmd, list)
272 retcode = subprocess.call(real_cmd, shell=expand)
274 raise CalledProcessError(retcode, real_cmd)
276 def die_bad_access(s):
277 die("failure accessing depot: {0}".format(s.rstrip()))
279 def p4_check_access(min_expiration=1):
280 """ Check if we can access Perforce - account still logged in
282 results = p4CmdList(["login", "-s"])
284 if len(results) == 0:
285 # should never get here: always get either some results, or a p4ExitCode
286 assert("could not parse response from perforce")
290 if 'p4ExitCode' in result:
291 # p4 returned non-zero status, e.g. P4PORT invalid, or p4 not in path
292 die_bad_access("could not run p4")
294 code = result.get("code")
296 # we get here if we couldn't connect and there was nothing to unmarshal
297 die_bad_access("could not connect")
300 expiry = result.get("TicketExpiration")
303 if expiry > min_expiration:
307 die_bad_access("perforce ticket expires in {0} seconds".format(expiry))
310 # account without a timeout - all ok
313 elif code == "error":
314 data = result.get("data")
316 die_bad_access("p4 error: {0}".format(data))
318 die_bad_access("unknown error")
322 die_bad_access("unknown error code {0}".format(code))
324 _p4_version_string = None
325 def p4_version_string():
326 """Read the version string, showing just the last line, which
327 hopefully is the interesting version bit.
330 Perforce - The Fast Software Configuration Management System.
331 Copyright 1995-2011 Perforce Software. All rights reserved.
332 Rev. P4/NTX86/2011.1/393975 (2011/12/16).
334 global _p4_version_string
335 if not _p4_version_string:
336 a = p4_read_pipe_lines(["-V"])
337 _p4_version_string = a[-1].rstrip()
338 return _p4_version_string
340 def p4_integrate(src, dest):
341 p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
343 def p4_sync(f, *options):
344 p4_system(["sync"] + list(options) + [wildcard_encode(f)])
347 # forcibly add file names with wildcards
348 if wildcard_present(f):
349 p4_system(["add", "-f", f])
351 p4_system(["add", f])
354 p4_system(["delete", wildcard_encode(f)])
356 def p4_edit(f, *options):
357 p4_system(["edit"] + list(options) + [wildcard_encode(f)])
360 p4_system(["revert", wildcard_encode(f)])
362 def p4_reopen(type, f):
363 p4_system(["reopen", "-t", type, wildcard_encode(f)])
365 def p4_reopen_in_change(changelist, files):
366 cmd = ["reopen", "-c", str(changelist)] + files
369 def p4_move(src, dest):
370 p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
372 def p4_last_change():
373 results = p4CmdList(["changes", "-m", "1"], skip_info=True)
374 return int(results[0]['change'])
376 def p4_describe(change, shelved=False):
377 """Make sure it returns a valid result by checking for
378 the presence of field "time". Return a dict of the
381 cmd = ["describe", "-s"]
386 ds = p4CmdList(cmd, skip_info=True)
388 die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
392 if "p4ExitCode" in d:
393 die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
396 if d["code"] == "error":
397 die("p4 describe -s %d returned error code: %s" % (change, str(d)))
400 die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
405 # Canonicalize the p4 type and return a tuple of the
406 # base type, plus any modifiers. See "p4 help filetypes"
407 # for a list and explanation.
409 def split_p4_type(p4type):
411 p4_filetypes_historical = {
412 "ctempobj": "binary+Sw",
418 "tempobj": "binary+FSw",
419 "ubinary": "binary+F",
420 "uresource": "resource+F",
421 "uxbinary": "binary+Fx",
422 "xbinary": "binary+x",
424 "xtempobj": "binary+Swx",
426 "xunicode": "unicode+x",
429 if p4type in p4_filetypes_historical:
430 p4type = p4_filetypes_historical[p4type]
432 s = p4type.split("+")
440 # return the raw p4 type of a file (text, text+ko, etc)
443 results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)])
444 return results[0]['headType']
447 # Given a type base and modifier, return a regexp matching
448 # the keywords that can be expanded in the file
450 def p4_keywords_regexp_for_type(base, type_mods):
451 if base in ("text", "unicode", "binary"):
453 if "ko" in type_mods:
455 elif "k" in type_mods:
456 kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
460 \$ # Starts with a dollar, followed by...
461 (%s) # one of the keywords, followed by...
462 (:[^$\n]+)? # possibly an old expansion, followed by...
470 # Given a file, return a regexp matching the possible
471 # RCS keywords that will be expanded, or None for files
472 # with kw expansion turned off.
474 def p4_keywords_regexp_for_file(file):
475 if not os.path.exists(file):
478 (type_base, type_mods) = split_p4_type(p4_type(file))
479 return p4_keywords_regexp_for_type(type_base, type_mods)
481 def setP4ExecBit(file, mode):
482 # Reopens an already open file and changes the execute bit to match
483 # the execute bit setting in the passed in mode.
487 if not isModeExec(mode):
488 p4Type = getP4OpenedType(file)
489 p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
490 p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
491 if p4Type[-1] == "+":
492 p4Type = p4Type[0:-1]
494 p4_reopen(p4Type, file)
496 def getP4OpenedType(file):
497 # Returns the perforce file type for the given file.
499 result = p4_read_pipe(["opened", wildcard_encode(file)])
500 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result)
502 return match.group(1)
504 die("Could not determine file type for %s (result: '%s')" % (file, result))
506 # Return the set of all p4 labels
507 def getP4Labels(depotPaths):
509 if not isinstance(depotPaths, list):
510 depotPaths = [depotPaths]
512 for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
518 # Return the set of all git tags
521 for line in read_pipe_lines(["git", "tag"]):
526 def diffTreePattern():
527 # This is a simple generator for the diff tree regex pattern. This could be
528 # a class variable if this and parseDiffTreeEntry were a part of a class.
529 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
533 def parseDiffTreeEntry(entry):
534 """Parses a single diff tree entry into its component elements.
536 See git-diff-tree(1) manpage for details about the format of the diff
537 output. This method returns a dictionary with the following elements:
539 src_mode - The mode of the source file
540 dst_mode - The mode of the destination file
541 src_sha1 - The sha1 for the source file
542 dst_sha1 - The sha1 fr the destination file
543 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
544 status_score - The score for the status (applicable for 'C' and 'R'
545 statuses). This is None if there is no score.
546 src - The path for the source file.
547 dst - The path for the destination file. This is only present for
548 copy or renames. If it is not present, this is None.
550 If the pattern is not matched, None is returned."""
552 match = diffTreePattern().next().match(entry)
555 'src_mode': match.group(1),
556 'dst_mode': match.group(2),
557 'src_sha1': match.group(3),
558 'dst_sha1': match.group(4),
559 'status': match.group(5),
560 'status_score': match.group(6),
561 'src': match.group(7),
562 'dst': match.group(10)
566 def isModeExec(mode):
567 # Returns True if the given git mode represents an executable file,
569 return mode[-3:] == "755"
571 class P4Exception(Exception):
572 """ Base class for exceptions from the p4 client """
573 def __init__(self, exit_code):
574 self.p4ExitCode = exit_code
576 class P4ServerException(P4Exception):
577 """ Base class for exceptions where we get some kind of marshalled up result from the server """
578 def __init__(self, exit_code, p4_result):
579 super(P4ServerException, self).__init__(exit_code)
580 self.p4_result = p4_result
581 self.code = p4_result[0]['code']
582 self.data = p4_result[0]['data']
584 class P4RequestSizeException(P4ServerException):
585 """ One of the maxresults or maxscanrows errors """
586 def __init__(self, exit_code, p4_result, limit):
587 super(P4RequestSizeException, self).__init__(exit_code, p4_result)
590 def isModeExecChanged(src_mode, dst_mode):
591 return isModeExec(src_mode) != isModeExec(dst_mode)
593 def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,
594 errors_as_exceptions=False):
596 if not isinstance(cmd, list):
603 cmd = p4_build_cmd(cmd)
605 sys.stderr.write("Opening pipe: %s\n" % str(cmd))
607 # Use a temporary file to avoid deadlocks without
608 # subprocess.communicate(), which would put another copy
609 # of stdout into memory.
611 if stdin is not None:
612 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
613 if not isinstance(stdin, list):
614 stdin_file.write(stdin)
617 stdin_file.write(i + '\n')
621 p4 = subprocess.Popen(cmd,
624 stdout=subprocess.PIPE)
629 entry = marshal.load(p4.stdout)
631 if 'code' in entry and entry['code'] == 'info':
641 if errors_as_exceptions:
643 data = result[0].get('data')
645 m = re.search('Too many rows scanned \(over (\d+)\)', data)
647 m = re.search('Request too large \(over (\d+)\)', data)
650 limit = int(m.group(1))
651 raise P4RequestSizeException(exitCode, result, limit)
653 raise P4ServerException(exitCode, result)
655 raise P4Exception(exitCode)
658 entry["p4ExitCode"] = exitCode
664 list = p4CmdList(cmd)
670 def p4Where(depotPath):
671 if not depotPath.endswith("/"):
673 depotPathLong = depotPath + "..."
674 outputList = p4CmdList(["where", depotPathLong])
676 for entry in outputList:
677 if "depotFile" in entry:
678 # Search for the base client side depot path, as long as it starts with the branch's P4 path.
679 # The base path always ends with "/...".
680 if entry["depotFile"].find(depotPath) == 0 and entry["depotFile"][-4:] == "/...":
683 elif "data" in entry:
684 data = entry.get("data")
685 space = data.find(" ")
686 if data[:space] == depotPath:
691 if output["code"] == "error":
695 clientPath = output.get("path")
696 elif "data" in output:
697 data = output.get("data")
698 lastSpace = data.rfind(" ")
699 clientPath = data[lastSpace + 1:]
701 if clientPath.endswith("..."):
702 clientPath = clientPath[:-3]
705 def currentGitBranch():
706 return read_pipe_text(["git", "symbolic-ref", "--short", "-q", "HEAD"])
708 def isValidGitDir(path):
709 return git_dir(path) != None
711 def parseRevision(ref):
712 return read_pipe("git rev-parse %s" % ref).strip()
714 def branchExists(ref):
715 rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
719 def extractLogMessageFromGitCommit(commit):
722 ## fixme: title is first line of commit, not 1st paragraph.
724 for log in read_pipe_lines(["git", "cat-file", "commit", commit]):
733 def extractSettingsGitLog(log):
735 for line in log.split("\n"):
737 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
741 assignments = m.group(1).split (':')
742 for a in assignments:
744 key = vals[0].strip()
745 val = ('='.join (vals[1:])).strip()
746 if val.endswith ('\"') and val.startswith('"'):
751 paths = values.get("depot-paths")
753 paths = values.get("depot-path")
755 values['depot-paths'] = paths.split(',')
758 def gitBranchExists(branch):
759 proc = subprocess.Popen(["git", "rev-parse", branch],
760 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
761 return proc.wait() == 0;
763 def gitUpdateRef(ref, newvalue):
764 subprocess.check_call(["git", "update-ref", ref, newvalue])
766 def gitDeleteRef(ref):
767 subprocess.check_call(["git", "update-ref", "-d", ref])
771 def gitConfig(key, typeSpecifier=None):
772 if key not in _gitConfig:
773 cmd = [ "git", "config" ]
775 cmd += [ typeSpecifier ]
777 s = read_pipe(cmd, ignore_error=True)
778 _gitConfig[key] = s.strip()
779 return _gitConfig[key]
781 def gitConfigBool(key):
782 """Return a bool, using git config --bool. It is True only if the
783 variable is set to true, and False if set to false or not present
786 if key not in _gitConfig:
787 _gitConfig[key] = gitConfig(key, '--bool') == "true"
788 return _gitConfig[key]
790 def gitConfigInt(key):
791 if key not in _gitConfig:
792 cmd = [ "git", "config", "--int", key ]
793 s = read_pipe(cmd, ignore_error=True)
796 _gitConfig[key] = int(gitConfig(key, '--int'))
798 _gitConfig[key] = None
799 return _gitConfig[key]
801 def gitConfigList(key):
802 if key not in _gitConfig:
803 s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
804 _gitConfig[key] = s.strip().splitlines()
805 if _gitConfig[key] == ['']:
807 return _gitConfig[key]
809 def p4BranchesInGit(branchesAreInRemotes=True):
810 """Find all the branches whose names start with "p4/", looking
811 in remotes or heads as specified by the argument. Return
812 a dictionary of { branch: revision } for each one found.
813 The branch names are the short names, without any
818 cmdline = "git rev-parse --symbolic "
819 if branchesAreInRemotes:
820 cmdline += "--remotes"
822 cmdline += "--branches"
824 for line in read_pipe_lines(cmdline):
828 if not line.startswith('p4/'):
830 # special symbolic ref to p4/master
831 if line == "p4/HEAD":
834 # strip off p4/ prefix
835 branch = line[len("p4/"):]
837 branches[branch] = parseRevision(line)
841 def branch_exists(branch):
842 """Make sure that the given ref name really exists."""
844 cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
845 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
846 out, _ = p.communicate()
849 # expect exactly one line of output: the branch name
850 return out.rstrip() == branch
852 def findUpstreamBranchPoint(head = "HEAD"):
853 branches = p4BranchesInGit()
854 # map from depot-path to branch name
855 branchByDepotPath = {}
856 for branch in branches.keys():
857 tip = branches[branch]
858 log = extractLogMessageFromGitCommit(tip)
859 settings = extractSettingsGitLog(log)
860 if "depot-paths" in settings:
861 paths = ",".join(settings["depot-paths"])
862 branchByDepotPath[paths] = "remotes/p4/" + branch
866 while parent < 65535:
867 commit = head + "~%s" % parent
868 log = extractLogMessageFromGitCommit(commit)
869 settings = extractSettingsGitLog(log)
870 if "depot-paths" in settings:
871 paths = ",".join(settings["depot-paths"])
872 if paths in branchByDepotPath:
873 return [branchByDepotPath[paths], settings]
877 return ["", settings]
879 def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
881 print("Creating/updating branch(es) in %s based on origin branch(es)"
884 originPrefix = "origin/p4/"
886 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
888 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
891 headName = line[len(originPrefix):]
892 remoteHead = localRefPrefix + headName
895 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
896 if ('depot-paths' not in original
897 or 'change' not in original):
901 if not gitBranchExists(remoteHead):
903 print("creating %s" % remoteHead)
906 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
907 if 'change' in settings:
908 if settings['depot-paths'] == original['depot-paths']:
909 originP4Change = int(original['change'])
910 p4Change = int(settings['change'])
911 if originP4Change > p4Change:
912 print("%s (%s) is newer than %s (%s). "
913 "Updating p4 branch from origin."
914 % (originHead, originP4Change,
915 remoteHead, p4Change))
918 print("Ignoring: %s was imported from %s while "
919 "%s was imported from %s"
920 % (originHead, ','.join(original['depot-paths']),
921 remoteHead, ','.join(settings['depot-paths'])))
924 system("git update-ref %s %s" % (remoteHead, originHead))
926 def originP4BranchesExist():
927 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
930 def p4ParseNumericChangeRange(parts):
931 changeStart = int(parts[0][1:])
932 if parts[1] == '#head':
933 changeEnd = p4_last_change()
935 changeEnd = int(parts[1])
937 return (changeStart, changeEnd)
939 def chooseBlockSize(blockSize):
943 return defaultBlockSize
945 def p4ChangesForPaths(depotPaths, changeRange, requestedBlockSize):
948 # Parse the change range into start and end. Try to find integer
949 # revision ranges as these can be broken up into blocks to avoid
950 # hitting server-side limits (maxrows, maxscanresults). But if
951 # that doesn't work, fall back to using the raw revision specifier
952 # strings, without using block mode.
954 if changeRange is None or changeRange == '':
956 changeEnd = p4_last_change()
957 block_size = chooseBlockSize(requestedBlockSize)
959 parts = changeRange.split(',')
960 assert len(parts) == 2
962 (changeStart, changeEnd) = p4ParseNumericChangeRange(parts)
963 block_size = chooseBlockSize(requestedBlockSize)
965 changeStart = parts[0][1:]
967 if requestedBlockSize:
968 die("cannot use --changes-block-size with non-numeric revisions")
973 # Retrieve changes a block at a time, to prevent running
974 # into a MaxResults/MaxScanRows error from the server. If
975 # we _do_ hit one of those errors, turn down the block size
981 end = min(changeEnd, changeStart + block_size)
982 revisionRange = "%d,%d" % (changeStart, end)
984 revisionRange = "%s,%s" % (changeStart, changeEnd)
987 cmd += ["%s...@%s" % (p, revisionRange)]
991 result = p4CmdList(cmd, errors_as_exceptions=True)
992 except P4RequestSizeException as e:
995 elif block_size > e.limit:
998 block_size = max(2, block_size // 2)
1000 if verbose: print("block size error, retrying with block size {0}".format(block_size))
1002 except P4Exception as e:
1003 die('Error retrieving changes description ({0})'.format(e.p4ExitCode))
1005 # Insert changes in chronological order
1006 for entry in reversed(result):
1007 if 'change' not in entry:
1009 changes.add(int(entry['change']))
1014 if end >= changeEnd:
1017 changeStart = end + 1
1019 changes = sorted(changes)
1022 def p4PathStartsWith(path, prefix):
1023 # This method tries to remedy a potential mixed-case issue:
1025 # If UserA adds //depot/DirA/file1
1026 # and UserB adds //depot/dira/file2
1028 # we may or may not have a problem. If you have core.ignorecase=true,
1029 # we treat DirA and dira as the same directory
1030 if gitConfigBool("core.ignorecase"):
1031 return path.lower().startswith(prefix.lower())
1032 return path.startswith(prefix)
1034 def getClientSpec():
1035 """Look at the p4 client spec, create a View() object that contains
1036 all the mappings, and return it."""
1038 specList = p4CmdList("client -o")
1039 if len(specList) != 1:
1040 die('Output from "client -o" is %d lines, expecting 1' %
1043 # dictionary of all client parameters
1046 # the //client/ name
1047 client_name = entry["Client"]
1049 # just the keys that start with "View"
1050 view_keys = [ k for k in entry.keys() if k.startswith("View") ]
1052 # hold this new View
1053 view = View(client_name)
1055 # append the lines, in order, to the view
1056 for view_num in range(len(view_keys)):
1057 k = "View%d" % view_num
1058 if k not in view_keys:
1059 die("Expected view key %s missing" % k)
1060 view.append(entry[k])
1064 def getClientRoot():
1065 """Grab the client directory."""
1067 output = p4CmdList("client -o")
1068 if len(output) != 1:
1069 die('Output from "client -o" is %d lines, expecting 1' % len(output))
1072 if "Root" not in entry:
1073 die('Client has no "Root"')
1075 return entry["Root"]
1078 # P4 wildcards are not allowed in filenames. P4 complains
1079 # if you simply add them, but you can force it with "-f", in
1080 # which case it translates them into %xx encoding internally.
1082 def wildcard_decode(path):
1083 # Search for and fix just these four characters. Do % last so
1084 # that fixing it does not inadvertently create new %-escapes.
1085 # Cannot have * in a filename in windows; untested as to
1086 # what p4 would do in such a case.
1087 if not platform.system() == "Windows":
1088 path = path.replace("%2A", "*")
1089 path = path.replace("%23", "#") \
1090 .replace("%40", "@") \
1091 .replace("%25", "%")
1094 def wildcard_encode(path):
1095 # do % first to avoid double-encoding the %s introduced here
1096 path = path.replace("%", "%25") \
1097 .replace("*", "%2A") \
1098 .replace("#", "%23") \
1099 .replace("@", "%40")
1102 def wildcard_present(path):
1103 m = re.search("[*#@%]", path)
1104 return m is not None
1106 class LargeFileSystem(object):
1107 """Base class for large file system support."""
1109 def __init__(self, writeToGitStream):
1110 self.largeFiles = set()
1111 self.writeToGitStream = writeToGitStream
1113 def generatePointer(self, cloneDestination, contentFile):
1114 """Return the content of a pointer file that is stored in Git instead of
1115 the actual content."""
1116 assert False, "Method 'generatePointer' required in " + self.__class__.__name__
1118 def pushFile(self, localLargeFile):
1119 """Push the actual content which is not stored in the Git repository to
1121 assert False, "Method 'pushFile' required in " + self.__class__.__name__
1123 def hasLargeFileExtension(self, relPath):
1125 lambda a, b: a or b,
1126 [relPath.endswith('.' + e) for e in gitConfigList('git-p4.largeFileExtensions')],
1130 def generateTempFile(self, contents):
1131 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False)
1133 contentFile.write(d)
1135 return contentFile.name
1137 def exceedsLargeFileThreshold(self, relPath, contents):
1138 if gitConfigInt('git-p4.largeFileThreshold'):
1139 contentsSize = sum(len(d) for d in contents)
1140 if contentsSize > gitConfigInt('git-p4.largeFileThreshold'):
1142 if gitConfigInt('git-p4.largeFileCompressedThreshold'):
1143 contentsSize = sum(len(d) for d in contents)
1144 if contentsSize <= gitConfigInt('git-p4.largeFileCompressedThreshold'):
1146 contentTempFile = self.generateTempFile(contents)
1147 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=True)
1148 with zipfile.ZipFile(compressedContentFile, mode='w') as zf:
1149 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED)
1150 compressedContentsSize = zf.infolist()[0].compress_size
1151 os.remove(contentTempFile)
1152 if compressedContentsSize > gitConfigInt('git-p4.largeFileCompressedThreshold'):
1156 def addLargeFile(self, relPath):
1157 self.largeFiles.add(relPath)
1159 def removeLargeFile(self, relPath):
1160 self.largeFiles.remove(relPath)
1162 def isLargeFile(self, relPath):
1163 return relPath in self.largeFiles
1165 def processContent(self, git_mode, relPath, contents):
1166 """Processes the content of git fast import. This method decides if a
1167 file is stored in the large file system and handles all necessary
1169 if self.exceedsLargeFileThreshold(relPath, contents) or self.hasLargeFileExtension(relPath):
1170 contentTempFile = self.generateTempFile(contents)
1171 (pointer_git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)
1172 if pointer_git_mode:
1173 git_mode = pointer_git_mode
1175 # Move temp file to final location in large file system
1176 largeFileDir = os.path.dirname(localLargeFile)
1177 if not os.path.isdir(largeFileDir):
1178 os.makedirs(largeFileDir)
1179 shutil.move(contentTempFile, localLargeFile)
1180 self.addLargeFile(relPath)
1181 if gitConfigBool('git-p4.largeFilePush'):
1182 self.pushFile(localLargeFile)
1184 sys.stderr.write("%s moved to large file system (%s)\n" % (relPath, localLargeFile))
1185 return (git_mode, contents)
1187 class MockLFS(LargeFileSystem):
1188 """Mock large file system for testing."""
1190 def generatePointer(self, contentFile):
1191 """The pointer content is the original content prefixed with "pointer-".
1192 The local filename of the large file storage is derived from the file content.
1194 with open(contentFile, 'r') as f:
1197 pointerContents = 'pointer-' + content
1198 localLargeFile = os.path.join(os.getcwd(), '.git', 'mock-storage', 'local', content[:-1])
1199 return (gitMode, pointerContents, localLargeFile)
1201 def pushFile(self, localLargeFile):
1202 """The remote filename of the large file storage is the same as the local
1203 one but in a different directory.
1205 remotePath = os.path.join(os.path.dirname(localLargeFile), '..', 'remote')
1206 if not os.path.exists(remotePath):
1207 os.makedirs(remotePath)
1208 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))
1210 class GitLFS(LargeFileSystem):
1211 """Git LFS as backend for the git-p4 large file system.
1212 See https://git-lfs.github.com/ for details."""
1214 def __init__(self, *args):
1215 LargeFileSystem.__init__(self, *args)
1216 self.baseGitAttributes = []
1218 def generatePointer(self, contentFile):
1219 """Generate a Git LFS pointer for the content. Return LFS Pointer file
1220 mode and content which is stored in the Git repository instead of
1221 the actual content. Return also the new location of the actual
1224 if os.path.getsize(contentFile) == 0:
1225 return (None, '', None)
1227 pointerProcess = subprocess.Popen(
1228 ['git', 'lfs', 'pointer', '--file=' + contentFile],
1229 stdout=subprocess.PIPE
1231 pointerFile = pointerProcess.stdout.read()
1232 if pointerProcess.wait():
1233 os.remove(contentFile)
1234 die('git-lfs pointer command failed. Did you install the extension?')
1236 # Git LFS removed the preamble in the output of the 'pointer' command
1237 # starting from version 1.2.0. Check for the preamble here to support
1239 # c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b43
1240 if pointerFile.startswith('Git LFS pointer for'):
1241 pointerFile = re.sub(r'Git LFS pointer for.*\n\n', '', pointerFile)
1243 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)
1244 localLargeFile = os.path.join(
1246 '.git', 'lfs', 'objects', oid[:2], oid[2:4],
1249 # LFS Spec states that pointer files should not have the executable bit set.
1251 return (gitMode, pointerFile, localLargeFile)
1253 def pushFile(self, localLargeFile):
1254 uploadProcess = subprocess.Popen(
1255 ['git', 'lfs', 'push', '--object-id', 'origin', os.path.basename(localLargeFile)]
1257 if uploadProcess.wait():
1258 die('git-lfs push command failed. Did you define a remote?')
1260 def generateGitAttributes(self):
1262 self.baseGitAttributes +
1266 '# Git LFS (see https://git-lfs.github.com/)\n',
1269 ['*.' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1270 for f in sorted(gitConfigList('git-p4.largeFileExtensions'))
1272 ['/' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1273 for f in sorted(self.largeFiles) if not self.hasLargeFileExtension(f)
1277 def addLargeFile(self, relPath):
1278 LargeFileSystem.addLargeFile(self, relPath)
1279 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
1281 def removeLargeFile(self, relPath):
1282 LargeFileSystem.removeLargeFile(self, relPath)
1283 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
1285 def processContent(self, git_mode, relPath, contents):
1286 if relPath == '.gitattributes':
1287 self.baseGitAttributes = contents
1288 return (git_mode, self.generateGitAttributes())
1290 return LargeFileSystem.processContent(self, git_mode, relPath, contents)
1293 delete_actions = ( "delete", "move/delete", "purge" )
1294 add_actions = ( "add", "branch", "move/add" )
1297 self.usage = "usage: %prog [options]"
1298 self.needsGit = True
1299 self.verbose = False
1301 # This is required for the "append" update_shelve action
1302 def ensure_value(self, attr, value):
1303 if not hasattr(self, attr) or getattr(self, attr) is None:
1304 setattr(self, attr, value)
1305 return getattr(self, attr)
1309 self.userMapFromPerforceServer = False
1310 self.myP4UserId = None
1314 return self.myP4UserId
1316 results = p4CmdList("user -o")
1319 self.myP4UserId = r['User']
1321 die("Could not find your p4 user id")
1323 def p4UserIsMe(self, p4User):
1324 # return True if the given p4 user is actually me
1325 me = self.p4UserId()
1326 if not p4User or p4User != me:
1331 def getUserCacheFilename(self):
1332 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
1333 return home + "/.gitp4-usercache.txt"
1335 def getUserMapFromPerforceServer(self):
1336 if self.userMapFromPerforceServer:
1341 for output in p4CmdList("users"):
1342 if "User" not in output:
1344 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
1345 self.emails[output["Email"]] = output["User"]
1347 mapUserConfigRegex = re.compile(r"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE)
1348 for mapUserConfig in gitConfigList("git-p4.mapUser"):
1349 mapUser = mapUserConfigRegex.findall(mapUserConfig)
1350 if mapUser and len(mapUser[0]) == 3:
1351 user = mapUser[0][0]
1352 fullname = mapUser[0][1]
1353 email = mapUser[0][2]
1354 self.users[user] = fullname + " <" + email + ">"
1355 self.emails[email] = user
1358 for (key, val) in self.users.items():
1359 s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
1361 open(self.getUserCacheFilename(), "wb").write(s)
1362 self.userMapFromPerforceServer = True
1364 def loadUserMapFromCache(self):
1366 self.userMapFromPerforceServer = False
1368 cache = open(self.getUserCacheFilename(), "rb")
1369 lines = cache.readlines()
1372 entry = line.strip().split("\t")
1373 self.users[entry[0]] = entry[1]
1375 self.getUserMapFromPerforceServer()
1377 class P4Debug(Command):
1379 Command.__init__(self)
1381 self.description = "A tool to debug the output of p4 -G."
1382 self.needsGit = False
1384 def run(self, args):
1386 for output in p4CmdList(args):
1387 print('Element: %d' % j)
1392 class P4RollBack(Command):
1394 Command.__init__(self)
1396 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
1398 self.description = "A tool to debug the multi-branch import. Don't use :)"
1399 self.rollbackLocalBranches = False
1401 def run(self, args):
1404 maxChange = int(args[0])
1406 if "p4ExitCode" in p4Cmd("changes -m 1"):
1407 die("Problems executing p4");
1409 if self.rollbackLocalBranches:
1410 refPrefix = "refs/heads/"
1411 lines = read_pipe_lines("git rev-parse --symbolic --branches")
1413 refPrefix = "refs/remotes/"
1414 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
1417 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
1419 ref = refPrefix + line
1420 log = extractLogMessageFromGitCommit(ref)
1421 settings = extractSettingsGitLog(log)
1423 depotPaths = settings['depot-paths']
1424 change = settings['change']
1428 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
1429 for p in depotPaths]))) == 0:
1430 print("Branch %s did not exist at change %s, deleting." % (ref, maxChange))
1431 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
1434 while change and int(change) > maxChange:
1437 print("%s is at %s ; rewinding towards %s" % (ref, change, maxChange))
1438 system("git update-ref %s \"%s^\"" % (ref, ref))
1439 log = extractLogMessageFromGitCommit(ref)
1440 settings = extractSettingsGitLog(log)
1443 depotPaths = settings['depot-paths']
1444 change = settings['change']
1447 print("%s rewound to %s" % (ref, change))
1451 class P4Submit(Command, P4UserMap):
1453 conflict_behavior_choices = ("ask", "skip", "quit")
1456 Command.__init__(self)
1457 P4UserMap.__init__(self)
1459 optparse.make_option("--origin", dest="origin"),
1460 optparse.make_option("-M", dest="detectRenames", action="store_true"),
1461 # preserve the user, requires relevant p4 permissions
1462 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
1463 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
1464 optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
1465 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
1466 optparse.make_option("--conflict", dest="conflict_behavior",
1467 choices=self.conflict_behavior_choices),
1468 optparse.make_option("--branch", dest="branch"),
1469 optparse.make_option("--shelve", dest="shelve", action="store_true",
1470 help="Shelve instead of submit. Shelved files are reverted, "
1471 "restoring the workspace to the state before the shelve"),
1472 optparse.make_option("--update-shelve", dest="update_shelve", action="append", type="int",
1473 metavar="CHANGELIST",
1474 help="update an existing shelved changelist, implies --shelve, "
1475 "repeat in-order for multiple shelved changelists"),
1476 optparse.make_option("--commit", dest="commit", metavar="COMMIT",
1477 help="submit only the specified commit(s), one commit or xxx..xxx"),
1478 optparse.make_option("--disable-rebase", dest="disable_rebase", action="store_true",
1479 help="Disable rebase after submit is completed. Can be useful if you "
1480 "work from a local git branch that is not master"),
1481 optparse.make_option("--disable-p4sync", dest="disable_p4sync", action="store_true",
1482 help="Skip Perforce sync of p4/master after submit or shelve"),
1484 self.description = """Submit changes from git to the perforce depot.\n
1485 The `p4-pre-submit` hook is executed if it exists and is executable.
1486 The hook takes no parameters and nothing from standard input. Exiting with
1487 non-zero status from this script prevents `git-p4 submit` from launching.
1489 One usage scenario is to run unit tests in the hook."""
1491 self.usage += " [name of git branch to submit into perforce depot]"
1493 self.detectRenames = False
1494 self.preserveUser = gitConfigBool("git-p4.preserveUser")
1495 self.dry_run = False
1497 self.update_shelve = list()
1499 self.disable_rebase = gitConfigBool("git-p4.disableRebase")
1500 self.disable_p4sync = gitConfigBool("git-p4.disableP4Sync")
1501 self.prepare_p4_only = False
1502 self.conflict_behavior = None
1503 self.isWindows = (platform.system() == "Windows")
1504 self.exportLabels = False
1505 self.p4HasMoveCommand = p4_has_move_command()
1508 if gitConfig('git-p4.largeFileSystem'):
1509 die("Large file system not supported for git-p4 submit command. Please remove it from config.")
1512 if len(p4CmdList("opened ...")) > 0:
1513 die("You have files opened with perforce! Close them before starting the sync.")
1515 def separate_jobs_from_description(self, message):
1516 """Extract and return a possible Jobs field in the commit
1517 message. It goes into a separate section in the p4 change
1520 A jobs line starts with "Jobs:" and looks like a new field
1521 in a form. Values are white-space separated on the same
1522 line or on following lines that start with a tab.
1524 This does not parse and extract the full git commit message
1525 like a p4 form. It just sees the Jobs: line as a marker
1526 to pass everything from then on directly into the p4 form,
1527 but outside the description section.
1529 Return a tuple (stripped log message, jobs string)."""
1531 m = re.search(r'^Jobs:', message, re.MULTILINE)
1533 return (message, None)
1535 jobtext = message[m.start():]
1536 stripped_message = message[:m.start()].rstrip()
1537 return (stripped_message, jobtext)
1539 def prepareLogMessage(self, template, message, jobs):
1540 """Edits the template returned from "p4 change -o" to insert
1541 the message in the Description field, and the jobs text in
1545 inDescriptionSection = False
1547 for line in template.split("\n"):
1548 if line.startswith("#"):
1549 result += line + "\n"
1552 if inDescriptionSection:
1553 if line.startswith("Files:") or line.startswith("Jobs:"):
1554 inDescriptionSection = False
1555 # insert Jobs section
1557 result += jobs + "\n"
1561 if line.startswith("Description:"):
1562 inDescriptionSection = True
1564 for messageLine in message.split("\n"):
1565 line += "\t" + messageLine + "\n"
1567 result += line + "\n"
1571 def patchRCSKeywords(self, file, pattern):
1572 # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
1573 (handle, outFileName) = tempfile.mkstemp(dir='.')
1575 outFile = os.fdopen(handle, "w+")
1576 inFile = open(file, "r")
1577 regexp = re.compile(pattern, re.VERBOSE)
1578 for line in inFile.readlines():
1579 line = regexp.sub(r'$\1$', line)
1583 # Forcibly overwrite the original file
1585 shutil.move(outFileName, file)
1587 # cleanup our temporary file
1588 os.unlink(outFileName)
1589 print("Failed to strip RCS keywords in %s" % file)
1592 print("Patched up RCS keywords in %s" % file)
1594 def p4UserForCommit(self,id):
1595 # Return the tuple (perforce user,git email) for a given git commit id
1596 self.getUserMapFromPerforceServer()
1597 gitEmail = read_pipe(["git", "log", "--max-count=1",
1598 "--format=%ae", id])
1599 gitEmail = gitEmail.strip()
1600 if gitEmail not in self.emails:
1601 return (None,gitEmail)
1603 return (self.emails[gitEmail],gitEmail)
1605 def checkValidP4Users(self,commits):
1606 # check if any git authors cannot be mapped to p4 users
1608 (user,email) = self.p4UserForCommit(id)
1610 msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
1611 if gitConfigBool("git-p4.allowMissingP4Users"):
1614 die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
1616 def lastP4Changelist(self):
1617 # Get back the last changelist number submitted in this client spec. This
1618 # then gets used to patch up the username in the change. If the same
1619 # client spec is being used by multiple processes then this might go
1621 results = p4CmdList("client -o") # find the current client
1625 client = r['Client']
1628 die("could not get client spec")
1629 results = p4CmdList(["changes", "-c", client, "-m", "1"])
1633 die("Could not get changelist number for last submit - cannot patch up user details")
1635 def modifyChangelistUser(self, changelist, newUser):
1636 # fixup the user field of a changelist after it has been submitted.
1637 changes = p4CmdList("change -o %s" % changelist)
1638 if len(changes) != 1:
1639 die("Bad output from p4 change modifying %s to user %s" %
1640 (changelist, newUser))
1643 if c['User'] == newUser: return # nothing to do
1645 input = marshal.dumps(c)
1647 result = p4CmdList("change -f -i", stdin=input)
1650 if r['code'] == 'error':
1651 die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
1653 print("Updated user field for changelist %s to %s" % (changelist, newUser))
1655 die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
1657 def canChangeChangelists(self):
1658 # check to see if we have p4 admin or super-user permissions, either of
1659 # which are required to modify changelists.
1660 results = p4CmdList(["protects", self.depotPath])
1663 if r['perm'] == 'admin':
1665 if r['perm'] == 'super':
1669 def prepareSubmitTemplate(self, changelist=None):
1670 """Run "p4 change -o" to grab a change specification template.
1671 This does not use "p4 -G", as it is nice to keep the submission
1672 template in original order, since a human might edit it.
1674 Remove lines in the Files section that show changes to files
1675 outside the depot path we're committing into."""
1677 [upstream, settings] = findUpstreamBranchPoint()
1680 # A Perforce Change Specification.
1682 # Change: The change number. 'new' on a new changelist.
1683 # Date: The date this specification was last modified.
1684 # Client: The client on which the changelist was created. Read-only.
1685 # User: The user who created the changelist.
1686 # Status: Either 'pending' or 'submitted'. Read-only.
1687 # Type: Either 'public' or 'restricted'. Default is 'public'.
1688 # Description: Comments about the changelist. Required.
1689 # Jobs: What opened jobs are to be closed by this changelist.
1690 # You may delete jobs from this list. (New changelists only.)
1691 # Files: What opened files from the default changelist are to be added
1692 # to this changelist. You may delete files from this list.
1693 # (New changelists only.)
1696 inFilesSection = False
1698 args = ['change', '-o']
1700 args.append(str(changelist))
1701 for entry in p4CmdList(args):
1702 if 'code' not in entry:
1704 if entry['code'] == 'stat':
1705 change_entry = entry
1707 if not change_entry:
1708 die('Failed to decode output of p4 change -o')
1709 for key, value in change_entry.iteritems():
1710 if key.startswith('File'):
1711 if 'depot-paths' in settings:
1712 if not [p for p in settings['depot-paths']
1713 if p4PathStartsWith(value, p)]:
1716 if not p4PathStartsWith(value, self.depotPath):
1718 files_list.append(value)
1720 # Output in the order expected by prepareLogMessage
1721 for key in ['Change', 'Client', 'User', 'Status', 'Description', 'Jobs']:
1722 if key not in change_entry:
1725 template += key + ':'
1726 if key == 'Description':
1728 for field_line in change_entry[key].splitlines():
1729 template += '\t'+field_line+'\n'
1730 if len(files_list) > 0:
1732 template += 'Files:\n'
1733 for path in files_list:
1734 template += '\t'+path+'\n'
1737 def edit_template(self, template_file):
1738 """Invoke the editor to let the user change the submission
1739 message. Return true if okay to continue with the submit."""
1741 # if configured to skip the editing part, just submit
1742 if gitConfigBool("git-p4.skipSubmitEdit"):
1745 # look at the modification time, to check later if the user saved
1747 mtime = os.stat(template_file).st_mtime
1750 if "P4EDITOR" in os.environ and (os.environ.get("P4EDITOR") != ""):
1751 editor = os.environ.get("P4EDITOR")
1753 editor = read_pipe("git var GIT_EDITOR").strip()
1754 system(["sh", "-c", ('%s "$@"' % editor), editor, template_file])
1756 # If the file was not saved, prompt to see if this patch should
1757 # be skipped. But skip this verification step if configured so.
1758 if gitConfigBool("git-p4.skipSubmitEditCheck"):
1761 # modification time updated means user saved the file
1762 if os.stat(template_file).st_mtime > mtime:
1766 response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
1772 def get_diff_description(self, editedFiles, filesToAdd, symlinks):
1774 if "P4DIFF" in os.environ:
1775 del(os.environ["P4DIFF"])
1777 for editedFile in editedFiles:
1778 diff += p4_read_pipe(['diff', '-du',
1779 wildcard_encode(editedFile)])
1783 for newFile in filesToAdd:
1784 newdiff += "==== new file ====\n"
1785 newdiff += "--- /dev/null\n"
1786 newdiff += "+++ %s\n" % newFile
1788 is_link = os.path.islink(newFile)
1789 expect_link = newFile in symlinks
1791 if is_link and expect_link:
1792 newdiff += "+%s\n" % os.readlink(newFile)
1794 f = open(newFile, "r")
1795 for line in f.readlines():
1796 newdiff += "+" + line
1799 return (diff + newdiff).replace('\r\n', '\n')
1801 def applyCommit(self, id):
1802 """Apply one commit, return True if it succeeded."""
1804 print("Applying", read_pipe(["git", "show", "-s",
1805 "--format=format:%h %s", id]))
1807 (p4User, gitEmail) = self.p4UserForCommit(id)
1809 diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
1811 filesToChangeType = set()
1812 filesToDelete = set()
1814 pureRenameCopy = set()
1816 filesToChangeExecBit = {}
1820 diff = parseDiffTreeEntry(line)
1821 modifier = diff['status']
1823 all_files.append(path)
1827 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1828 filesToChangeExecBit[path] = diff['dst_mode']
1829 editedFiles.add(path)
1830 elif modifier == "A":
1831 filesToAdd.add(path)
1832 filesToChangeExecBit[path] = diff['dst_mode']
1833 if path in filesToDelete:
1834 filesToDelete.remove(path)
1836 dst_mode = int(diff['dst_mode'], 8)
1837 if dst_mode == 0o120000:
1840 elif modifier == "D":
1841 filesToDelete.add(path)
1842 if path in filesToAdd:
1843 filesToAdd.remove(path)
1844 elif modifier == "C":
1845 src, dest = diff['src'], diff['dst']
1846 all_files.append(dest)
1847 p4_integrate(src, dest)
1848 pureRenameCopy.add(dest)
1849 if diff['src_sha1'] != diff['dst_sha1']:
1851 pureRenameCopy.discard(dest)
1852 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1854 pureRenameCopy.discard(dest)
1855 filesToChangeExecBit[dest] = diff['dst_mode']
1857 # turn off read-only attribute
1858 os.chmod(dest, stat.S_IWRITE)
1860 editedFiles.add(dest)
1861 elif modifier == "R":
1862 src, dest = diff['src'], diff['dst']
1863 all_files.append(dest)
1864 if self.p4HasMoveCommand:
1865 p4_edit(src) # src must be open before move
1866 p4_move(src, dest) # opens for (move/delete, move/add)
1868 p4_integrate(src, dest)
1869 if diff['src_sha1'] != diff['dst_sha1']:
1872 pureRenameCopy.add(dest)
1873 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1874 if not self.p4HasMoveCommand:
1875 p4_edit(dest) # with move: already open, writable
1876 filesToChangeExecBit[dest] = diff['dst_mode']
1877 if not self.p4HasMoveCommand:
1879 os.chmod(dest, stat.S_IWRITE)
1881 filesToDelete.add(src)
1882 editedFiles.add(dest)
1883 elif modifier == "T":
1884 filesToChangeType.add(path)
1886 die("unknown modifier %s for %s" % (modifier, path))
1888 diffcmd = "git diff-tree --full-index -p \"%s\"" % (id)
1889 patchcmd = diffcmd + " | git apply "
1890 tryPatchCmd = patchcmd + "--check -"
1891 applyPatchCmd = patchcmd + "--check --apply -"
1892 patch_succeeded = True
1894 if os.system(tryPatchCmd) != 0:
1895 fixed_rcs_keywords = False
1896 patch_succeeded = False
1897 print("Unfortunately applying the change failed!")
1899 # Patch failed, maybe it's just RCS keyword woes. Look through
1900 # the patch to see if that's possible.
1901 if gitConfigBool("git-p4.attemptRCSCleanup"):
1905 for file in editedFiles | filesToDelete:
1906 # did this file's delta contain RCS keywords?
1907 pattern = p4_keywords_regexp_for_file(file)
1910 # this file is a possibility...look for RCS keywords.
1911 regexp = re.compile(pattern, re.VERBOSE)
1912 for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
1913 if regexp.search(line):
1915 print("got keyword match on %s in %s in %s" % (pattern, line, file))
1916 kwfiles[file] = pattern
1919 for file in kwfiles:
1921 print("zapping %s with %s" % (line,pattern))
1922 # File is being deleted, so not open in p4. Must
1923 # disable the read-only bit on windows.
1924 if self.isWindows and file not in editedFiles:
1925 os.chmod(file, stat.S_IWRITE)
1926 self.patchRCSKeywords(file, kwfiles[file])
1927 fixed_rcs_keywords = True
1929 if fixed_rcs_keywords:
1930 print("Retrying the patch with RCS keywords cleaned up")
1931 if os.system(tryPatchCmd) == 0:
1932 patch_succeeded = True
1934 if not patch_succeeded:
1935 for f in editedFiles:
1940 # Apply the patch for real, and do add/delete/+x handling.
1942 system(applyPatchCmd)
1944 for f in filesToChangeType:
1945 p4_edit(f, "-t", "auto")
1946 for f in filesToAdd:
1948 for f in filesToDelete:
1952 # Set/clear executable bits
1953 for f in filesToChangeExecBit.keys():
1954 mode = filesToChangeExecBit[f]
1955 setP4ExecBit(f, mode)
1958 if len(self.update_shelve) > 0:
1959 update_shelve = self.update_shelve.pop(0)
1960 p4_reopen_in_change(update_shelve, all_files)
1963 # Build p4 change description, starting with the contents
1964 # of the git commit message.
1966 logMessage = extractLogMessageFromGitCommit(id)
1967 logMessage = logMessage.strip()
1968 (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
1970 template = self.prepareSubmitTemplate(update_shelve)
1971 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
1973 if self.preserveUser:
1974 submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
1976 if self.checkAuthorship and not self.p4UserIsMe(p4User):
1977 submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
1978 submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
1979 submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
1981 separatorLine = "######## everything below this line is just the diff #######\n"
1982 if not self.prepare_p4_only:
1983 submitTemplate += separatorLine
1984 submitTemplate += self.get_diff_description(editedFiles, filesToAdd, symlinks)
1986 (handle, fileName) = tempfile.mkstemp()
1987 tmpFile = os.fdopen(handle, "w+b")
1989 submitTemplate = submitTemplate.replace("\n", "\r\n")
1990 tmpFile.write(submitTemplate)
1993 if self.prepare_p4_only:
1995 # Leave the p4 tree prepared, and the submit template around
1996 # and let the user decide what to do next
1999 print("P4 workspace prepared for submission.")
2000 print("To submit or revert, go to client workspace")
2001 print(" " + self.clientPath)
2003 print("To submit, use \"p4 submit\" to write a new description,")
2004 print("or \"p4 submit -i <%s\" to use the one prepared by" \
2005 " \"git p4\"." % fileName)
2006 print("You can delete the file \"%s\" when finished." % fileName)
2008 if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
2009 print("To preserve change ownership by user %s, you must\n" \
2010 "do \"p4 change -f <change>\" after submitting and\n" \
2011 "edit the User field.")
2013 print("After submitting, renamed files must be re-synced.")
2014 print("Invoke \"p4 sync -f\" on each of these files:")
2015 for f in pureRenameCopy:
2019 print("To revert the changes, use \"p4 revert ...\", and delete")
2020 print("the submit template file \"%s\"" % fileName)
2022 print("Since the commit adds new files, they must be deleted:")
2023 for f in filesToAdd:
2029 # Let the user edit the change description, then submit it.
2034 if self.edit_template(fileName):
2035 # read the edited message and submit
2036 tmpFile = open(fileName, "rb")
2037 message = tmpFile.read()
2040 message = message.replace("\r\n", "\n")
2041 submitTemplate = message[:message.index(separatorLine)]
2044 p4_write_pipe(['shelve', '-r', '-i'], submitTemplate)
2046 p4_write_pipe(['shelve', '-i'], submitTemplate)
2048 p4_write_pipe(['submit', '-i'], submitTemplate)
2049 # The rename/copy happened by applying a patch that created a
2050 # new file. This leaves it writable, which confuses p4.
2051 for f in pureRenameCopy:
2054 if self.preserveUser:
2056 # Get last changelist number. Cannot easily get it from
2057 # the submit command output as the output is
2059 changelist = self.lastP4Changelist()
2060 self.modifyChangelistUser(changelist, p4User)
2066 if not submitted or self.shelve:
2068 print ("Reverting shelved files.")
2070 print ("Submission cancelled, undoing p4 changes.")
2071 for f in editedFiles | filesToDelete:
2073 for f in filesToAdd:
2080 # Export git tags as p4 labels. Create a p4 label and then tag
2082 def exportGitTags(self, gitTags):
2083 validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
2084 if len(validLabelRegexp) == 0:
2085 validLabelRegexp = defaultLabelRegexp
2086 m = re.compile(validLabelRegexp)
2088 for name in gitTags:
2090 if not m.match(name):
2092 print("tag %s does not match regexp %s" % (name, validLabelRegexp))
2095 # Get the p4 commit this corresponds to
2096 logMessage = extractLogMessageFromGitCommit(name)
2097 values = extractSettingsGitLog(logMessage)
2099 if 'change' not in values:
2100 # a tag pointing to something not sent to p4; ignore
2102 print("git tag %s does not give a p4 commit" % name)
2105 changelist = values['change']
2107 # Get the tag details.
2111 for l in read_pipe_lines(["git", "cat-file", "-p", name]):
2114 if re.match(r'tag\s+', l):
2116 elif re.match(r'\s*$', l):
2123 body = ["lightweight tag imported by git p4\n"]
2125 # Create the label - use the same view as the client spec we are using
2126 clientSpec = getClientSpec()
2128 labelTemplate = "Label: %s\n" % name
2129 labelTemplate += "Description:\n"
2131 labelTemplate += "\t" + b + "\n"
2132 labelTemplate += "View:\n"
2133 for depot_side in clientSpec.mappings:
2134 labelTemplate += "\t%s\n" % depot_side
2137 print("Would create p4 label %s for tag" % name)
2138 elif self.prepare_p4_only:
2139 print("Not creating p4 label %s for tag due to option" \
2140 " --prepare-p4-only" % name)
2142 p4_write_pipe(["label", "-i"], labelTemplate)
2145 p4_system(["tag", "-l", name] +
2146 ["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings])
2149 print("created p4 label for tag %s" % name)
2151 def run(self, args):
2153 self.master = currentGitBranch()
2154 elif len(args) == 1:
2155 self.master = args[0]
2156 if not branchExists(self.master):
2157 die("Branch %s does not exist" % self.master)
2161 for i in self.update_shelve:
2163 sys.exit("invalid changelist %d" % i)
2166 allowSubmit = gitConfig("git-p4.allowSubmit")
2167 if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
2168 die("%s is not in git-p4.allowSubmit" % self.master)
2170 [upstream, settings] = findUpstreamBranchPoint()
2171 self.depotPath = settings['depot-paths'][0]
2172 if len(self.origin) == 0:
2173 self.origin = upstream
2175 if len(self.update_shelve) > 0:
2178 if self.preserveUser:
2179 if not self.canChangeChangelists():
2180 die("Cannot preserve user names without p4 super-user or admin permissions")
2182 # if not set from the command line, try the config file
2183 if self.conflict_behavior is None:
2184 val = gitConfig("git-p4.conflict")
2186 if val not in self.conflict_behavior_choices:
2187 die("Invalid value '%s' for config git-p4.conflict" % val)
2190 self.conflict_behavior = val
2193 print("Origin branch is " + self.origin)
2195 if len(self.depotPath) == 0:
2196 print("Internal error: cannot locate perforce depot path from existing branches")
2199 self.useClientSpec = False
2200 if gitConfigBool("git-p4.useclientspec"):
2201 self.useClientSpec = True
2202 if self.useClientSpec:
2203 self.clientSpecDirs = getClientSpec()
2205 # Check for the existence of P4 branches
2206 branchesDetected = (len(p4BranchesInGit().keys()) > 1)
2208 if self.useClientSpec and not branchesDetected:
2209 # all files are relative to the client spec
2210 self.clientPath = getClientRoot()
2212 self.clientPath = p4Where(self.depotPath)
2214 if self.clientPath == "":
2215 die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
2217 print("Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath))
2218 self.oldWorkingDirectory = os.getcwd()
2220 # ensure the clientPath exists
2221 new_client_dir = False
2222 if not os.path.exists(self.clientPath):
2223 new_client_dir = True
2224 os.makedirs(self.clientPath)
2226 chdir(self.clientPath, is_client_path=True)
2228 print("Would synchronize p4 checkout in %s" % self.clientPath)
2230 print("Synchronizing p4 checkout...")
2232 # old one was destroyed, and maybe nobody told p4
2233 p4_sync("...", "-f")
2240 committish = self.master
2244 if self.commit != "":
2245 if self.commit.find("..") != -1:
2246 limits_ish = self.commit.split("..")
2247 for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (limits_ish[0], limits_ish[1])]):
2248 commits.append(line.strip())
2251 commits.append(self.commit)
2253 for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, committish)]):
2254 commits.append(line.strip())
2257 if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"):
2258 self.checkAuthorship = False
2260 self.checkAuthorship = True
2262 if self.preserveUser:
2263 self.checkValidP4Users(commits)
2266 # Build up a set of options to be passed to diff when
2267 # submitting each commit to p4.
2269 if self.detectRenames:
2270 # command-line -M arg
2271 self.diffOpts = "-M"
2273 # If not explicitly set check the config variable
2274 detectRenames = gitConfig("git-p4.detectRenames")
2276 if detectRenames.lower() == "false" or detectRenames == "":
2278 elif detectRenames.lower() == "true":
2279 self.diffOpts = "-M"
2281 self.diffOpts = "-M%s" % detectRenames
2283 # no command-line arg for -C or --find-copies-harder, just
2285 detectCopies = gitConfig("git-p4.detectCopies")
2286 if detectCopies.lower() == "false" or detectCopies == "":
2288 elif detectCopies.lower() == "true":
2289 self.diffOpts += " -C"
2291 self.diffOpts += " -C%s" % detectCopies
2293 if gitConfigBool("git-p4.detectCopiesHarder"):
2294 self.diffOpts += " --find-copies-harder"
2296 num_shelves = len(self.update_shelve)
2297 if num_shelves > 0 and num_shelves != len(commits):
2298 sys.exit("number of commits (%d) must match number of shelved changelist (%d)" %
2299 (len(commits), num_shelves))
2301 hooks_path = gitConfig("core.hooksPath")
2302 if len(hooks_path) <= 0:
2303 hooks_path = os.path.join(os.environ.get("GIT_DIR", ".git"), "hooks")
2305 hook_file = os.path.join(hooks_path, "p4-pre-submit")
2306 if os.path.isfile(hook_file) and os.access(hook_file, os.X_OK) and subprocess.call([hook_file]) != 0:
2310 # Apply the commits, one at a time. On failure, ask if should
2311 # continue to try the rest of the patches, or quit.
2314 print("Would apply")
2316 last = len(commits) - 1
2317 for i, commit in enumerate(commits):
2319 print(" ", read_pipe(["git", "show", "-s",
2320 "--format=format:%h %s", commit]))
2323 ok = self.applyCommit(commit)
2325 applied.append(commit)
2327 if self.prepare_p4_only and i < last:
2328 print("Processing only the first commit due to option" \
2329 " --prepare-p4-only")
2334 # prompt for what to do, or use the option/variable
2335 if self.conflict_behavior == "ask":
2336 print("What do you want to do?")
2337 response = raw_input("[s]kip this commit but apply"
2338 " the rest, or [q]uit? ")
2341 elif self.conflict_behavior == "skip":
2343 elif self.conflict_behavior == "quit":
2346 die("Unknown conflict_behavior '%s'" %
2347 self.conflict_behavior)
2349 if response[0] == "s":
2350 print("Skipping this commit, but applying the rest")
2352 if response[0] == "q":
2359 chdir(self.oldWorkingDirectory)
2360 shelved_applied = "shelved" if self.shelve else "applied"
2363 elif self.prepare_p4_only:
2365 elif len(commits) == len(applied):
2366 print("All commits {0}!".format(shelved_applied))
2370 sync.branch = self.branch
2371 if self.disable_p4sync:
2372 sync.sync_origin_only()
2376 if not self.disable_rebase:
2381 if len(applied) == 0:
2382 print("No commits {0}.".format(shelved_applied))
2384 print("{0} only the commits marked with '*':".format(shelved_applied.capitalize()))
2390 print(star, read_pipe(["git", "show", "-s",
2391 "--format=format:%h %s", c]))
2392 print("You will have to do 'git p4 sync' and rebase.")
2394 if gitConfigBool("git-p4.exportLabels"):
2395 self.exportLabels = True
2397 if self.exportLabels:
2398 p4Labels = getP4Labels(self.depotPath)
2399 gitTags = getGitTags()
2401 missingGitTags = gitTags - p4Labels
2402 self.exportGitTags(missingGitTags)
2404 # exit with error unless everything applied perfectly
2405 if len(commits) != len(applied):
2411 """Represent a p4 view ("p4 help views"), and map files in a
2412 repo according to the view."""
2414 def __init__(self, client_name):
2416 self.client_prefix = "//%s/" % client_name
2417 # cache results of "p4 where" to lookup client file locations
2418 self.client_spec_path_cache = {}
2420 def append(self, view_line):
2421 """Parse a view line, splitting it into depot and client
2422 sides. Append to self.mappings, preserving order. This
2423 is only needed for tag creation."""
2425 # Split the view line into exactly two words. P4 enforces
2426 # structure on these lines that simplifies this quite a bit.
2428 # Either or both words may be double-quoted.
2429 # Single quotes do not matter.
2430 # Double-quote marks cannot occur inside the words.
2431 # A + or - prefix is also inside the quotes.
2432 # There are no quotes unless they contain a space.
2433 # The line is already white-space stripped.
2434 # The two words are separated by a single space.
2436 if view_line[0] == '"':
2437 # First word is double quoted. Find its end.
2438 close_quote_index = view_line.find('"', 1)
2439 if close_quote_index <= 0:
2440 die("No first-word closing quote found: %s" % view_line)
2441 depot_side = view_line[1:close_quote_index]
2442 # skip closing quote and space
2443 rhs_index = close_quote_index + 1 + 1
2445 space_index = view_line.find(" ")
2446 if space_index <= 0:
2447 die("No word-splitting space found: %s" % view_line)
2448 depot_side = view_line[0:space_index]
2449 rhs_index = space_index + 1
2451 # prefix + means overlay on previous mapping
2452 if depot_side.startswith("+"):
2453 depot_side = depot_side[1:]
2455 # prefix - means exclude this path, leave out of mappings
2457 if depot_side.startswith("-"):
2459 depot_side = depot_side[1:]
2462 self.mappings.append(depot_side)
2464 def convert_client_path(self, clientFile):
2465 # chop off //client/ part to make it relative
2466 if not clientFile.startswith(self.client_prefix):
2467 die("No prefix '%s' on clientFile '%s'" %
2468 (self.client_prefix, clientFile))
2469 return clientFile[len(self.client_prefix):]
2471 def update_client_spec_path_cache(self, files):
2472 """ Caching file paths by "p4 where" batch query """
2474 # List depot file paths exclude that already cached
2475 fileArgs = [f['path'] for f in files if f['path'] not in self.client_spec_path_cache]
2477 if len(fileArgs) == 0:
2478 return # All files in cache
2480 where_result = p4CmdList(["-x", "-", "where"], stdin=fileArgs)
2481 for res in where_result:
2482 if "code" in res and res["code"] == "error":
2483 # assume error is "... file(s) not in client view"
2485 if "clientFile" not in res:
2486 die("No clientFile in 'p4 where' output")
2488 # it will list all of them, but only one not unmap-ped
2490 if gitConfigBool("core.ignorecase"):
2491 res['depotFile'] = res['depotFile'].lower()
2492 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])
2494 # not found files or unmap files set to ""
2495 for depotFile in fileArgs:
2496 if gitConfigBool("core.ignorecase"):
2497 depotFile = depotFile.lower()
2498 if depotFile not in self.client_spec_path_cache:
2499 self.client_spec_path_cache[depotFile] = ""
2501 def map_in_client(self, depot_path):
2502 """Return the relative location in the client where this
2503 depot file should live. Returns "" if the file should
2504 not be mapped in the client."""
2506 if gitConfigBool("core.ignorecase"):
2507 depot_path = depot_path.lower()
2509 if depot_path in self.client_spec_path_cache:
2510 return self.client_spec_path_cache[depot_path]
2512 die( "Error: %s is not found in client spec path" % depot_path )
2515 def cloneExcludeCallback(option, opt_str, value, parser):
2516 # prepend "/" because the first "/" was consumed as part of the option itself.
2517 # ("-//depot/A/..." becomes "/depot/A/..." after option parsing)
2518 parser.values.cloneExclude += ["/" + re.sub(r"\.\.\.$", "", value)]
2520 class P4Sync(Command, P4UserMap):
2523 Command.__init__(self)
2524 P4UserMap.__init__(self)
2526 optparse.make_option("--branch", dest="branch"),
2527 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
2528 optparse.make_option("--changesfile", dest="changesFile"),
2529 optparse.make_option("--silent", dest="silent", action="store_true"),
2530 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
2531 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
2532 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
2533 help="Import into refs/heads/ , not refs/remotes"),
2534 optparse.make_option("--max-changes", dest="maxChanges",
2535 help="Maximum number of changes to import"),
2536 optparse.make_option("--changes-block-size", dest="changes_block_size", type="int",
2537 help="Internal block size to use when iteratively calling p4 changes"),
2538 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
2539 help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
2540 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
2541 help="Only sync files that are included in the Perforce Client Spec"),
2542 optparse.make_option("-/", dest="cloneExclude",
2543 action="callback", callback=cloneExcludeCallback, type="string",
2544 help="exclude depot path"),
2546 self.description = """Imports from Perforce into a git repository.\n
2548 //depot/my/project/ -- to import the current head
2549 //depot/my/project/@all -- to import everything
2550 //depot/my/project/@1,6 -- to import only from revision 1 to 6
2552 (a ... is not needed in the path p4 specification, it's added implicitly)"""
2554 self.usage += " //depot/path[@revRange]"
2556 self.createdBranches = set()
2557 self.committedChanges = set()
2559 self.detectBranches = False
2560 self.detectLabels = False
2561 self.importLabels = False
2562 self.changesFile = ""
2563 self.syncWithOrigin = True
2564 self.importIntoRemotes = True
2565 self.maxChanges = ""
2566 self.changes_block_size = None
2567 self.keepRepoPath = False
2568 self.depotPaths = None
2569 self.p4BranchesInGit = []
2570 self.cloneExclude = []
2571 self.useClientSpec = False
2572 self.useClientSpec_from_options = False
2573 self.clientSpecDirs = None
2574 self.tempBranches = []
2575 self.tempBranchLocation = "refs/git-p4-tmp"
2576 self.largeFileSystem = None
2577 self.suppress_meta_comment = False
2579 if gitConfig('git-p4.largeFileSystem'):
2580 largeFileSystemConstructor = globals()[gitConfig('git-p4.largeFileSystem')]
2581 self.largeFileSystem = largeFileSystemConstructor(
2582 lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)
2585 if gitConfig("git-p4.syncFromOrigin") == "false":
2586 self.syncWithOrigin = False
2588 self.depotPaths = []
2589 self.changeRange = ""
2590 self.previousDepotPaths = []
2591 self.hasOrigin = False
2593 # map from branch depot path to parent branch
2594 self.knownBranches = {}
2595 self.initialParents = {}
2597 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
2600 # Force a checkpoint in fast-import and wait for it to finish
2601 def checkpoint(self):
2602 self.gitStream.write("checkpoint\n\n")
2603 self.gitStream.write("progress checkpoint\n\n")
2604 out = self.gitOutput.readline()
2606 print("checkpoint finished: " + out)
2608 def isPathWanted(self, path):
2609 for p in self.cloneExclude:
2611 if p4PathStartsWith(path, p):
2613 # "-//depot/file1" without a trailing "/" should only exclude "file1", but not "file111" or "file1_dir/file2"
2614 elif path.lower() == p.lower():
2616 for p in self.depotPaths:
2617 if p4PathStartsWith(path, p):
2621 def extractFilesFromCommit(self, commit, shelved=False, shelved_cl = 0):
2624 while "depotFile%s" % fnum in commit:
2625 path = commit["depotFile%s" % fnum]
2626 found = self.isPathWanted(path)
2633 file["rev"] = commit["rev%s" % fnum]
2634 file["action"] = commit["action%s" % fnum]
2635 file["type"] = commit["type%s" % fnum]
2637 file["shelved_cl"] = int(shelved_cl)
2642 def extractJobsFromCommit(self, commit):
2645 while "job%s" % jnum in commit:
2646 job = commit["job%s" % jnum]
2651 def stripRepoPath(self, path, prefixes):
2652 """When streaming files, this is called to map a p4 depot path
2653 to where it should go in git. The prefixes are either
2654 self.depotPaths, or self.branchPrefixes in the case of
2655 branch detection."""
2657 if self.useClientSpec:
2658 # branch detection moves files up a level (the branch name)
2659 # from what client spec interpretation gives
2660 path = self.clientSpecDirs.map_in_client(path)
2661 if self.detectBranches:
2662 for b in self.knownBranches:
2663 if p4PathStartsWith(path, b + "/"):
2664 path = path[len(b)+1:]
2666 elif self.keepRepoPath:
2667 # Preserve everything in relative path name except leading
2668 # //depot/; just look at first prefix as they all should
2669 # be in the same depot.
2670 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])
2671 if p4PathStartsWith(path, depot):
2672 path = path[len(depot):]
2676 if p4PathStartsWith(path, p):
2677 path = path[len(p):]
2680 path = wildcard_decode(path)
2683 def splitFilesIntoBranches(self, commit):
2684 """Look at each depotFile in the commit to figure out to what
2685 branch it belongs."""
2687 if self.clientSpecDirs:
2688 files = self.extractFilesFromCommit(commit)
2689 self.clientSpecDirs.update_client_spec_path_cache(files)
2693 while "depotFile%s" % fnum in commit:
2694 path = commit["depotFile%s" % fnum]
2695 found = self.isPathWanted(path)
2702 file["rev"] = commit["rev%s" % fnum]
2703 file["action"] = commit["action%s" % fnum]
2704 file["type"] = commit["type%s" % fnum]
2707 # start with the full relative path where this file would
2709 if self.useClientSpec:
2710 relPath = self.clientSpecDirs.map_in_client(path)
2712 relPath = self.stripRepoPath(path, self.depotPaths)
2714 for branch in self.knownBranches.keys():
2715 # add a trailing slash so that a commit into qt/4.2foo
2716 # doesn't end up in qt/4.2, e.g.
2717 if p4PathStartsWith(relPath, branch + "/"):
2718 if branch not in branches:
2719 branches[branch] = []
2720 branches[branch].append(file)
2725 def writeToGitStream(self, gitMode, relPath, contents):
2726 self.gitStream.write('M %s inline %s\n' % (gitMode, relPath))
2727 self.gitStream.write('data %d\n' % sum(len(d) for d in contents))
2729 self.gitStream.write(d)
2730 self.gitStream.write('\n')
2732 def encodeWithUTF8(self, path):
2734 path.decode('ascii')
2737 if gitConfig('git-p4.pathEncoding'):
2738 encoding = gitConfig('git-p4.pathEncoding')
2739 path = path.decode(encoding, 'replace').encode('utf8', 'replace')
2741 print('Path with non-ASCII characters detected. Used %s to encode: %s ' % (encoding, path))
2744 # output one file from the P4 stream
2745 # - helper for streamP4Files
2747 def streamOneP4File(self, file, contents):
2748 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
2749 relPath = self.encodeWithUTF8(relPath)
2751 if 'fileSize' in self.stream_file:
2752 size = int(self.stream_file['fileSize'])
2754 size = 0 # deleted files don't get a fileSize apparently
2755 sys.stdout.write('\r%s --> %s (%i MB)\n' % (file['depotFile'], relPath, size/1024/1024))
2758 (type_base, type_mods) = split_p4_type(file["type"])
2761 if "x" in type_mods:
2763 if type_base == "symlink":
2765 # p4 print on a symlink sometimes contains "target\n";
2766 # if it does, remove the newline
2767 data = ''.join(contents)
2769 # Some version of p4 allowed creating a symlink that pointed
2770 # to nothing. This causes p4 errors when checking out such
2771 # a change, and errors here too. Work around it by ignoring
2772 # the bad symlink; hopefully a future change fixes it.
2773 print("\nIgnoring empty symlink in %s" % file['depotFile'])
2775 elif data[-1] == '\n':
2776 contents = [data[:-1]]
2780 if type_base == "utf16":
2781 # p4 delivers different text in the python output to -G
2782 # than it does when using "print -o", or normal p4 client
2783 # operations. utf16 is converted to ascii or utf8, perhaps.
2784 # But ascii text saved as -t utf16 is completely mangled.
2785 # Invoke print -o to get the real contents.
2787 # On windows, the newlines will always be mangled by print, so put
2788 # them back too. This is not needed to the cygwin windows version,
2789 # just the native "NT" type.
2792 text = p4_read_pipe(['print', '-q', '-o', '-', '%s@%s' % (file['depotFile'], file['change'])])
2793 except Exception as e:
2794 if 'Translation of file content failed' in str(e):
2795 type_base = 'binary'
2799 if p4_version_string().find('/NT') >= 0:
2800 text = text.replace('\r\n', '\n')
2803 if type_base == "apple":
2804 # Apple filetype files will be streamed as a concatenation of
2805 # its appledouble header and the contents. This is useless
2806 # on both macs and non-macs. If using "print -q -o xx", it
2807 # will create "xx" with the data, and "%xx" with the header.
2808 # This is also not very useful.
2810 # Ideally, someday, this script can learn how to generate
2811 # appledouble files directly and import those to git, but
2812 # non-mac machines can never find a use for apple filetype.
2813 print("\nIgnoring apple filetype file %s" % file['depotFile'])
2816 # Note that we do not try to de-mangle keywords on utf16 files,
2817 # even though in theory somebody may want that.
2818 pattern = p4_keywords_regexp_for_type(type_base, type_mods)
2820 regexp = re.compile(pattern, re.VERBOSE)
2821 text = ''.join(contents)
2822 text = regexp.sub(r'$\1$', text)
2825 if self.largeFileSystem:
2826 (git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)
2828 self.writeToGitStream(git_mode, relPath, contents)
2830 def streamOneP4Deletion(self, file):
2831 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
2832 relPath = self.encodeWithUTF8(relPath)
2834 sys.stdout.write("delete %s\n" % relPath)
2836 self.gitStream.write("D %s\n" % relPath)
2838 if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):
2839 self.largeFileSystem.removeLargeFile(relPath)
2841 # handle another chunk of streaming data
2842 def streamP4FilesCb(self, marshalled):
2844 # catch p4 errors and complain
2846 if "code" in marshalled:
2847 if marshalled["code"] == "error":
2848 if "data" in marshalled:
2849 err = marshalled["data"].rstrip()
2851 if not err and 'fileSize' in self.stream_file:
2852 required_bytes = int((4 * int(self.stream_file["fileSize"])) - calcDiskFree())
2853 if required_bytes > 0:
2854 err = 'Not enough space left on %s! Free at least %i MB.' % (
2855 os.getcwd(), required_bytes/1024/1024
2860 if self.stream_have_file_info:
2861 if "depotFile" in self.stream_file:
2862 f = self.stream_file["depotFile"]
2863 # force a failure in fast-import, else an empty
2864 # commit will be made
2865 self.gitStream.write("\n")
2866 self.gitStream.write("die-now\n")
2867 self.gitStream.close()
2868 # ignore errors, but make sure it exits first
2869 self.importProcess.wait()
2871 die("Error from p4 print for %s: %s" % (f, err))
2873 die("Error from p4 print: %s" % err)
2875 if 'depotFile' in marshalled and self.stream_have_file_info:
2876 # start of a new file - output the old one first
2877 self.streamOneP4File(self.stream_file, self.stream_contents)
2878 self.stream_file = {}
2879 self.stream_contents = []
2880 self.stream_have_file_info = False
2882 # pick up the new file information... for the
2883 # 'data' field we need to append to our array
2884 for k in marshalled.keys():
2886 if 'streamContentSize' not in self.stream_file:
2887 self.stream_file['streamContentSize'] = 0
2888 self.stream_file['streamContentSize'] += len(marshalled['data'])
2889 self.stream_contents.append(marshalled['data'])
2891 self.stream_file[k] = marshalled[k]
2894 'streamContentSize' in self.stream_file and
2895 'fileSize' in self.stream_file and
2896 'depotFile' in self.stream_file):
2897 size = int(self.stream_file["fileSize"])
2899 progress = 100*self.stream_file['streamContentSize']/size
2900 sys.stdout.write('\r%s %d%% (%i MB)' % (self.stream_file['depotFile'], progress, int(size/1024/1024)))
2903 self.stream_have_file_info = True
2905 # Stream directly from "p4 files" into "git fast-import"
2906 def streamP4Files(self, files):
2912 filesForCommit.append(f)
2913 if f['action'] in self.delete_actions:
2914 filesToDelete.append(f)
2916 filesToRead.append(f)
2919 for f in filesToDelete:
2920 self.streamOneP4Deletion(f)
2922 if len(filesToRead) > 0:
2923 self.stream_file = {}
2924 self.stream_contents = []
2925 self.stream_have_file_info = False
2927 # curry self argument
2928 def streamP4FilesCbSelf(entry):
2929 self.streamP4FilesCb(entry)
2932 for f in filesToRead:
2933 if 'shelved_cl' in f:
2934 # Handle shelved CLs using the "p4 print file@=N" syntax to print
2936 fileArg = '%s@=%d' % (f['path'], f['shelved_cl'])
2938 fileArg = '%s#%s' % (f['path'], f['rev'])
2940 fileArgs.append(fileArg)
2942 p4CmdList(["-x", "-", "print"],
2944 cb=streamP4FilesCbSelf)
2947 if 'depotFile' in self.stream_file:
2948 self.streamOneP4File(self.stream_file, self.stream_contents)
2950 def make_email(self, userid):
2951 if userid in self.users:
2952 return self.users[userid]
2954 return "%s <a@b>" % userid
2956 def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
2957 """ Stream a p4 tag.
2958 commit is either a git commit, or a fast-import mark, ":<p4commit>"
2962 print("writing tag %s for commit %s" % (labelName, commit))
2963 gitStream.write("tag %s\n" % labelName)
2964 gitStream.write("from %s\n" % commit)
2966 if 'Owner' in labelDetails:
2967 owner = labelDetails["Owner"]
2971 # Try to use the owner of the p4 label, or failing that,
2972 # the current p4 user id.
2974 email = self.make_email(owner)
2976 email = self.make_email(self.p4UserId())
2977 tagger = "%s %s %s" % (email, epoch, self.tz)
2979 gitStream.write("tagger %s\n" % tagger)
2981 print("labelDetails=",labelDetails)
2982 if 'Description' in labelDetails:
2983 description = labelDetails['Description']
2985 description = 'Label from git p4'
2987 gitStream.write("data %d\n" % len(description))
2988 gitStream.write(description)
2989 gitStream.write("\n")
2991 def inClientSpec(self, path):
2992 if not self.clientSpecDirs:
2994 inClientSpec = self.clientSpecDirs.map_in_client(path)
2995 if not inClientSpec and self.verbose:
2996 print('Ignoring file outside of client spec: {0}'.format(path))
2999 def hasBranchPrefix(self, path):
3000 if not self.branchPrefixes:
3002 hasPrefix = [p for p in self.branchPrefixes
3003 if p4PathStartsWith(path, p)]
3004 if not hasPrefix and self.verbose:
3005 print('Ignoring file outside of prefix: {0}'.format(path))
3008 def commit(self, details, files, branch, parent = "", allow_empty=False):
3009 epoch = details["time"]
3010 author = details["user"]
3011 jobs = self.extractJobsFromCommit(details)
3014 print('commit into {0}'.format(branch))
3016 if self.clientSpecDirs:
3017 self.clientSpecDirs.update_client_spec_path_cache(files)
3019 files = [f for f in files
3020 if self.inClientSpec(f['path']) and self.hasBranchPrefix(f['path'])]
3022 if gitConfigBool('git-p4.keepEmptyCommits'):
3025 if not files and not allow_empty:
3026 print('Ignoring revision {0} as it would produce an empty commit.'
3027 .format(details['change']))
3030 self.gitStream.write("commit %s\n" % branch)
3031 self.gitStream.write("mark :%s\n" % details["change"])
3032 self.committedChanges.add(int(details["change"]))
3034 if author not in self.users:
3035 self.getUserMapFromPerforceServer()
3036 committer = "%s %s %s" % (self.make_email(author), epoch, self.tz)
3038 self.gitStream.write("committer %s\n" % committer)
3040 self.gitStream.write("data <<EOT\n")
3041 self.gitStream.write(details["desc"])
3043 self.gitStream.write("\nJobs: %s" % (' '.join(jobs)))
3045 if not self.suppress_meta_comment:
3046 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" %
3047 (','.join(self.branchPrefixes), details["change"]))
3048 if len(details['options']) > 0:
3049 self.gitStream.write(": options = %s" % details['options'])
3050 self.gitStream.write("]\n")
3052 self.gitStream.write("EOT\n\n")
3056 print("parent %s" % parent)
3057 self.gitStream.write("from %s\n" % parent)
3059 self.streamP4Files(files)
3060 self.gitStream.write("\n")
3062 change = int(details["change"])
3064 if change in self.labels:
3065 label = self.labels[change]
3066 labelDetails = label[0]
3067 labelRevisions = label[1]
3069 print("Change %s is labelled %s" % (change, labelDetails))
3071 files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
3072 for p in self.branchPrefixes])
3074 if len(files) == len(labelRevisions):
3078 if info["action"] in self.delete_actions:
3080 cleanedFiles[info["depotFile"]] = info["rev"]
3082 if cleanedFiles == labelRevisions:
3083 self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
3087 print("Tag %s does not match with change %s: files do not match."
3088 % (labelDetails["label"], change))
3092 print("Tag %s does not match with change %s: file count is different."
3093 % (labelDetails["label"], change))
3095 # Build a dictionary of changelists and labels, for "detect-labels" option.
3096 def getLabels(self):
3099 l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
3100 if len(l) > 0 and not self.silent:
3101 print("Finding files belonging to labels in %s" % self.depotPaths)
3104 label = output["label"]
3108 print("Querying files for label %s" % label)
3109 for file in p4CmdList(["files"] +
3110 ["%s...@%s" % (p, label)
3111 for p in self.depotPaths]):
3112 revisions[file["depotFile"]] = file["rev"]
3113 change = int(file["change"])
3114 if change > newestChange:
3115 newestChange = change
3117 self.labels[newestChange] = [output, revisions]
3120 print("Label changes: %s" % self.labels.keys())
3122 # Import p4 labels as git tags. A direct mapping does not
3123 # exist, so assume that if all the files are at the same revision
3124 # then we can use that, or it's something more complicated we should
3126 def importP4Labels(self, stream, p4Labels):
3128 print("import p4 labels: " + ' '.join(p4Labels))
3130 ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
3131 validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
3132 if len(validLabelRegexp) == 0:
3133 validLabelRegexp = defaultLabelRegexp
3134 m = re.compile(validLabelRegexp)
3136 for name in p4Labels:
3139 if not m.match(name):
3141 print("label %s does not match regexp %s" % (name,validLabelRegexp))
3144 if name in ignoredP4Labels:
3147 labelDetails = p4CmdList(['label', "-o", name])[0]
3149 # get the most recent changelist for each file in this label
3150 change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name)
3151 for p in self.depotPaths])
3153 if 'change' in change:
3154 # find the corresponding git commit; take the oldest commit
3155 changelist = int(change['change'])
3156 if changelist in self.committedChanges:
3157 gitCommit = ":%d" % changelist # use a fast-import mark
3160 gitCommit = read_pipe(["git", "rev-list", "--max-count=1",
3161 "--reverse", ":/\[git-p4:.*change = %d\]" % changelist], ignore_error=True)
3162 if len(gitCommit) == 0:
3163 print("importing label %s: could not find git commit for changelist %d" % (name, changelist))
3166 gitCommit = gitCommit.strip()
3169 # Convert from p4 time format
3171 tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
3173 print("Could not convert label time %s" % labelDetails['Update'])
3176 when = int(time.mktime(tmwhen))
3177 self.streamTag(stream, name, labelDetails, gitCommit, when)
3179 print("p4 label %s mapped to git commit %s" % (name, gitCommit))
3182 print("Label %s has no changelists - possibly deleted?" % name)
3185 # We can't import this label; don't try again as it will get very
3186 # expensive repeatedly fetching all the files for labels that will
3187 # never be imported. If the label is moved in the future, the
3188 # ignore will need to be removed manually.
3189 system(["git", "config", "--add", "git-p4.ignoredP4Labels", name])
3191 def guessProjectName(self):
3192 for p in self.depotPaths:
3195 p = p[p.strip().rfind("/") + 1:]
3196 if not p.endswith("/"):
3200 def getBranchMapping(self):
3201 lostAndFoundBranches = set()
3203 user = gitConfig("git-p4.branchUser")
3205 command = "branches -u %s" % user
3207 command = "branches"
3209 for info in p4CmdList(command):
3210 details = p4Cmd(["branch", "-o", info["branch"]])
3212 while "View%s" % viewIdx in details:
3213 paths = details["View%s" % viewIdx].split(" ")
3214 viewIdx = viewIdx + 1
3215 # require standard //depot/foo/... //depot/bar/... mapping
3216 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
3219 destination = paths[1]
3221 if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
3222 source = source[len(self.depotPaths[0]):-4]
3223 destination = destination[len(self.depotPaths[0]):-4]
3225 if destination in self.knownBranches:
3227 print("p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination))
3228 print("but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination))
3231 self.knownBranches[destination] = source
3233 lostAndFoundBranches.discard(destination)
3235 if source not in self.knownBranches:
3236 lostAndFoundBranches.add(source)
3238 # Perforce does not strictly require branches to be defined, so we also
3239 # check git config for a branch list.
3241 # Example of branch definition in git config file:
3243 # branchList=main:branchA
3244 # branchList=main:branchB
3245 # branchList=branchA:branchC
3246 configBranches = gitConfigList("git-p4.branchList")
3247 for branch in configBranches:
3249 (source, destination) = branch.split(":")
3250 self.knownBranches[destination] = source
3252 lostAndFoundBranches.discard(destination)
3254 if source not in self.knownBranches:
3255 lostAndFoundBranches.add(source)
3258 for branch in lostAndFoundBranches:
3259 self.knownBranches[branch] = branch
3261 def getBranchMappingFromGitBranches(self):
3262 branches = p4BranchesInGit(self.importIntoRemotes)
3263 for branch in branches.keys():
3264 if branch == "master":
3267 branch = branch[len(self.projectName):]
3268 self.knownBranches[branch] = branch
3270 def updateOptionDict(self, d):
3272 if self.keepRepoPath:
3273 option_keys['keepRepoPath'] = 1
3275 d["options"] = ' '.join(sorted(option_keys.keys()))
3277 def readOptions(self, d):
3278 self.keepRepoPath = ('options' in d
3279 and ('keepRepoPath' in d['options']))
3281 def gitRefForBranch(self, branch):
3282 if branch == "main":
3283 return self.refPrefix + "master"
3285 if len(branch) <= 0:
3288 return self.refPrefix + self.projectName + branch
3290 def gitCommitByP4Change(self, ref, change):
3292 print("looking in ref " + ref + " for change %s using bisect..." % change)
3295 latestCommit = parseRevision(ref)
3299 print("trying: earliest %s latest %s" % (earliestCommit, latestCommit))
3300 next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
3305 log = extractLogMessageFromGitCommit(next)
3306 settings = extractSettingsGitLog(log)
3307 currentChange = int(settings['change'])
3309 print("current change %s" % currentChange)
3311 if currentChange == change:
3313 print("found %s" % next)
3316 if currentChange < change:
3317 earliestCommit = "^%s" % next
3319 if next == latestCommit:
3320 die("Infinite loop while looking in ref %s for change %s. Check your branch mappings" % (ref, change))
3321 latestCommit = "%s^@" % next
3325 def importNewBranch(self, branch, maxChange):
3326 # make fast-import flush all changes to disk and update the refs using the checkpoint
3327 # command so that we can try to find the branch parent in the git history
3328 self.gitStream.write("checkpoint\n\n");
3329 self.gitStream.flush();
3330 branchPrefix = self.depotPaths[0] + branch + "/"
3331 range = "@1,%s" % maxChange
3332 #print "prefix" + branchPrefix
3333 changes = p4ChangesForPaths([branchPrefix], range, self.changes_block_size)
3334 if len(changes) <= 0:
3336 firstChange = changes[0]
3337 #print "first change in branch: %s" % firstChange
3338 sourceBranch = self.knownBranches[branch]
3339 sourceDepotPath = self.depotPaths[0] + sourceBranch
3340 sourceRef = self.gitRefForBranch(sourceBranch)
3341 #print "source " + sourceBranch
3343 branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
3344 #print "branch parent: %s" % branchParentChange
3345 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
3346 if len(gitParent) > 0:
3347 self.initialParents[self.gitRefForBranch(branch)] = gitParent
3348 #print "parent git commit: %s" % gitParent
3350 self.importChanges(changes)
3353 def searchParent(self, parent, branch, target):
3355 for blob in read_pipe_lines(["git", "rev-list", "--reverse",
3356 "--no-merges", parent]):
3358 if len(read_pipe(["git", "diff-tree", blob, target])) == 0:
3361 print("Found parent of %s in commit %s" % (branch, blob))
3368 def importChanges(self, changes, origin_revision=0):
3370 for change in changes:
3371 description = p4_describe(change)
3372 self.updateOptionDict(description)
3375 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
3380 if self.detectBranches:
3381 branches = self.splitFilesIntoBranches(description)
3382 for branch in branches.keys():
3384 branchPrefix = self.depotPaths[0] + branch + "/"
3385 self.branchPrefixes = [ branchPrefix ]
3389 filesForCommit = branches[branch]
3392 print("branch is %s" % branch)
3394 self.updatedBranches.add(branch)
3396 if branch not in self.createdBranches:
3397 self.createdBranches.add(branch)
3398 parent = self.knownBranches[branch]
3399 if parent == branch:
3402 fullBranch = self.projectName + branch
3403 if fullBranch not in self.p4BranchesInGit:
3405 print("\n Importing new branch %s" % fullBranch);
3406 if self.importNewBranch(branch, change - 1):
3408 self.p4BranchesInGit.append(fullBranch)
3410 print("\n Resuming with change %s" % change);
3413 print("parent determined through known branches: %s" % parent)
3415 branch = self.gitRefForBranch(branch)
3416 parent = self.gitRefForBranch(parent)
3419 print("looking for initial parent for %s; current parent is %s" % (branch, parent))
3421 if len(parent) == 0 and branch in self.initialParents:
3422 parent = self.initialParents[branch]
3423 del self.initialParents[branch]
3427 tempBranch = "%s/%d" % (self.tempBranchLocation, change)
3429 print("Creating temporary branch: " + tempBranch)
3430 self.commit(description, filesForCommit, tempBranch)
3431 self.tempBranches.append(tempBranch)
3433 blob = self.searchParent(parent, branch, tempBranch)
3435 self.commit(description, filesForCommit, branch, blob)
3438 print("Parent of %s not found. Committing into head of %s" % (branch, parent))
3439 self.commit(description, filesForCommit, branch, parent)
3441 files = self.extractFilesFromCommit(description)
3442 self.commit(description, files, self.branch,
3444 # only needed once, to connect to the previous commit
3445 self.initialParent = ""
3447 print(self.gitError.read())
3450 def sync_origin_only(self):
3451 if self.syncWithOrigin:
3452 self.hasOrigin = originP4BranchesExist()
3455 print('Syncing with origin first, using "git fetch origin"')
3456 system("git fetch origin")
3458 def importHeadRevision(self, revision):
3459 print("Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch))
3462 details["user"] = "git perforce import user"
3463 details["desc"] = ("Initial import of %s from the state at revision %s\n"
3464 % (' '.join(self.depotPaths), revision))
3465 details["change"] = revision
3469 fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
3471 for info in p4CmdList(["files"] + fileArgs):
3473 if 'code' in info and info['code'] == 'error':
3474 sys.stderr.write("p4 returned an error: %s\n"
3476 if info['data'].find("must refer to client") >= 0:
3477 sys.stderr.write("This particular p4 error is misleading.\n")
3478 sys.stderr.write("Perhaps the depot path was misspelled.\n");
3479 sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
3481 if 'p4ExitCode' in info:
3482 sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
3486 change = int(info["change"])
3487 if change > newestRevision:
3488 newestRevision = change
3490 if info["action"] in self.delete_actions:
3491 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
3492 #fileCnt = fileCnt + 1
3495 for prop in ["depotFile", "rev", "action", "type" ]:
3496 details["%s%s" % (prop, fileCnt)] = info[prop]
3498 fileCnt = fileCnt + 1
3500 details["change"] = newestRevision
3502 # Use time from top-most change so that all git p4 clones of
3503 # the same p4 repo have the same commit SHA1s.
3504 res = p4_describe(newestRevision)
3505 details["time"] = res["time"]
3507 self.updateOptionDict(details)
3509 self.commit(details, self.extractFilesFromCommit(details), self.branch)
3510 except IOError as err:
3511 print("IO error with git fast-import. Is your git version recent enough?")
3512 print("IO error details: {}".format(err))
3513 print(self.gitError.read())
3515 def openStreams(self):
3516 self.importProcess = subprocess.Popen(["git", "fast-import"],
3517 stdin=subprocess.PIPE,
3518 stdout=subprocess.PIPE,
3519 stderr=subprocess.PIPE);
3520 self.gitOutput = self.importProcess.stdout
3521 self.gitStream = self.importProcess.stdin
3522 self.gitError = self.importProcess.stderr
3524 def closeStreams(self):
3525 self.gitStream.close()
3526 if self.importProcess.wait() != 0:
3527 die("fast-import failed: %s" % self.gitError.read())
3528 self.gitOutput.close()
3529 self.gitError.close()
3531 def run(self, args):
3532 if self.importIntoRemotes:
3533 self.refPrefix = "refs/remotes/p4/"
3535 self.refPrefix = "refs/heads/p4/"
3537 self.sync_origin_only()
3539 branch_arg_given = bool(self.branch)
3540 if len(self.branch) == 0:
3541 self.branch = self.refPrefix + "master"
3542 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
3543 system("git update-ref %s refs/heads/p4" % self.branch)
3544 system("git branch -D p4")
3546 # accept either the command-line option, or the configuration variable
3547 if self.useClientSpec:
3548 # will use this after clone to set the variable
3549 self.useClientSpec_from_options = True
3551 if gitConfigBool("git-p4.useclientspec"):
3552 self.useClientSpec = True
3553 if self.useClientSpec:
3554 self.clientSpecDirs = getClientSpec()
3556 # TODO: should always look at previous commits,
3557 # merge with previous imports, if possible.
3560 createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
3562 # branches holds mapping from branch name to sha1
3563 branches = p4BranchesInGit(self.importIntoRemotes)
3565 # restrict to just this one, disabling detect-branches
3566 if branch_arg_given:
3567 short = self.branch.split("/")[-1]
3568 if short in branches:
3569 self.p4BranchesInGit = [ short ]
3571 self.p4BranchesInGit = branches.keys()
3573 if len(self.p4BranchesInGit) > 1:
3575 print("Importing from/into multiple branches")
3576 self.detectBranches = True
3577 for branch in branches.keys():
3578 self.initialParents[self.refPrefix + branch] = \
3582 print("branches: %s" % self.p4BranchesInGit)
3585 for branch in self.p4BranchesInGit:
3586 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
3588 settings = extractSettingsGitLog(logMsg)
3590 self.readOptions(settings)
3591 if ('depot-paths' in settings
3592 and 'change' in settings):
3593 change = int(settings['change']) + 1
3594 p4Change = max(p4Change, change)
3596 depotPaths = sorted(settings['depot-paths'])
3597 if self.previousDepotPaths == []:
3598 self.previousDepotPaths = depotPaths
3601 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
3602 prev_list = prev.split("/")
3603 cur_list = cur.split("/")
3604 for i in range(0, min(len(cur_list), len(prev_list))):
3605 if cur_list[i] != prev_list[i]:
3609 paths.append ("/".join(cur_list[:i + 1]))
3611 self.previousDepotPaths = paths
3614 self.depotPaths = sorted(self.previousDepotPaths)
3615 self.changeRange = "@%s,#head" % p4Change
3616 if not self.silent and not self.detectBranches:
3617 print("Performing incremental import into %s git branch" % self.branch)
3619 # accept multiple ref name abbreviations:
3620 # refs/foo/bar/branch -> use it exactly
3621 # p4/branch -> prepend refs/remotes/ or refs/heads/
3622 # branch -> prepend refs/remotes/p4/ or refs/heads/p4/
3623 if not self.branch.startswith("refs/"):
3624 if self.importIntoRemotes:
3625 prepend = "refs/remotes/"
3627 prepend = "refs/heads/"
3628 if not self.branch.startswith("p4/"):
3630 self.branch = prepend + self.branch
3632 if len(args) == 0 and self.depotPaths:
3634 print("Depot paths: %s" % ' '.join(self.depotPaths))
3636 if self.depotPaths and self.depotPaths != args:
3637 print("previous import used depot path %s and now %s was specified. "
3638 "This doesn't work!" % (' '.join (self.depotPaths),
3642 self.depotPaths = sorted(args)
3647 # Make sure no revision specifiers are used when --changesfile
3649 bad_changesfile = False
3650 if len(self.changesFile) > 0:
3651 for p in self.depotPaths:
3652 if p.find("@") >= 0 or p.find("#") >= 0:
3653 bad_changesfile = True
3656 die("Option --changesfile is incompatible with revision specifiers")
3659 for p in self.depotPaths:
3660 if p.find("@") != -1:
3661 atIdx = p.index("@")
3662 self.changeRange = p[atIdx:]
3663 if self.changeRange == "@all":
3664 self.changeRange = ""
3665 elif ',' not in self.changeRange:
3666 revision = self.changeRange
3667 self.changeRange = ""
3669 elif p.find("#") != -1:
3670 hashIdx = p.index("#")
3671 revision = p[hashIdx:]
3673 elif self.previousDepotPaths == []:
3674 # pay attention to changesfile, if given, else import
3675 # the entire p4 tree at the head revision
3676 if len(self.changesFile) == 0:
3679 p = re.sub ("\.\.\.$", "", p)
3680 if not p.endswith("/"):
3685 self.depotPaths = newPaths
3687 # --detect-branches may change this for each branch
3688 self.branchPrefixes = self.depotPaths
3690 self.loadUserMapFromCache()
3692 if self.detectLabels:
3695 if self.detectBranches:
3696 ## FIXME - what's a P4 projectName ?
3697 self.projectName = self.guessProjectName()
3700 self.getBranchMappingFromGitBranches()
3702 self.getBranchMapping()
3704 print("p4-git branches: %s" % self.p4BranchesInGit)
3705 print("initial parents: %s" % self.initialParents)
3706 for b in self.p4BranchesInGit:
3710 b = b[len(self.projectName):]
3711 self.createdBranches.add(b)
3716 self.importHeadRevision(revision)
3720 if len(self.changesFile) > 0:
3721 output = open(self.changesFile).readlines()
3724 changeSet.add(int(line))
3726 for change in changeSet:
3727 changes.append(change)
3731 # catch "git p4 sync" with no new branches, in a repo that
3732 # does not have any existing p4 branches
3734 if not self.p4BranchesInGit:
3735 die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.")
3737 # The default branch is master, unless --branch is used to
3738 # specify something else. Make sure it exists, or complain
3739 # nicely about how to use --branch.
3740 if not self.detectBranches:
3741 if not branch_exists(self.branch):
3742 if branch_arg_given:
3743 die("Error: branch %s does not exist." % self.branch)
3745 die("Error: no branch %s; perhaps specify one with --branch." %
3749 print("Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
3751 changes = p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)
3753 if len(self.maxChanges) > 0:
3754 changes = changes[:min(int(self.maxChanges), len(changes))]
3756 if len(changes) == 0:
3758 print("No changes to import!")
3760 if not self.silent and not self.detectBranches:
3761 print("Import destination: %s" % self.branch)
3763 self.updatedBranches = set()
3765 if not self.detectBranches:
3767 # start a new branch
3768 self.initialParent = ""
3770 # build on a previous revision
3771 self.initialParent = parseRevision(self.branch)
3773 self.importChanges(changes)
3777 if len(self.updatedBranches) > 0:
3778 sys.stdout.write("Updated branches: ")
3779 for b in self.updatedBranches:
3780 sys.stdout.write("%s " % b)
3781 sys.stdout.write("\n")
3783 if gitConfigBool("git-p4.importLabels"):
3784 self.importLabels = True
3786 if self.importLabels:
3787 p4Labels = getP4Labels(self.depotPaths)
3788 gitTags = getGitTags()
3790 missingP4Labels = p4Labels - gitTags
3791 self.importP4Labels(self.gitStream, missingP4Labels)
3795 # Cleanup temporary branches created during import
3796 if self.tempBranches != []:
3797 for branch in self.tempBranches:
3798 read_pipe("git update-ref -d %s" % branch)
3799 os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
3801 # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow
3802 # a convenient shortcut refname "p4".
3803 if self.importIntoRemotes:
3804 head_ref = self.refPrefix + "HEAD"
3805 if not gitBranchExists(head_ref) and gitBranchExists(self.branch):
3806 system(["git", "symbolic-ref", head_ref, self.branch])
3810 class P4Rebase(Command):
3812 Command.__init__(self)
3814 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
3816 self.importLabels = False
3817 self.description = ("Fetches the latest revision from perforce and "
3818 + "rebases the current work (branch) against it")
3820 def run(self, args):
3822 sync.importLabels = self.importLabels
3825 return self.rebase()
3828 if os.system("git update-index --refresh") != 0:
3829 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.");
3830 if len(read_pipe("git diff-index HEAD --")) > 0:
3831 die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");
3833 [upstream, settings] = findUpstreamBranchPoint()
3834 if len(upstream) == 0:
3835 die("Cannot find upstream branchpoint for rebase")
3837 # the branchpoint may be p4/foo~3, so strip off the parent
3838 upstream = re.sub("~[0-9]+$", "", upstream)
3840 print("Rebasing the current branch onto %s" % upstream)
3841 oldHead = read_pipe("git rev-parse HEAD").strip()
3842 system("git rebase %s" % upstream)
3843 system("git diff-tree --stat --summary -M %s HEAD --" % oldHead)
3846 class P4Clone(P4Sync):
3848 P4Sync.__init__(self)
3849 self.description = "Creates a new git repository and imports from Perforce into it"
3850 self.usage = "usage: %prog [options] //depot/path[@revRange]"
3852 optparse.make_option("--destination", dest="cloneDestination",
3853 action='store', default=None,
3854 help="where to leave result of the clone"),
3855 optparse.make_option("--bare", dest="cloneBare",
3856 action="store_true", default=False),
3858 self.cloneDestination = None
3859 self.needsGit = False
3860 self.cloneBare = False
3862 def defaultDestination(self, args):
3863 ## TODO: use common prefix of args?
3865 depotDir = re.sub("(@[^@]*)$", "", depotPath)
3866 depotDir = re.sub("(#[^#]*)$", "", depotDir)
3867 depotDir = re.sub(r"\.\.\.$", "", depotDir)
3868 depotDir = re.sub(r"/$", "", depotDir)
3869 return os.path.split(depotDir)[1]
3871 def run(self, args):
3875 if self.keepRepoPath and not self.cloneDestination:
3876 sys.stderr.write("Must specify destination for --keep-path\n")
3881 if not self.cloneDestination and len(depotPaths) > 1:
3882 self.cloneDestination = depotPaths[-1]
3883 depotPaths = depotPaths[:-1]
3885 for p in depotPaths:
3886 if not p.startswith("//"):
3887 sys.stderr.write('Depot paths must start with "//": %s\n' % p)
3890 if not self.cloneDestination:
3891 self.cloneDestination = self.defaultDestination(args)
3893 print("Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination))
3895 if not os.path.exists(self.cloneDestination):
3896 os.makedirs(self.cloneDestination)
3897 chdir(self.cloneDestination)
3899 init_cmd = [ "git", "init" ]
3901 init_cmd.append("--bare")
3902 retcode = subprocess.call(init_cmd)
3904 raise CalledProcessError(retcode, init_cmd)
3906 if not P4Sync.run(self, depotPaths):
3909 # create a master branch and check out a work tree
3910 if gitBranchExists(self.branch):
3911 system([ "git", "branch", "master", self.branch ])
3912 if not self.cloneBare:
3913 system([ "git", "checkout", "-f" ])
3915 print('Not checking out any branch, use ' \
3916 '"git checkout -q -b master <branch>"')
3918 # auto-set this variable if invoked with --use-client-spec
3919 if self.useClientSpec_from_options:
3920 system("git config --bool git-p4.useclientspec true")
3924 class P4Unshelve(Command):
3926 Command.__init__(self)
3928 self.origin = "HEAD"
3929 self.description = "Unshelve a P4 changelist into a git commit"
3930 self.usage = "usage: %prog [options] changelist"
3932 optparse.make_option("--origin", dest="origin",
3933 help="Use this base revision instead of the default (%s)" % self.origin),
3935 self.verbose = False
3936 self.noCommit = False
3937 self.destbranch = "refs/remotes/p4-unshelved"
3939 def renameBranch(self, branch_name):
3940 """ Rename the existing branch to branch_name.N
3944 for i in range(0,1000):
3945 backup_branch_name = "{0}.{1}".format(branch_name, i)
3946 if not gitBranchExists(backup_branch_name):
3947 gitUpdateRef(backup_branch_name, branch_name) # copy ref to backup
3948 gitDeleteRef(branch_name)
3950 print("renamed old unshelve branch to {0}".format(backup_branch_name))
3954 sys.exit("gave up trying to rename existing branch {0}".format(sync.branch))
3956 def findLastP4Revision(self, starting_point):
3957 """ Look back from starting_point for the first commit created by git-p4
3958 to find the P4 commit we are based on, and the depot-paths.
3961 for parent in (range(65535)):
3962 log = extractLogMessageFromGitCommit("{0}^{1}".format(starting_point, parent))
3963 settings = extractSettingsGitLog(log)
3964 if 'change' in settings:
3967 sys.exit("could not find git-p4 commits in {0}".format(self.origin))
3969 def createShelveParent(self, change, branch_name, sync, origin):
3970 """ Create a commit matching the parent of the shelved changelist 'change'
3972 parent_description = p4_describe(change, shelved=True)
3973 parent_description['desc'] = 'parent for shelved changelist {}\n'.format(change)
3974 files = sync.extractFilesFromCommit(parent_description, shelved=False, shelved_cl=change)
3978 # if it was added in the shelved changelist, it won't exist in the parent
3979 if f['action'] in self.add_actions:
3982 # if it was deleted in the shelved changelist it must not be deleted
3983 # in the parent - we might even need to create it if the origin branch
3985 if f['action'] in self.delete_actions:
3988 parent_files.append(f)
3990 sync.commit(parent_description, parent_files, branch_name,
3991 parent=origin, allow_empty=True)
3992 print("created parent commit for {0} based on {1} in {2}".format(
3993 change, self.origin, branch_name))
3995 def run(self, args):
3999 if not gitBranchExists(self.origin):
4000 sys.exit("origin branch {0} does not exist".format(self.origin))
4005 # only one change at a time
4008 # if the target branch already exists, rename it
4009 branch_name = "{0}/{1}".format(self.destbranch, change)
4010 if gitBranchExists(branch_name):
4011 self.renameBranch(branch_name)
4012 sync.branch = branch_name
4014 sync.verbose = self.verbose
4015 sync.suppress_meta_comment = True
4017 settings = self.findLastP4Revision(self.origin)
4018 sync.depotPaths = settings['depot-paths']
4019 sync.branchPrefixes = sync.depotPaths
4022 sync.loadUserMapFromCache()
4025 # create a commit for the parent of the shelved changelist
4026 self.createShelveParent(change, branch_name, sync, self.origin)
4028 # create the commit for the shelved changelist itself
4029 description = p4_describe(change, True)
4030 files = sync.extractFilesFromCommit(description, True, change)
4032 sync.commit(description, files, branch_name, "")
4035 print("unshelved changelist {0} into {1}".format(change, branch_name))
4039 class P4Branches(Command):
4041 Command.__init__(self)
4043 self.description = ("Shows the git branches that hold imports and their "
4044 + "corresponding perforce depot paths")
4045 self.verbose = False
4047 def run(self, args):
4048 if originP4BranchesExist():
4049 createOrUpdateBranchesFromOrigin()
4051 cmdline = "git rev-parse --symbolic "
4052 cmdline += " --remotes"
4054 for line in read_pipe_lines(cmdline):
4057 if not line.startswith('p4/') or line == "p4/HEAD":
4061 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
4062 settings = extractSettingsGitLog(log)
4064 print("%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]))
4067 class HelpFormatter(optparse.IndentedHelpFormatter):
4069 optparse.IndentedHelpFormatter.__init__(self)
4071 def format_description(self, description):
4073 return description + "\n"
4077 def printUsage(commands):
4078 print("usage: %s <command> [options]" % sys.argv[0])
4080 print("valid commands: %s" % ", ".join(commands))
4082 print("Try %s <command> --help for command specific help." % sys.argv[0])
4087 "submit" : P4Submit,
4088 "commit" : P4Submit,
4090 "rebase" : P4Rebase,
4092 "rollback" : P4RollBack,
4093 "branches" : P4Branches,
4094 "unshelve" : P4Unshelve,
4099 if len(sys.argv[1:]) == 0:
4100 printUsage(commands.keys())
4103 cmdName = sys.argv[1]
4105 klass = commands[cmdName]
4108 print("unknown command %s" % cmdName)
4110 printUsage(commands.keys())
4113 options = cmd.options
4114 cmd.gitdir = os.environ.get("GIT_DIR", None)
4118 options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
4120 options.append(optparse.make_option("--git-dir", dest="gitdir"))
4122 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
4124 description = cmd.description,
4125 formatter = HelpFormatter())
4127 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
4129 verbose = cmd.verbose
4131 if cmd.gitdir == None:
4132 cmd.gitdir = os.path.abspath(".git")
4133 if not isValidGitDir(cmd.gitdir):
4134 # "rev-parse --git-dir" without arguments will try $PWD/.git
4135 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
4136 if os.path.exists(cmd.gitdir):
4137 cdup = read_pipe("git rev-parse --show-cdup").strip()
4141 if not isValidGitDir(cmd.gitdir):
4142 if isValidGitDir(cmd.gitdir + "/.git"):
4143 cmd.gitdir += "/.git"
4145 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
4147 # so git commands invoked from the P4 workspace will succeed
4148 os.environ["GIT_DIR"] = cmd.gitdir
4150 if not cmd.run(args):
4155 if __name__ == '__main__':