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")
31 # Only labels/tags matching this will be imported/exported
32 defaultLabelRegexp = r'[a-zA-Z0-9_\-.]+$'
34 # The block size is reduced automatically if required
35 defaultBlockSize = 1<<20
37 p4_access_checked = False
39 def p4_build_cmd(cmd):
40 """Build a suitable p4 command line.
42 This consolidates building and returning a p4 command line into one
43 location. It means that hooking into the environment, or other configuration
44 can be done more easily.
48 user = gitConfig("git-p4.user")
50 real_cmd += ["-u",user]
52 password = gitConfig("git-p4.password")
54 real_cmd += ["-P", password]
56 port = gitConfig("git-p4.port")
58 real_cmd += ["-p", port]
60 host = gitConfig("git-p4.host")
62 real_cmd += ["-H", host]
64 client = gitConfig("git-p4.client")
66 real_cmd += ["-c", client]
68 retries = gitConfigInt("git-p4.retries")
70 # Perform 3 retries by default
73 # Provide a way to not pass this option by setting git-p4.retries to 0
74 real_cmd += ["-r", str(retries)]
76 if not isinstance(cmd, list):
77 real_cmd = ' '.join(real_cmd) + ' ' + cmd
81 # now check that we can actually talk to the server
82 global p4_access_checked
83 if not p4_access_checked:
84 p4_access_checked = True # suppress access checks in p4_check_access itself
90 """ Return TRUE if the given path is a git directory (/path/to/dir/.git).
91 This won't automatically add ".git" to a directory.
93 d = read_pipe(["git", "--git-dir", path, "rev-parse", "--git-dir"], True).strip()
94 if not d or len(d) == 0:
99 def chdir(path, is_client_path=False):
100 """Do chdir to the given path, and set the PWD environment
101 variable for use by P4. It does not look at getcwd() output.
102 Since we're not using the shell, it is necessary to set the
103 PWD environment variable explicitly.
105 Normally, expand the path to force it to be absolute. This
106 addresses the use of relative path names inside P4 settings,
107 e.g. P4CONFIG=.p4config. P4 does not simply open the filename
108 as given; it looks for .p4config using PWD.
110 If is_client_path, the path was handed to us directly by p4,
111 and may be a symbolic link. Do not call os.getcwd() in this
112 case, because it will cause p4 to think that PWD is not inside
117 if not is_client_path:
119 os.environ['PWD'] = path
122 """Return free space in bytes on the disk of the given dirname."""
123 if platform.system() == 'Windows':
124 free_bytes = ctypes.c_ulonglong(0)
125 ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(os.getcwd()), None, None, ctypes.pointer(free_bytes))
126 return free_bytes.value
128 st = os.statvfs(os.getcwd())
129 return st.f_bavail * st.f_frsize
135 sys.stderr.write(msg + "\n")
138 def write_pipe(c, stdin):
140 sys.stderr.write('Writing pipe: %s\n' % str(c))
142 expand = not isinstance(c, list)
143 p = subprocess.Popen(c, stdin=subprocess.PIPE, shell=expand)
145 val = pipe.write(stdin)
148 die('Command failed: %s' % str(c))
152 def p4_write_pipe(c, stdin):
153 real_cmd = p4_build_cmd(c)
154 return write_pipe(real_cmd, stdin)
156 def read_pipe_full(c):
157 """ Read output from command. Returns a tuple
158 of the return status, stdout text and stderr
162 sys.stderr.write('Reading pipe: %s\n' % str(c))
164 expand = not isinstance(c, list)
165 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand)
166 (out, err) = p.communicate()
167 return (p.returncode, out, err)
169 def read_pipe(c, ignore_error=False):
170 """ Read output from command. Returns the output text on
171 success. On failure, terminates execution, unless
172 ignore_error is True, when it returns an empty string.
174 (retcode, out, err) = read_pipe_full(c)
179 die('Command failed: %s\nError: %s' % (str(c), err))
182 def read_pipe_text(c):
183 """ Read output from a command with trailing whitespace stripped.
184 On error, returns None.
186 (retcode, out, err) = read_pipe_full(c)
192 def p4_read_pipe(c, ignore_error=False):
193 real_cmd = p4_build_cmd(c)
194 return read_pipe(real_cmd, ignore_error)
196 def read_pipe_lines(c):
198 sys.stderr.write('Reading pipe: %s\n' % str(c))
200 expand = not isinstance(c, list)
201 p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
203 val = pipe.readlines()
204 if pipe.close() or p.wait():
205 die('Command failed: %s' % str(c))
209 def p4_read_pipe_lines(c):
210 """Specifically invoke p4 on the command supplied. """
211 real_cmd = p4_build_cmd(c)
212 return read_pipe_lines(real_cmd)
214 def p4_has_command(cmd):
215 """Ask p4 for help on this command. If it returns an error, the
216 command does not exist in this version of p4."""
217 real_cmd = p4_build_cmd(["help", cmd])
218 p = subprocess.Popen(real_cmd, stdout=subprocess.PIPE,
219 stderr=subprocess.PIPE)
221 return p.returncode == 0
223 def p4_has_move_command():
224 """See if the move command exists, that it supports -k, and that
225 it has not been administratively disabled. The arguments
226 must be correct, but the filenames do not have to exist. Use
227 ones with wildcards so even if they exist, it will fail."""
229 if not p4_has_command("move"):
231 cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
232 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
233 (out, err) = p.communicate()
234 # return code will be 1 in either case
235 if err.find("Invalid option") >= 0:
237 if err.find("disabled") >= 0:
239 # assume it failed because @... was invalid changelist
242 def system(cmd, ignore_error=False):
243 expand = not isinstance(cmd, list)
245 sys.stderr.write("executing %s\n" % str(cmd))
246 retcode = subprocess.call(cmd, shell=expand)
247 if retcode and not ignore_error:
248 raise CalledProcessError(retcode, cmd)
253 """Specifically invoke p4 as the system command. """
254 real_cmd = p4_build_cmd(cmd)
255 expand = not isinstance(real_cmd, list)
256 retcode = subprocess.call(real_cmd, shell=expand)
258 raise CalledProcessError(retcode, real_cmd)
260 def die_bad_access(s):
261 die("failure accessing depot: {0}".format(s.rstrip()))
263 def p4_check_access(min_expiration=1):
264 """ Check if we can access Perforce - account still logged in
266 results = p4CmdList(["login", "-s"])
268 if len(results) == 0:
269 # should never get here: always get either some results, or a p4ExitCode
270 assert("could not parse response from perforce")
274 if 'p4ExitCode' in result:
275 # p4 returned non-zero status, e.g. P4PORT invalid, or p4 not in path
276 die_bad_access("could not run p4")
278 code = result.get("code")
280 # we get here if we couldn't connect and there was nothing to unmarshal
281 die_bad_access("could not connect")
284 expiry = result.get("TicketExpiration")
287 if expiry > min_expiration:
291 die_bad_access("perforce ticket expires in {0} seconds".format(expiry))
294 # account without a timeout - all ok
297 elif code == "error":
298 data = result.get("data")
300 die_bad_access("p4 error: {0}".format(data))
302 die_bad_access("unknown error")
306 die_bad_access("unknown error code {0}".format(code))
308 _p4_version_string = None
309 def p4_version_string():
310 """Read the version string, showing just the last line, which
311 hopefully is the interesting version bit.
314 Perforce - The Fast Software Configuration Management System.
315 Copyright 1995-2011 Perforce Software. All rights reserved.
316 Rev. P4/NTX86/2011.1/393975 (2011/12/16).
318 global _p4_version_string
319 if not _p4_version_string:
320 a = p4_read_pipe_lines(["-V"])
321 _p4_version_string = a[-1].rstrip()
322 return _p4_version_string
324 def p4_integrate(src, dest):
325 p4_system(["integrate", "-Dt", wildcard_encode(src), wildcard_encode(dest)])
327 def p4_sync(f, *options):
328 p4_system(["sync"] + list(options) + [wildcard_encode(f)])
331 # forcibly add file names with wildcards
332 if wildcard_present(f):
333 p4_system(["add", "-f", f])
335 p4_system(["add", f])
338 p4_system(["delete", wildcard_encode(f)])
340 def p4_edit(f, *options):
341 p4_system(["edit"] + list(options) + [wildcard_encode(f)])
344 p4_system(["revert", wildcard_encode(f)])
346 def p4_reopen(type, f):
347 p4_system(["reopen", "-t", type, wildcard_encode(f)])
349 def p4_reopen_in_change(changelist, files):
350 cmd = ["reopen", "-c", str(changelist)] + files
353 def p4_move(src, dest):
354 p4_system(["move", "-k", wildcard_encode(src), wildcard_encode(dest)])
356 def p4_last_change():
357 results = p4CmdList(["changes", "-m", "1"], skip_info=True)
358 return int(results[0]['change'])
360 def p4_describe(change, shelved=False):
361 """Make sure it returns a valid result by checking for
362 the presence of field "time". Return a dict of the
365 cmd = ["describe", "-s"]
370 ds = p4CmdList(cmd, skip_info=True)
372 die("p4 describe -s %d did not return 1 result: %s" % (change, str(ds)))
376 if "p4ExitCode" in d:
377 die("p4 describe -s %d exited with %d: %s" % (change, d["p4ExitCode"],
380 if d["code"] == "error":
381 die("p4 describe -s %d returned error code: %s" % (change, str(d)))
384 die("p4 describe -s %d returned no \"time\": %s" % (change, str(d)))
389 # Canonicalize the p4 type and return a tuple of the
390 # base type, plus any modifiers. See "p4 help filetypes"
391 # for a list and explanation.
393 def split_p4_type(p4type):
395 p4_filetypes_historical = {
396 "ctempobj": "binary+Sw",
402 "tempobj": "binary+FSw",
403 "ubinary": "binary+F",
404 "uresource": "resource+F",
405 "uxbinary": "binary+Fx",
406 "xbinary": "binary+x",
408 "xtempobj": "binary+Swx",
410 "xunicode": "unicode+x",
413 if p4type in p4_filetypes_historical:
414 p4type = p4_filetypes_historical[p4type]
416 s = p4type.split("+")
424 # return the raw p4 type of a file (text, text+ko, etc)
427 results = p4CmdList(["fstat", "-T", "headType", wildcard_encode(f)])
428 return results[0]['headType']
431 # Given a type base and modifier, return a regexp matching
432 # the keywords that can be expanded in the file
434 def p4_keywords_regexp_for_type(base, type_mods):
435 if base in ("text", "unicode", "binary"):
437 if "ko" in type_mods:
439 elif "k" in type_mods:
440 kwords = 'Id|Header|Author|Date|DateTime|Change|File|Revision'
444 \$ # Starts with a dollar, followed by...
445 (%s) # one of the keywords, followed by...
446 (:[^$\n]+)? # possibly an old expansion, followed by...
454 # Given a file, return a regexp matching the possible
455 # RCS keywords that will be expanded, or None for files
456 # with kw expansion turned off.
458 def p4_keywords_regexp_for_file(file):
459 if not os.path.exists(file):
462 (type_base, type_mods) = split_p4_type(p4_type(file))
463 return p4_keywords_regexp_for_type(type_base, type_mods)
465 def setP4ExecBit(file, mode):
466 # Reopens an already open file and changes the execute bit to match
467 # the execute bit setting in the passed in mode.
471 if not isModeExec(mode):
472 p4Type = getP4OpenedType(file)
473 p4Type = re.sub('^([cku]?)x(.*)', '\\1\\2', p4Type)
474 p4Type = re.sub('(.*?\+.*?)x(.*?)', '\\1\\2', p4Type)
475 if p4Type[-1] == "+":
476 p4Type = p4Type[0:-1]
478 p4_reopen(p4Type, file)
480 def getP4OpenedType(file):
481 # Returns the perforce file type for the given file.
483 result = p4_read_pipe(["opened", wildcard_encode(file)])
484 match = re.match(".*\((.+)\)( \*exclusive\*)?\r?$", result)
486 return match.group(1)
488 die("Could not determine file type for %s (result: '%s')" % (file, result))
490 # Return the set of all p4 labels
491 def getP4Labels(depotPaths):
493 if not isinstance(depotPaths, list):
494 depotPaths = [depotPaths]
496 for l in p4CmdList(["labels"] + ["%s..." % p for p in depotPaths]):
502 # Return the set of all git tags
505 for line in read_pipe_lines(["git", "tag"]):
510 def diffTreePattern():
511 # This is a simple generator for the diff tree regex pattern. This could be
512 # a class variable if this and parseDiffTreeEntry were a part of a class.
513 pattern = re.compile(':(\d+) (\d+) (\w+) (\w+) ([A-Z])(\d+)?\t(.*?)((\t(.*))|$)')
517 def parseDiffTreeEntry(entry):
518 """Parses a single diff tree entry into its component elements.
520 See git-diff-tree(1) manpage for details about the format of the diff
521 output. This method returns a dictionary with the following elements:
523 src_mode - The mode of the source file
524 dst_mode - The mode of the destination file
525 src_sha1 - The sha1 for the source file
526 dst_sha1 - The sha1 fr the destination file
527 status - The one letter status of the diff (i.e. 'A', 'M', 'D', etc)
528 status_score - The score for the status (applicable for 'C' and 'R'
529 statuses). This is None if there is no score.
530 src - The path for the source file.
531 dst - The path for the destination file. This is only present for
532 copy or renames. If it is not present, this is None.
534 If the pattern is not matched, None is returned."""
536 match = diffTreePattern().next().match(entry)
539 'src_mode': match.group(1),
540 'dst_mode': match.group(2),
541 'src_sha1': match.group(3),
542 'dst_sha1': match.group(4),
543 'status': match.group(5),
544 'status_score': match.group(6),
545 'src': match.group(7),
546 'dst': match.group(10)
550 def isModeExec(mode):
551 # Returns True if the given git mode represents an executable file,
553 return mode[-3:] == "755"
555 class P4Exception(Exception):
556 """ Base class for exceptions from the p4 client """
557 def __init__(self, exit_code):
558 self.p4ExitCode = exit_code
560 class P4ServerException(P4Exception):
561 """ Base class for exceptions where we get some kind of marshalled up result from the server """
562 def __init__(self, exit_code, p4_result):
563 super(P4ServerException, self).__init__(exit_code)
564 self.p4_result = p4_result
565 self.code = p4_result[0]['code']
566 self.data = p4_result[0]['data']
568 class P4RequestSizeException(P4ServerException):
569 """ One of the maxresults or maxscanrows errors """
570 def __init__(self, exit_code, p4_result, limit):
571 super(P4RequestSizeException, self).__init__(exit_code, p4_result)
574 def isModeExecChanged(src_mode, dst_mode):
575 return isModeExec(src_mode) != isModeExec(dst_mode)
577 def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,
578 errors_as_exceptions=False):
580 if not isinstance(cmd, list):
587 cmd = p4_build_cmd(cmd)
589 sys.stderr.write("Opening pipe: %s\n" % str(cmd))
591 # Use a temporary file to avoid deadlocks without
592 # subprocess.communicate(), which would put another copy
593 # of stdout into memory.
595 if stdin is not None:
596 stdin_file = tempfile.TemporaryFile(prefix='p4-stdin', mode=stdin_mode)
597 if not isinstance(stdin, list):
598 stdin_file.write(stdin)
601 stdin_file.write(i + '\n')
605 p4 = subprocess.Popen(cmd,
608 stdout=subprocess.PIPE)
613 entry = marshal.load(p4.stdout)
615 if 'code' in entry and entry['code'] == 'info':
625 if errors_as_exceptions:
627 data = result[0].get('data')
629 m = re.search('Too many rows scanned \(over (\d+)\)', data)
631 m = re.search('Request too large \(over (\d+)\)', data)
634 limit = int(m.group(1))
635 raise P4RequestSizeException(exitCode, result, limit)
637 raise P4ServerException(exitCode, result)
639 raise P4Exception(exitCode)
642 entry["p4ExitCode"] = exitCode
648 list = p4CmdList(cmd)
654 def p4Where(depotPath):
655 if not depotPath.endswith("/"):
657 depotPathLong = depotPath + "..."
658 outputList = p4CmdList(["where", depotPathLong])
660 for entry in outputList:
661 if "depotFile" in entry:
662 # Search for the base client side depot path, as long as it starts with the branch's P4 path.
663 # The base path always ends with "/...".
664 if entry["depotFile"].find(depotPath) == 0 and entry["depotFile"][-4:] == "/...":
667 elif "data" in entry:
668 data = entry.get("data")
669 space = data.find(" ")
670 if data[:space] == depotPath:
675 if output["code"] == "error":
679 clientPath = output.get("path")
680 elif "data" in output:
681 data = output.get("data")
682 lastSpace = data.rfind(" ")
683 clientPath = data[lastSpace + 1:]
685 if clientPath.endswith("..."):
686 clientPath = clientPath[:-3]
689 def currentGitBranch():
690 return read_pipe_text(["git", "symbolic-ref", "--short", "-q", "HEAD"])
692 def isValidGitDir(path):
693 return git_dir(path) != None
695 def parseRevision(ref):
696 return read_pipe("git rev-parse %s" % ref).strip()
698 def branchExists(ref):
699 rev = read_pipe(["git", "rev-parse", "-q", "--verify", ref],
703 def extractLogMessageFromGitCommit(commit):
706 ## fixme: title is first line of commit, not 1st paragraph.
708 for log in read_pipe_lines(["git", "cat-file", "commit", commit]):
717 def extractSettingsGitLog(log):
719 for line in log.split("\n"):
721 m = re.search (r"^ *\[git-p4: (.*)\]$", line)
725 assignments = m.group(1).split (':')
726 for a in assignments:
728 key = vals[0].strip()
729 val = ('='.join (vals[1:])).strip()
730 if val.endswith ('\"') and val.startswith('"'):
735 paths = values.get("depot-paths")
737 paths = values.get("depot-path")
739 values['depot-paths'] = paths.split(',')
742 def gitBranchExists(branch):
743 proc = subprocess.Popen(["git", "rev-parse", branch],
744 stderr=subprocess.PIPE, stdout=subprocess.PIPE);
745 return proc.wait() == 0;
747 def gitUpdateRef(ref, newvalue):
748 subprocess.check_call(["git", "update-ref", ref, newvalue])
750 def gitDeleteRef(ref):
751 subprocess.check_call(["git", "update-ref", "-d", ref])
755 def gitConfig(key, typeSpecifier=None):
756 if key not in _gitConfig:
757 cmd = [ "git", "config" ]
759 cmd += [ typeSpecifier ]
761 s = read_pipe(cmd, ignore_error=True)
762 _gitConfig[key] = s.strip()
763 return _gitConfig[key]
765 def gitConfigBool(key):
766 """Return a bool, using git config --bool. It is True only if the
767 variable is set to true, and False if set to false or not present
770 if key not in _gitConfig:
771 _gitConfig[key] = gitConfig(key, '--bool') == "true"
772 return _gitConfig[key]
774 def gitConfigInt(key):
775 if key not in _gitConfig:
776 cmd = [ "git", "config", "--int", key ]
777 s = read_pipe(cmd, ignore_error=True)
780 _gitConfig[key] = int(gitConfig(key, '--int'))
782 _gitConfig[key] = None
783 return _gitConfig[key]
785 def gitConfigList(key):
786 if key not in _gitConfig:
787 s = read_pipe(["git", "config", "--get-all", key], ignore_error=True)
788 _gitConfig[key] = s.strip().splitlines()
789 if _gitConfig[key] == ['']:
791 return _gitConfig[key]
793 def p4BranchesInGit(branchesAreInRemotes=True):
794 """Find all the branches whose names start with "p4/", looking
795 in remotes or heads as specified by the argument. Return
796 a dictionary of { branch: revision } for each one found.
797 The branch names are the short names, without any
802 cmdline = "git rev-parse --symbolic "
803 if branchesAreInRemotes:
804 cmdline += "--remotes"
806 cmdline += "--branches"
808 for line in read_pipe_lines(cmdline):
812 if not line.startswith('p4/'):
814 # special symbolic ref to p4/master
815 if line == "p4/HEAD":
818 # strip off p4/ prefix
819 branch = line[len("p4/"):]
821 branches[branch] = parseRevision(line)
825 def branch_exists(branch):
826 """Make sure that the given ref name really exists."""
828 cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
829 p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
830 out, _ = p.communicate()
833 # expect exactly one line of output: the branch name
834 return out.rstrip() == branch
836 def findUpstreamBranchPoint(head = "HEAD"):
837 branches = p4BranchesInGit()
838 # map from depot-path to branch name
839 branchByDepotPath = {}
840 for branch in branches.keys():
841 tip = branches[branch]
842 log = extractLogMessageFromGitCommit(tip)
843 settings = extractSettingsGitLog(log)
844 if "depot-paths" in settings:
845 paths = ",".join(settings["depot-paths"])
846 branchByDepotPath[paths] = "remotes/p4/" + branch
850 while parent < 65535:
851 commit = head + "~%s" % parent
852 log = extractLogMessageFromGitCommit(commit)
853 settings = extractSettingsGitLog(log)
854 if "depot-paths" in settings:
855 paths = ",".join(settings["depot-paths"])
856 if paths in branchByDepotPath:
857 return [branchByDepotPath[paths], settings]
861 return ["", settings]
863 def createOrUpdateBranchesFromOrigin(localRefPrefix = "refs/remotes/p4/", silent=True):
865 print("Creating/updating branch(es) in %s based on origin branch(es)"
868 originPrefix = "origin/p4/"
870 for line in read_pipe_lines("git rev-parse --symbolic --remotes"):
872 if (not line.startswith(originPrefix)) or line.endswith("HEAD"):
875 headName = line[len(originPrefix):]
876 remoteHead = localRefPrefix + headName
879 original = extractSettingsGitLog(extractLogMessageFromGitCommit(originHead))
880 if ('depot-paths' not in original
881 or 'change' not in original):
885 if not gitBranchExists(remoteHead):
887 print("creating %s" % remoteHead)
890 settings = extractSettingsGitLog(extractLogMessageFromGitCommit(remoteHead))
891 if 'change' in settings:
892 if settings['depot-paths'] == original['depot-paths']:
893 originP4Change = int(original['change'])
894 p4Change = int(settings['change'])
895 if originP4Change > p4Change:
896 print("%s (%s) is newer than %s (%s). "
897 "Updating p4 branch from origin."
898 % (originHead, originP4Change,
899 remoteHead, p4Change))
902 print("Ignoring: %s was imported from %s while "
903 "%s was imported from %s"
904 % (originHead, ','.join(original['depot-paths']),
905 remoteHead, ','.join(settings['depot-paths'])))
908 system("git update-ref %s %s" % (remoteHead, originHead))
910 def originP4BranchesExist():
911 return gitBranchExists("origin") or gitBranchExists("origin/p4") or gitBranchExists("origin/p4/master")
914 def p4ParseNumericChangeRange(parts):
915 changeStart = int(parts[0][1:])
916 if parts[1] == '#head':
917 changeEnd = p4_last_change()
919 changeEnd = int(parts[1])
921 return (changeStart, changeEnd)
923 def chooseBlockSize(blockSize):
927 return defaultBlockSize
929 def p4ChangesForPaths(depotPaths, changeRange, requestedBlockSize):
932 # Parse the change range into start and end. Try to find integer
933 # revision ranges as these can be broken up into blocks to avoid
934 # hitting server-side limits (maxrows, maxscanresults). But if
935 # that doesn't work, fall back to using the raw revision specifier
936 # strings, without using block mode.
938 if changeRange is None or changeRange == '':
940 changeEnd = p4_last_change()
941 block_size = chooseBlockSize(requestedBlockSize)
943 parts = changeRange.split(',')
944 assert len(parts) == 2
946 (changeStart, changeEnd) = p4ParseNumericChangeRange(parts)
947 block_size = chooseBlockSize(requestedBlockSize)
949 changeStart = parts[0][1:]
951 if requestedBlockSize:
952 die("cannot use --changes-block-size with non-numeric revisions")
957 # Retrieve changes a block at a time, to prevent running
958 # into a MaxResults/MaxScanRows error from the server. If
959 # we _do_ hit one of those errors, turn down the block size
965 end = min(changeEnd, changeStart + block_size)
966 revisionRange = "%d,%d" % (changeStart, end)
968 revisionRange = "%s,%s" % (changeStart, changeEnd)
971 cmd += ["%s...@%s" % (p, revisionRange)]
975 result = p4CmdList(cmd, errors_as_exceptions=True)
976 except P4RequestSizeException as e:
979 elif block_size > e.limit:
982 block_size = max(2, block_size // 2)
984 if verbose: print("block size error, retrying with block size {0}".format(block_size))
986 except P4Exception as e:
987 die('Error retrieving changes description ({0})'.format(e.p4ExitCode))
989 # Insert changes in chronological order
990 for entry in reversed(result):
991 if 'change' not in entry:
993 changes.add(int(entry['change']))
1001 changeStart = end + 1
1003 changes = sorted(changes)
1006 def p4PathStartsWith(path, prefix):
1007 # This method tries to remedy a potential mixed-case issue:
1009 # If UserA adds //depot/DirA/file1
1010 # and UserB adds //depot/dira/file2
1012 # we may or may not have a problem. If you have core.ignorecase=true,
1013 # we treat DirA and dira as the same directory
1014 if gitConfigBool("core.ignorecase"):
1015 return path.lower().startswith(prefix.lower())
1016 return path.startswith(prefix)
1018 def getClientSpec():
1019 """Look at the p4 client spec, create a View() object that contains
1020 all the mappings, and return it."""
1022 specList = p4CmdList("client -o")
1023 if len(specList) != 1:
1024 die('Output from "client -o" is %d lines, expecting 1' %
1027 # dictionary of all client parameters
1030 # the //client/ name
1031 client_name = entry["Client"]
1033 # just the keys that start with "View"
1034 view_keys = [ k for k in entry.keys() if k.startswith("View") ]
1036 # hold this new View
1037 view = View(client_name)
1039 # append the lines, in order, to the view
1040 for view_num in range(len(view_keys)):
1041 k = "View%d" % view_num
1042 if k not in view_keys:
1043 die("Expected view key %s missing" % k)
1044 view.append(entry[k])
1048 def getClientRoot():
1049 """Grab the client directory."""
1051 output = p4CmdList("client -o")
1052 if len(output) != 1:
1053 die('Output from "client -o" is %d lines, expecting 1' % len(output))
1056 if "Root" not in entry:
1057 die('Client has no "Root"')
1059 return entry["Root"]
1062 # P4 wildcards are not allowed in filenames. P4 complains
1063 # if you simply add them, but you can force it with "-f", in
1064 # which case it translates them into %xx encoding internally.
1066 def wildcard_decode(path):
1067 # Search for and fix just these four characters. Do % last so
1068 # that fixing it does not inadvertently create new %-escapes.
1069 # Cannot have * in a filename in windows; untested as to
1070 # what p4 would do in such a case.
1071 if not platform.system() == "Windows":
1072 path = path.replace("%2A", "*")
1073 path = path.replace("%23", "#") \
1074 .replace("%40", "@") \
1075 .replace("%25", "%")
1078 def wildcard_encode(path):
1079 # do % first to avoid double-encoding the %s introduced here
1080 path = path.replace("%", "%25") \
1081 .replace("*", "%2A") \
1082 .replace("#", "%23") \
1083 .replace("@", "%40")
1086 def wildcard_present(path):
1087 m = re.search("[*#@%]", path)
1088 return m is not None
1090 class LargeFileSystem(object):
1091 """Base class for large file system support."""
1093 def __init__(self, writeToGitStream):
1094 self.largeFiles = set()
1095 self.writeToGitStream = writeToGitStream
1097 def generatePointer(self, cloneDestination, contentFile):
1098 """Return the content of a pointer file that is stored in Git instead of
1099 the actual content."""
1100 assert False, "Method 'generatePointer' required in " + self.__class__.__name__
1102 def pushFile(self, localLargeFile):
1103 """Push the actual content which is not stored in the Git repository to
1105 assert False, "Method 'pushFile' required in " + self.__class__.__name__
1107 def hasLargeFileExtension(self, relPath):
1109 lambda a, b: a or b,
1110 [relPath.endswith('.' + e) for e in gitConfigList('git-p4.largeFileExtensions')],
1114 def generateTempFile(self, contents):
1115 contentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=False)
1117 contentFile.write(d)
1119 return contentFile.name
1121 def exceedsLargeFileThreshold(self, relPath, contents):
1122 if gitConfigInt('git-p4.largeFileThreshold'):
1123 contentsSize = sum(len(d) for d in contents)
1124 if contentsSize > gitConfigInt('git-p4.largeFileThreshold'):
1126 if gitConfigInt('git-p4.largeFileCompressedThreshold'):
1127 contentsSize = sum(len(d) for d in contents)
1128 if contentsSize <= gitConfigInt('git-p4.largeFileCompressedThreshold'):
1130 contentTempFile = self.generateTempFile(contents)
1131 compressedContentFile = tempfile.NamedTemporaryFile(prefix='git-p4-large-file', delete=True)
1132 with zipfile.ZipFile(compressedContentFile, mode='w') as zf:
1133 zf.write(contentTempFile, compress_type=zipfile.ZIP_DEFLATED)
1134 compressedContentsSize = zf.infolist()[0].compress_size
1135 os.remove(contentTempFile)
1136 if compressedContentsSize > gitConfigInt('git-p4.largeFileCompressedThreshold'):
1140 def addLargeFile(self, relPath):
1141 self.largeFiles.add(relPath)
1143 def removeLargeFile(self, relPath):
1144 self.largeFiles.remove(relPath)
1146 def isLargeFile(self, relPath):
1147 return relPath in self.largeFiles
1149 def processContent(self, git_mode, relPath, contents):
1150 """Processes the content of git fast import. This method decides if a
1151 file is stored in the large file system and handles all necessary
1153 if self.exceedsLargeFileThreshold(relPath, contents) or self.hasLargeFileExtension(relPath):
1154 contentTempFile = self.generateTempFile(contents)
1155 (pointer_git_mode, contents, localLargeFile) = self.generatePointer(contentTempFile)
1156 if pointer_git_mode:
1157 git_mode = pointer_git_mode
1159 # Move temp file to final location in large file system
1160 largeFileDir = os.path.dirname(localLargeFile)
1161 if not os.path.isdir(largeFileDir):
1162 os.makedirs(largeFileDir)
1163 shutil.move(contentTempFile, localLargeFile)
1164 self.addLargeFile(relPath)
1165 if gitConfigBool('git-p4.largeFilePush'):
1166 self.pushFile(localLargeFile)
1168 sys.stderr.write("%s moved to large file system (%s)\n" % (relPath, localLargeFile))
1169 return (git_mode, contents)
1171 class MockLFS(LargeFileSystem):
1172 """Mock large file system for testing."""
1174 def generatePointer(self, contentFile):
1175 """The pointer content is the original content prefixed with "pointer-".
1176 The local filename of the large file storage is derived from the file content.
1178 with open(contentFile, 'r') as f:
1181 pointerContents = 'pointer-' + content
1182 localLargeFile = os.path.join(os.getcwd(), '.git', 'mock-storage', 'local', content[:-1])
1183 return (gitMode, pointerContents, localLargeFile)
1185 def pushFile(self, localLargeFile):
1186 """The remote filename of the large file storage is the same as the local
1187 one but in a different directory.
1189 remotePath = os.path.join(os.path.dirname(localLargeFile), '..', 'remote')
1190 if not os.path.exists(remotePath):
1191 os.makedirs(remotePath)
1192 shutil.copyfile(localLargeFile, os.path.join(remotePath, os.path.basename(localLargeFile)))
1194 class GitLFS(LargeFileSystem):
1195 """Git LFS as backend for the git-p4 large file system.
1196 See https://git-lfs.github.com/ for details."""
1198 def __init__(self, *args):
1199 LargeFileSystem.__init__(self, *args)
1200 self.baseGitAttributes = []
1202 def generatePointer(self, contentFile):
1203 """Generate a Git LFS pointer for the content. Return LFS Pointer file
1204 mode and content which is stored in the Git repository instead of
1205 the actual content. Return also the new location of the actual
1208 if os.path.getsize(contentFile) == 0:
1209 return (None, '', None)
1211 pointerProcess = subprocess.Popen(
1212 ['git', 'lfs', 'pointer', '--file=' + contentFile],
1213 stdout=subprocess.PIPE
1215 pointerFile = pointerProcess.stdout.read()
1216 if pointerProcess.wait():
1217 os.remove(contentFile)
1218 die('git-lfs pointer command failed. Did you install the extension?')
1220 # Git LFS removed the preamble in the output of the 'pointer' command
1221 # starting from version 1.2.0. Check for the preamble here to support
1223 # c.f. https://github.com/github/git-lfs/commit/da2935d9a739592bc775c98d8ef4df9c72ea3b43
1224 if pointerFile.startswith('Git LFS pointer for'):
1225 pointerFile = re.sub(r'Git LFS pointer for.*\n\n', '', pointerFile)
1227 oid = re.search(r'^oid \w+:(\w+)', pointerFile, re.MULTILINE).group(1)
1228 localLargeFile = os.path.join(
1230 '.git', 'lfs', 'objects', oid[:2], oid[2:4],
1233 # LFS Spec states that pointer files should not have the executable bit set.
1235 return (gitMode, pointerFile, localLargeFile)
1237 def pushFile(self, localLargeFile):
1238 uploadProcess = subprocess.Popen(
1239 ['git', 'lfs', 'push', '--object-id', 'origin', os.path.basename(localLargeFile)]
1241 if uploadProcess.wait():
1242 die('git-lfs push command failed. Did you define a remote?')
1244 def generateGitAttributes(self):
1246 self.baseGitAttributes +
1250 '# Git LFS (see https://git-lfs.github.com/)\n',
1253 ['*.' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1254 for f in sorted(gitConfigList('git-p4.largeFileExtensions'))
1256 ['/' + f.replace(' ', '[[:space:]]') + ' filter=lfs diff=lfs merge=lfs -text\n'
1257 for f in sorted(self.largeFiles) if not self.hasLargeFileExtension(f)
1261 def addLargeFile(self, relPath):
1262 LargeFileSystem.addLargeFile(self, relPath)
1263 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
1265 def removeLargeFile(self, relPath):
1266 LargeFileSystem.removeLargeFile(self, relPath)
1267 self.writeToGitStream('100644', '.gitattributes', self.generateGitAttributes())
1269 def processContent(self, git_mode, relPath, contents):
1270 if relPath == '.gitattributes':
1271 self.baseGitAttributes = contents
1272 return (git_mode, self.generateGitAttributes())
1274 return LargeFileSystem.processContent(self, git_mode, relPath, contents)
1277 delete_actions = ( "delete", "move/delete", "purge" )
1278 add_actions = ( "add", "branch", "move/add" )
1281 self.usage = "usage: %prog [options]"
1282 self.needsGit = True
1283 self.verbose = False
1285 # This is required for the "append" update_shelve action
1286 def ensure_value(self, attr, value):
1287 if not hasattr(self, attr) or getattr(self, attr) is None:
1288 setattr(self, attr, value)
1289 return getattr(self, attr)
1293 self.userMapFromPerforceServer = False
1294 self.myP4UserId = None
1298 return self.myP4UserId
1300 results = p4CmdList("user -o")
1303 self.myP4UserId = r['User']
1305 die("Could not find your p4 user id")
1307 def p4UserIsMe(self, p4User):
1308 # return True if the given p4 user is actually me
1309 me = self.p4UserId()
1310 if not p4User or p4User != me:
1315 def getUserCacheFilename(self):
1316 home = os.environ.get("HOME", os.environ.get("USERPROFILE"))
1317 return home + "/.gitp4-usercache.txt"
1319 def getUserMapFromPerforceServer(self):
1320 if self.userMapFromPerforceServer:
1325 for output in p4CmdList("users"):
1326 if "User" not in output:
1328 self.users[output["User"]] = output["FullName"] + " <" + output["Email"] + ">"
1329 self.emails[output["Email"]] = output["User"]
1331 mapUserConfigRegex = re.compile(r"^\s*(\S+)\s*=\s*(.+)\s*<(\S+)>\s*$", re.VERBOSE)
1332 for mapUserConfig in gitConfigList("git-p4.mapUser"):
1333 mapUser = mapUserConfigRegex.findall(mapUserConfig)
1334 if mapUser and len(mapUser[0]) == 3:
1335 user = mapUser[0][0]
1336 fullname = mapUser[0][1]
1337 email = mapUser[0][2]
1338 self.users[user] = fullname + " <" + email + ">"
1339 self.emails[email] = user
1342 for (key, val) in self.users.items():
1343 s += "%s\t%s\n" % (key.expandtabs(1), val.expandtabs(1))
1345 open(self.getUserCacheFilename(), "wb").write(s)
1346 self.userMapFromPerforceServer = True
1348 def loadUserMapFromCache(self):
1350 self.userMapFromPerforceServer = False
1352 cache = open(self.getUserCacheFilename(), "rb")
1353 lines = cache.readlines()
1356 entry = line.strip().split("\t")
1357 self.users[entry[0]] = entry[1]
1359 self.getUserMapFromPerforceServer()
1361 class P4Debug(Command):
1363 Command.__init__(self)
1365 self.description = "A tool to debug the output of p4 -G."
1366 self.needsGit = False
1368 def run(self, args):
1370 for output in p4CmdList(args):
1371 print('Element: %d' % j)
1376 class P4RollBack(Command):
1378 Command.__init__(self)
1380 optparse.make_option("--local", dest="rollbackLocalBranches", action="store_true")
1382 self.description = "A tool to debug the multi-branch import. Don't use :)"
1383 self.rollbackLocalBranches = False
1385 def run(self, args):
1388 maxChange = int(args[0])
1390 if "p4ExitCode" in p4Cmd("changes -m 1"):
1391 die("Problems executing p4");
1393 if self.rollbackLocalBranches:
1394 refPrefix = "refs/heads/"
1395 lines = read_pipe_lines("git rev-parse --symbolic --branches")
1397 refPrefix = "refs/remotes/"
1398 lines = read_pipe_lines("git rev-parse --symbolic --remotes")
1401 if self.rollbackLocalBranches or (line.startswith("p4/") and line != "p4/HEAD\n"):
1403 ref = refPrefix + line
1404 log = extractLogMessageFromGitCommit(ref)
1405 settings = extractSettingsGitLog(log)
1407 depotPaths = settings['depot-paths']
1408 change = settings['change']
1412 if len(p4Cmd("changes -m 1 " + ' '.join (['%s...@%s' % (p, maxChange)
1413 for p in depotPaths]))) == 0:
1414 print("Branch %s did not exist at change %s, deleting." % (ref, maxChange))
1415 system("git update-ref -d %s `git rev-parse %s`" % (ref, ref))
1418 while change and int(change) > maxChange:
1421 print("%s is at %s ; rewinding towards %s" % (ref, change, maxChange))
1422 system("git update-ref %s \"%s^\"" % (ref, ref))
1423 log = extractLogMessageFromGitCommit(ref)
1424 settings = extractSettingsGitLog(log)
1427 depotPaths = settings['depot-paths']
1428 change = settings['change']
1431 print("%s rewound to %s" % (ref, change))
1435 class P4Submit(Command, P4UserMap):
1437 conflict_behavior_choices = ("ask", "skip", "quit")
1440 Command.__init__(self)
1441 P4UserMap.__init__(self)
1443 optparse.make_option("--origin", dest="origin"),
1444 optparse.make_option("-M", dest="detectRenames", action="store_true"),
1445 # preserve the user, requires relevant p4 permissions
1446 optparse.make_option("--preserve-user", dest="preserveUser", action="store_true"),
1447 optparse.make_option("--export-labels", dest="exportLabels", action="store_true"),
1448 optparse.make_option("--dry-run", "-n", dest="dry_run", action="store_true"),
1449 optparse.make_option("--prepare-p4-only", dest="prepare_p4_only", action="store_true"),
1450 optparse.make_option("--conflict", dest="conflict_behavior",
1451 choices=self.conflict_behavior_choices),
1452 optparse.make_option("--branch", dest="branch"),
1453 optparse.make_option("--shelve", dest="shelve", action="store_true",
1454 help="Shelve instead of submit. Shelved files are reverted, "
1455 "restoring the workspace to the state before the shelve"),
1456 optparse.make_option("--update-shelve", dest="update_shelve", action="append", type="int",
1457 metavar="CHANGELIST",
1458 help="update an existing shelved changelist, implies --shelve, "
1459 "repeat in-order for multiple shelved changelists"),
1460 optparse.make_option("--commit", dest="commit", metavar="COMMIT",
1461 help="submit only the specified commit(s), one commit or xxx..xxx"),
1462 optparse.make_option("--disable-rebase", dest="disable_rebase", action="store_true",
1463 help="Disable rebase after submit is completed. Can be useful if you "
1464 "work from a local git branch that is not master"),
1465 optparse.make_option("--disable-p4sync", dest="disable_p4sync", action="store_true",
1466 help="Skip Perforce sync of p4/master after submit or shelve"),
1468 self.description = """Submit changes from git to the perforce depot.\n
1469 The `p4-pre-submit` hook is executed if it exists and is executable.
1470 The hook takes no parameters and nothing from standard input. Exiting with
1471 non-zero status from this script prevents `git-p4 submit` from launching.
1473 One usage scenario is to run unit tests in the hook."""
1475 self.usage += " [name of git branch to submit into perforce depot]"
1477 self.detectRenames = False
1478 self.preserveUser = gitConfigBool("git-p4.preserveUser")
1479 self.dry_run = False
1481 self.update_shelve = list()
1483 self.disable_rebase = gitConfigBool("git-p4.disableRebase")
1484 self.disable_p4sync = gitConfigBool("git-p4.disableP4Sync")
1485 self.prepare_p4_only = False
1486 self.conflict_behavior = None
1487 self.isWindows = (platform.system() == "Windows")
1488 self.exportLabels = False
1489 self.p4HasMoveCommand = p4_has_move_command()
1492 if gitConfig('git-p4.largeFileSystem'):
1493 die("Large file system not supported for git-p4 submit command. Please remove it from config.")
1496 if len(p4CmdList("opened ...")) > 0:
1497 die("You have files opened with perforce! Close them before starting the sync.")
1499 def separate_jobs_from_description(self, message):
1500 """Extract and return a possible Jobs field in the commit
1501 message. It goes into a separate section in the p4 change
1504 A jobs line starts with "Jobs:" and looks like a new field
1505 in a form. Values are white-space separated on the same
1506 line or on following lines that start with a tab.
1508 This does not parse and extract the full git commit message
1509 like a p4 form. It just sees the Jobs: line as a marker
1510 to pass everything from then on directly into the p4 form,
1511 but outside the description section.
1513 Return a tuple (stripped log message, jobs string)."""
1515 m = re.search(r'^Jobs:', message, re.MULTILINE)
1517 return (message, None)
1519 jobtext = message[m.start():]
1520 stripped_message = message[:m.start()].rstrip()
1521 return (stripped_message, jobtext)
1523 def prepareLogMessage(self, template, message, jobs):
1524 """Edits the template returned from "p4 change -o" to insert
1525 the message in the Description field, and the jobs text in
1529 inDescriptionSection = False
1531 for line in template.split("\n"):
1532 if line.startswith("#"):
1533 result += line + "\n"
1536 if inDescriptionSection:
1537 if line.startswith("Files:") or line.startswith("Jobs:"):
1538 inDescriptionSection = False
1539 # insert Jobs section
1541 result += jobs + "\n"
1545 if line.startswith("Description:"):
1546 inDescriptionSection = True
1548 for messageLine in message.split("\n"):
1549 line += "\t" + messageLine + "\n"
1551 result += line + "\n"
1555 def patchRCSKeywords(self, file, pattern):
1556 # Attempt to zap the RCS keywords in a p4 controlled file matching the given pattern
1557 (handle, outFileName) = tempfile.mkstemp(dir='.')
1559 outFile = os.fdopen(handle, "w+")
1560 inFile = open(file, "r")
1561 regexp = re.compile(pattern, re.VERBOSE)
1562 for line in inFile.readlines():
1563 line = regexp.sub(r'$\1$', line)
1567 # Forcibly overwrite the original file
1569 shutil.move(outFileName, file)
1571 # cleanup our temporary file
1572 os.unlink(outFileName)
1573 print("Failed to strip RCS keywords in %s" % file)
1576 print("Patched up RCS keywords in %s" % file)
1578 def p4UserForCommit(self,id):
1579 # Return the tuple (perforce user,git email) for a given git commit id
1580 self.getUserMapFromPerforceServer()
1581 gitEmail = read_pipe(["git", "log", "--max-count=1",
1582 "--format=%ae", id])
1583 gitEmail = gitEmail.strip()
1584 if gitEmail not in self.emails:
1585 return (None,gitEmail)
1587 return (self.emails[gitEmail],gitEmail)
1589 def checkValidP4Users(self,commits):
1590 # check if any git authors cannot be mapped to p4 users
1592 (user,email) = self.p4UserForCommit(id)
1594 msg = "Cannot find p4 user for email %s in commit %s." % (email, id)
1595 if gitConfigBool("git-p4.allowMissingP4Users"):
1598 die("Error: %s\nSet git-p4.allowMissingP4Users to true to allow this." % msg)
1600 def lastP4Changelist(self):
1601 # Get back the last changelist number submitted in this client spec. This
1602 # then gets used to patch up the username in the change. If the same
1603 # client spec is being used by multiple processes then this might go
1605 results = p4CmdList("client -o") # find the current client
1609 client = r['Client']
1612 die("could not get client spec")
1613 results = p4CmdList(["changes", "-c", client, "-m", "1"])
1617 die("Could not get changelist number for last submit - cannot patch up user details")
1619 def modifyChangelistUser(self, changelist, newUser):
1620 # fixup the user field of a changelist after it has been submitted.
1621 changes = p4CmdList("change -o %s" % changelist)
1622 if len(changes) != 1:
1623 die("Bad output from p4 change modifying %s to user %s" %
1624 (changelist, newUser))
1627 if c['User'] == newUser: return # nothing to do
1629 input = marshal.dumps(c)
1631 result = p4CmdList("change -f -i", stdin=input)
1634 if r['code'] == 'error':
1635 die("Could not modify user field of changelist %s to %s:%s" % (changelist, newUser, r['data']))
1637 print("Updated user field for changelist %s to %s" % (changelist, newUser))
1639 die("Could not modify user field of changelist %s to %s" % (changelist, newUser))
1641 def canChangeChangelists(self):
1642 # check to see if we have p4 admin or super-user permissions, either of
1643 # which are required to modify changelists.
1644 results = p4CmdList(["protects", self.depotPath])
1647 if r['perm'] == 'admin':
1649 if r['perm'] == 'super':
1653 def prepareSubmitTemplate(self, changelist=None):
1654 """Run "p4 change -o" to grab a change specification template.
1655 This does not use "p4 -G", as it is nice to keep the submission
1656 template in original order, since a human might edit it.
1658 Remove lines in the Files section that show changes to files
1659 outside the depot path we're committing into."""
1661 [upstream, settings] = findUpstreamBranchPoint()
1664 # A Perforce Change Specification.
1666 # Change: The change number. 'new' on a new changelist.
1667 # Date: The date this specification was last modified.
1668 # Client: The client on which the changelist was created. Read-only.
1669 # User: The user who created the changelist.
1670 # Status: Either 'pending' or 'submitted'. Read-only.
1671 # Type: Either 'public' or 'restricted'. Default is 'public'.
1672 # Description: Comments about the changelist. Required.
1673 # Jobs: What opened jobs are to be closed by this changelist.
1674 # You may delete jobs from this list. (New changelists only.)
1675 # Files: What opened files from the default changelist are to be added
1676 # to this changelist. You may delete files from this list.
1677 # (New changelists only.)
1680 inFilesSection = False
1682 args = ['change', '-o']
1684 args.append(str(changelist))
1685 for entry in p4CmdList(args):
1686 if 'code' not in entry:
1688 if entry['code'] == 'stat':
1689 change_entry = entry
1691 if not change_entry:
1692 die('Failed to decode output of p4 change -o')
1693 for key, value in change_entry.iteritems():
1694 if key.startswith('File'):
1695 if 'depot-paths' in settings:
1696 if not [p for p in settings['depot-paths']
1697 if p4PathStartsWith(value, p)]:
1700 if not p4PathStartsWith(value, self.depotPath):
1702 files_list.append(value)
1704 # Output in the order expected by prepareLogMessage
1705 for key in ['Change', 'Client', 'User', 'Status', 'Description', 'Jobs']:
1706 if key not in change_entry:
1709 template += key + ':'
1710 if key == 'Description':
1712 for field_line in change_entry[key].splitlines():
1713 template += '\t'+field_line+'\n'
1714 if len(files_list) > 0:
1716 template += 'Files:\n'
1717 for path in files_list:
1718 template += '\t'+path+'\n'
1721 def edit_template(self, template_file):
1722 """Invoke the editor to let the user change the submission
1723 message. Return true if okay to continue with the submit."""
1725 # if configured to skip the editing part, just submit
1726 if gitConfigBool("git-p4.skipSubmitEdit"):
1729 # look at the modification time, to check later if the user saved
1731 mtime = os.stat(template_file).st_mtime
1734 if "P4EDITOR" in os.environ and (os.environ.get("P4EDITOR") != ""):
1735 editor = os.environ.get("P4EDITOR")
1737 editor = read_pipe("git var GIT_EDITOR").strip()
1738 system(["sh", "-c", ('%s "$@"' % editor), editor, template_file])
1740 # If the file was not saved, prompt to see if this patch should
1741 # be skipped. But skip this verification step if configured so.
1742 if gitConfigBool("git-p4.skipSubmitEditCheck"):
1745 # modification time updated means user saved the file
1746 if os.stat(template_file).st_mtime > mtime:
1750 response = raw_input("Submit template unchanged. Submit anyway? [y]es, [n]o (skip this patch) ")
1756 def get_diff_description(self, editedFiles, filesToAdd, symlinks):
1758 if "P4DIFF" in os.environ:
1759 del(os.environ["P4DIFF"])
1761 for editedFile in editedFiles:
1762 diff += p4_read_pipe(['diff', '-du',
1763 wildcard_encode(editedFile)])
1767 for newFile in filesToAdd:
1768 newdiff += "==== new file ====\n"
1769 newdiff += "--- /dev/null\n"
1770 newdiff += "+++ %s\n" % newFile
1772 is_link = os.path.islink(newFile)
1773 expect_link = newFile in symlinks
1775 if is_link and expect_link:
1776 newdiff += "+%s\n" % os.readlink(newFile)
1778 f = open(newFile, "r")
1779 for line in f.readlines():
1780 newdiff += "+" + line
1783 return (diff + newdiff).replace('\r\n', '\n')
1785 def applyCommit(self, id):
1786 """Apply one commit, return True if it succeeded."""
1788 print("Applying", read_pipe(["git", "show", "-s",
1789 "--format=format:%h %s", id]))
1791 (p4User, gitEmail) = self.p4UserForCommit(id)
1793 diff = read_pipe_lines("git diff-tree -r %s \"%s^\" \"%s\"" % (self.diffOpts, id, id))
1795 filesToChangeType = set()
1796 filesToDelete = set()
1798 pureRenameCopy = set()
1800 filesToChangeExecBit = {}
1804 diff = parseDiffTreeEntry(line)
1805 modifier = diff['status']
1807 all_files.append(path)
1811 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1812 filesToChangeExecBit[path] = diff['dst_mode']
1813 editedFiles.add(path)
1814 elif modifier == "A":
1815 filesToAdd.add(path)
1816 filesToChangeExecBit[path] = diff['dst_mode']
1817 if path in filesToDelete:
1818 filesToDelete.remove(path)
1820 dst_mode = int(diff['dst_mode'], 8)
1821 if dst_mode == 0o120000:
1824 elif modifier == "D":
1825 filesToDelete.add(path)
1826 if path in filesToAdd:
1827 filesToAdd.remove(path)
1828 elif modifier == "C":
1829 src, dest = diff['src'], diff['dst']
1830 all_files.append(dest)
1831 p4_integrate(src, dest)
1832 pureRenameCopy.add(dest)
1833 if diff['src_sha1'] != diff['dst_sha1']:
1835 pureRenameCopy.discard(dest)
1836 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1838 pureRenameCopy.discard(dest)
1839 filesToChangeExecBit[dest] = diff['dst_mode']
1841 # turn off read-only attribute
1842 os.chmod(dest, stat.S_IWRITE)
1844 editedFiles.add(dest)
1845 elif modifier == "R":
1846 src, dest = diff['src'], diff['dst']
1847 all_files.append(dest)
1848 if self.p4HasMoveCommand:
1849 p4_edit(src) # src must be open before move
1850 p4_move(src, dest) # opens for (move/delete, move/add)
1852 p4_integrate(src, dest)
1853 if diff['src_sha1'] != diff['dst_sha1']:
1856 pureRenameCopy.add(dest)
1857 if isModeExecChanged(diff['src_mode'], diff['dst_mode']):
1858 if not self.p4HasMoveCommand:
1859 p4_edit(dest) # with move: already open, writable
1860 filesToChangeExecBit[dest] = diff['dst_mode']
1861 if not self.p4HasMoveCommand:
1863 os.chmod(dest, stat.S_IWRITE)
1865 filesToDelete.add(src)
1866 editedFiles.add(dest)
1867 elif modifier == "T":
1868 filesToChangeType.add(path)
1870 die("unknown modifier %s for %s" % (modifier, path))
1872 diffcmd = "git diff-tree --full-index -p \"%s\"" % (id)
1873 patchcmd = diffcmd + " | git apply "
1874 tryPatchCmd = patchcmd + "--check -"
1875 applyPatchCmd = patchcmd + "--check --apply -"
1876 patch_succeeded = True
1878 if os.system(tryPatchCmd) != 0:
1879 fixed_rcs_keywords = False
1880 patch_succeeded = False
1881 print("Unfortunately applying the change failed!")
1883 # Patch failed, maybe it's just RCS keyword woes. Look through
1884 # the patch to see if that's possible.
1885 if gitConfigBool("git-p4.attemptRCSCleanup"):
1889 for file in editedFiles | filesToDelete:
1890 # did this file's delta contain RCS keywords?
1891 pattern = p4_keywords_regexp_for_file(file)
1894 # this file is a possibility...look for RCS keywords.
1895 regexp = re.compile(pattern, re.VERBOSE)
1896 for line in read_pipe_lines(["git", "diff", "%s^..%s" % (id, id), file]):
1897 if regexp.search(line):
1899 print("got keyword match on %s in %s in %s" % (pattern, line, file))
1900 kwfiles[file] = pattern
1903 for file in kwfiles:
1905 print("zapping %s with %s" % (line,pattern))
1906 # File is being deleted, so not open in p4. Must
1907 # disable the read-only bit on windows.
1908 if self.isWindows and file not in editedFiles:
1909 os.chmod(file, stat.S_IWRITE)
1910 self.patchRCSKeywords(file, kwfiles[file])
1911 fixed_rcs_keywords = True
1913 if fixed_rcs_keywords:
1914 print("Retrying the patch with RCS keywords cleaned up")
1915 if os.system(tryPatchCmd) == 0:
1916 patch_succeeded = True
1918 if not patch_succeeded:
1919 for f in editedFiles:
1924 # Apply the patch for real, and do add/delete/+x handling.
1926 system(applyPatchCmd)
1928 for f in filesToChangeType:
1929 p4_edit(f, "-t", "auto")
1930 for f in filesToAdd:
1932 for f in filesToDelete:
1936 # Set/clear executable bits
1937 for f in filesToChangeExecBit.keys():
1938 mode = filesToChangeExecBit[f]
1939 setP4ExecBit(f, mode)
1942 if len(self.update_shelve) > 0:
1943 update_shelve = self.update_shelve.pop(0)
1944 p4_reopen_in_change(update_shelve, all_files)
1947 # Build p4 change description, starting with the contents
1948 # of the git commit message.
1950 logMessage = extractLogMessageFromGitCommit(id)
1951 logMessage = logMessage.strip()
1952 (logMessage, jobs) = self.separate_jobs_from_description(logMessage)
1954 template = self.prepareSubmitTemplate(update_shelve)
1955 submitTemplate = self.prepareLogMessage(template, logMessage, jobs)
1957 if self.preserveUser:
1958 submitTemplate += "\n######## Actual user %s, modified after commit\n" % p4User
1960 if self.checkAuthorship and not self.p4UserIsMe(p4User):
1961 submitTemplate += "######## git author %s does not match your p4 account.\n" % gitEmail
1962 submitTemplate += "######## Use option --preserve-user to modify authorship.\n"
1963 submitTemplate += "######## Variable git-p4.skipUserNameCheck hides this message.\n"
1965 separatorLine = "######## everything below this line is just the diff #######\n"
1966 if not self.prepare_p4_only:
1967 submitTemplate += separatorLine
1968 submitTemplate += self.get_diff_description(editedFiles, filesToAdd, symlinks)
1970 (handle, fileName) = tempfile.mkstemp()
1971 tmpFile = os.fdopen(handle, "w+b")
1973 submitTemplate = submitTemplate.replace("\n", "\r\n")
1974 tmpFile.write(submitTemplate)
1977 if self.prepare_p4_only:
1979 # Leave the p4 tree prepared, and the submit template around
1980 # and let the user decide what to do next
1983 print("P4 workspace prepared for submission.")
1984 print("To submit or revert, go to client workspace")
1985 print(" " + self.clientPath)
1987 print("To submit, use \"p4 submit\" to write a new description,")
1988 print("or \"p4 submit -i <%s\" to use the one prepared by" \
1989 " \"git p4\"." % fileName)
1990 print("You can delete the file \"%s\" when finished." % fileName)
1992 if self.preserveUser and p4User and not self.p4UserIsMe(p4User):
1993 print("To preserve change ownership by user %s, you must\n" \
1994 "do \"p4 change -f <change>\" after submitting and\n" \
1995 "edit the User field.")
1997 print("After submitting, renamed files must be re-synced.")
1998 print("Invoke \"p4 sync -f\" on each of these files:")
1999 for f in pureRenameCopy:
2003 print("To revert the changes, use \"p4 revert ...\", and delete")
2004 print("the submit template file \"%s\"" % fileName)
2006 print("Since the commit adds new files, they must be deleted:")
2007 for f in filesToAdd:
2013 # Let the user edit the change description, then submit it.
2018 if self.edit_template(fileName):
2019 # read the edited message and submit
2020 tmpFile = open(fileName, "rb")
2021 message = tmpFile.read()
2024 message = message.replace("\r\n", "\n")
2025 submitTemplate = message[:message.index(separatorLine)]
2028 p4_write_pipe(['shelve', '-r', '-i'], submitTemplate)
2030 p4_write_pipe(['shelve', '-i'], submitTemplate)
2032 p4_write_pipe(['submit', '-i'], submitTemplate)
2033 # The rename/copy happened by applying a patch that created a
2034 # new file. This leaves it writable, which confuses p4.
2035 for f in pureRenameCopy:
2038 if self.preserveUser:
2040 # Get last changelist number. Cannot easily get it from
2041 # the submit command output as the output is
2043 changelist = self.lastP4Changelist()
2044 self.modifyChangelistUser(changelist, p4User)
2050 if not submitted or self.shelve:
2052 print ("Reverting shelved files.")
2054 print ("Submission cancelled, undoing p4 changes.")
2055 for f in editedFiles | filesToDelete:
2057 for f in filesToAdd:
2064 # Export git tags as p4 labels. Create a p4 label and then tag
2066 def exportGitTags(self, gitTags):
2067 validLabelRegexp = gitConfig("git-p4.labelExportRegexp")
2068 if len(validLabelRegexp) == 0:
2069 validLabelRegexp = defaultLabelRegexp
2070 m = re.compile(validLabelRegexp)
2072 for name in gitTags:
2074 if not m.match(name):
2076 print("tag %s does not match regexp %s" % (name, validLabelRegexp))
2079 # Get the p4 commit this corresponds to
2080 logMessage = extractLogMessageFromGitCommit(name)
2081 values = extractSettingsGitLog(logMessage)
2083 if 'change' not in values:
2084 # a tag pointing to something not sent to p4; ignore
2086 print("git tag %s does not give a p4 commit" % name)
2089 changelist = values['change']
2091 # Get the tag details.
2095 for l in read_pipe_lines(["git", "cat-file", "-p", name]):
2098 if re.match(r'tag\s+', l):
2100 elif re.match(r'\s*$', l):
2107 body = ["lightweight tag imported by git p4\n"]
2109 # Create the label - use the same view as the client spec we are using
2110 clientSpec = getClientSpec()
2112 labelTemplate = "Label: %s\n" % name
2113 labelTemplate += "Description:\n"
2115 labelTemplate += "\t" + b + "\n"
2116 labelTemplate += "View:\n"
2117 for depot_side in clientSpec.mappings:
2118 labelTemplate += "\t%s\n" % depot_side
2121 print("Would create p4 label %s for tag" % name)
2122 elif self.prepare_p4_only:
2123 print("Not creating p4 label %s for tag due to option" \
2124 " --prepare-p4-only" % name)
2126 p4_write_pipe(["label", "-i"], labelTemplate)
2129 p4_system(["tag", "-l", name] +
2130 ["%s@%s" % (depot_side, changelist) for depot_side in clientSpec.mappings])
2133 print("created p4 label for tag %s" % name)
2135 def run(self, args):
2137 self.master = currentGitBranch()
2138 elif len(args) == 1:
2139 self.master = args[0]
2140 if not branchExists(self.master):
2141 die("Branch %s does not exist" % self.master)
2145 for i in self.update_shelve:
2147 sys.exit("invalid changelist %d" % i)
2150 allowSubmit = gitConfig("git-p4.allowSubmit")
2151 if len(allowSubmit) > 0 and not self.master in allowSubmit.split(","):
2152 die("%s is not in git-p4.allowSubmit" % self.master)
2154 [upstream, settings] = findUpstreamBranchPoint()
2155 self.depotPath = settings['depot-paths'][0]
2156 if len(self.origin) == 0:
2157 self.origin = upstream
2159 if len(self.update_shelve) > 0:
2162 if self.preserveUser:
2163 if not self.canChangeChangelists():
2164 die("Cannot preserve user names without p4 super-user or admin permissions")
2166 # if not set from the command line, try the config file
2167 if self.conflict_behavior is None:
2168 val = gitConfig("git-p4.conflict")
2170 if val not in self.conflict_behavior_choices:
2171 die("Invalid value '%s' for config git-p4.conflict" % val)
2174 self.conflict_behavior = val
2177 print("Origin branch is " + self.origin)
2179 if len(self.depotPath) == 0:
2180 print("Internal error: cannot locate perforce depot path from existing branches")
2183 self.useClientSpec = False
2184 if gitConfigBool("git-p4.useclientspec"):
2185 self.useClientSpec = True
2186 if self.useClientSpec:
2187 self.clientSpecDirs = getClientSpec()
2189 # Check for the existence of P4 branches
2190 branchesDetected = (len(p4BranchesInGit().keys()) > 1)
2192 if self.useClientSpec and not branchesDetected:
2193 # all files are relative to the client spec
2194 self.clientPath = getClientRoot()
2196 self.clientPath = p4Where(self.depotPath)
2198 if self.clientPath == "":
2199 die("Error: Cannot locate perforce checkout of %s in client view" % self.depotPath)
2201 print("Perforce checkout for depot path %s located at %s" % (self.depotPath, self.clientPath))
2202 self.oldWorkingDirectory = os.getcwd()
2204 # ensure the clientPath exists
2205 new_client_dir = False
2206 if not os.path.exists(self.clientPath):
2207 new_client_dir = True
2208 os.makedirs(self.clientPath)
2210 chdir(self.clientPath, is_client_path=True)
2212 print("Would synchronize p4 checkout in %s" % self.clientPath)
2214 print("Synchronizing p4 checkout...")
2216 # old one was destroyed, and maybe nobody told p4
2217 p4_sync("...", "-f")
2224 committish = self.master
2228 if self.commit != "":
2229 if self.commit.find("..") != -1:
2230 limits_ish = self.commit.split("..")
2231 for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (limits_ish[0], limits_ish[1])]):
2232 commits.append(line.strip())
2235 commits.append(self.commit)
2237 for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, committish)]):
2238 commits.append(line.strip())
2241 if self.preserveUser or gitConfigBool("git-p4.skipUserNameCheck"):
2242 self.checkAuthorship = False
2244 self.checkAuthorship = True
2246 if self.preserveUser:
2247 self.checkValidP4Users(commits)
2250 # Build up a set of options to be passed to diff when
2251 # submitting each commit to p4.
2253 if self.detectRenames:
2254 # command-line -M arg
2255 self.diffOpts = "-M"
2257 # If not explicitly set check the config variable
2258 detectRenames = gitConfig("git-p4.detectRenames")
2260 if detectRenames.lower() == "false" or detectRenames == "":
2262 elif detectRenames.lower() == "true":
2263 self.diffOpts = "-M"
2265 self.diffOpts = "-M%s" % detectRenames
2267 # no command-line arg for -C or --find-copies-harder, just
2269 detectCopies = gitConfig("git-p4.detectCopies")
2270 if detectCopies.lower() == "false" or detectCopies == "":
2272 elif detectCopies.lower() == "true":
2273 self.diffOpts += " -C"
2275 self.diffOpts += " -C%s" % detectCopies
2277 if gitConfigBool("git-p4.detectCopiesHarder"):
2278 self.diffOpts += " --find-copies-harder"
2280 num_shelves = len(self.update_shelve)
2281 if num_shelves > 0 and num_shelves != len(commits):
2282 sys.exit("number of commits (%d) must match number of shelved changelist (%d)" %
2283 (len(commits), num_shelves))
2285 hooks_path = gitConfig("core.hooksPath")
2286 if len(hooks_path) <= 0:
2287 hooks_path = os.path.join(os.environ.get("GIT_DIR", ".git"), "hooks")
2289 hook_file = os.path.join(hooks_path, "p4-pre-submit")
2290 if os.path.isfile(hook_file) and os.access(hook_file, os.X_OK) and subprocess.call([hook_file]) != 0:
2294 # Apply the commits, one at a time. On failure, ask if should
2295 # continue to try the rest of the patches, or quit.
2298 print("Would apply")
2300 last = len(commits) - 1
2301 for i, commit in enumerate(commits):
2303 print(" ", read_pipe(["git", "show", "-s",
2304 "--format=format:%h %s", commit]))
2307 ok = self.applyCommit(commit)
2309 applied.append(commit)
2311 if self.prepare_p4_only and i < last:
2312 print("Processing only the first commit due to option" \
2313 " --prepare-p4-only")
2318 # prompt for what to do, or use the option/variable
2319 if self.conflict_behavior == "ask":
2320 print("What do you want to do?")
2321 response = raw_input("[s]kip this commit but apply"
2322 " the rest, or [q]uit? ")
2325 elif self.conflict_behavior == "skip":
2327 elif self.conflict_behavior == "quit":
2330 die("Unknown conflict_behavior '%s'" %
2331 self.conflict_behavior)
2333 if response[0] == "s":
2334 print("Skipping this commit, but applying the rest")
2336 if response[0] == "q":
2343 chdir(self.oldWorkingDirectory)
2344 shelved_applied = "shelved" if self.shelve else "applied"
2347 elif self.prepare_p4_only:
2349 elif len(commits) == len(applied):
2350 print("All commits {0}!".format(shelved_applied))
2354 sync.branch = self.branch
2355 if self.disable_p4sync:
2356 sync.sync_origin_only()
2360 if not self.disable_rebase:
2365 if len(applied) == 0:
2366 print("No commits {0}.".format(shelved_applied))
2368 print("{0} only the commits marked with '*':".format(shelved_applied.capitalize()))
2374 print(star, read_pipe(["git", "show", "-s",
2375 "--format=format:%h %s", c]))
2376 print("You will have to do 'git p4 sync' and rebase.")
2378 if gitConfigBool("git-p4.exportLabels"):
2379 self.exportLabels = True
2381 if self.exportLabels:
2382 p4Labels = getP4Labels(self.depotPath)
2383 gitTags = getGitTags()
2385 missingGitTags = gitTags - p4Labels
2386 self.exportGitTags(missingGitTags)
2388 # exit with error unless everything applied perfectly
2389 if len(commits) != len(applied):
2395 """Represent a p4 view ("p4 help views"), and map files in a
2396 repo according to the view."""
2398 def __init__(self, client_name):
2400 self.client_prefix = "//%s/" % client_name
2401 # cache results of "p4 where" to lookup client file locations
2402 self.client_spec_path_cache = {}
2404 def append(self, view_line):
2405 """Parse a view line, splitting it into depot and client
2406 sides. Append to self.mappings, preserving order. This
2407 is only needed for tag creation."""
2409 # Split the view line into exactly two words. P4 enforces
2410 # structure on these lines that simplifies this quite a bit.
2412 # Either or both words may be double-quoted.
2413 # Single quotes do not matter.
2414 # Double-quote marks cannot occur inside the words.
2415 # A + or - prefix is also inside the quotes.
2416 # There are no quotes unless they contain a space.
2417 # The line is already white-space stripped.
2418 # The two words are separated by a single space.
2420 if view_line[0] == '"':
2421 # First word is double quoted. Find its end.
2422 close_quote_index = view_line.find('"', 1)
2423 if close_quote_index <= 0:
2424 die("No first-word closing quote found: %s" % view_line)
2425 depot_side = view_line[1:close_quote_index]
2426 # skip closing quote and space
2427 rhs_index = close_quote_index + 1 + 1
2429 space_index = view_line.find(" ")
2430 if space_index <= 0:
2431 die("No word-splitting space found: %s" % view_line)
2432 depot_side = view_line[0:space_index]
2433 rhs_index = space_index + 1
2435 # prefix + means overlay on previous mapping
2436 if depot_side.startswith("+"):
2437 depot_side = depot_side[1:]
2439 # prefix - means exclude this path, leave out of mappings
2441 if depot_side.startswith("-"):
2443 depot_side = depot_side[1:]
2446 self.mappings.append(depot_side)
2448 def convert_client_path(self, clientFile):
2449 # chop off //client/ part to make it relative
2450 if not clientFile.startswith(self.client_prefix):
2451 die("No prefix '%s' on clientFile '%s'" %
2452 (self.client_prefix, clientFile))
2453 return clientFile[len(self.client_prefix):]
2455 def update_client_spec_path_cache(self, files):
2456 """ Caching file paths by "p4 where" batch query """
2458 # List depot file paths exclude that already cached
2459 fileArgs = [f['path'] for f in files if f['path'] not in self.client_spec_path_cache]
2461 if len(fileArgs) == 0:
2462 return # All files in cache
2464 where_result = p4CmdList(["-x", "-", "where"], stdin=fileArgs)
2465 for res in where_result:
2466 if "code" in res and res["code"] == "error":
2467 # assume error is "... file(s) not in client view"
2469 if "clientFile" not in res:
2470 die("No clientFile in 'p4 where' output")
2472 # it will list all of them, but only one not unmap-ped
2474 if gitConfigBool("core.ignorecase"):
2475 res['depotFile'] = res['depotFile'].lower()
2476 self.client_spec_path_cache[res['depotFile']] = self.convert_client_path(res["clientFile"])
2478 # not found files or unmap files set to ""
2479 for depotFile in fileArgs:
2480 if gitConfigBool("core.ignorecase"):
2481 depotFile = depotFile.lower()
2482 if depotFile not in self.client_spec_path_cache:
2483 self.client_spec_path_cache[depotFile] = ""
2485 def map_in_client(self, depot_path):
2486 """Return the relative location in the client where this
2487 depot file should live. Returns "" if the file should
2488 not be mapped in the client."""
2490 if gitConfigBool("core.ignorecase"):
2491 depot_path = depot_path.lower()
2493 if depot_path in self.client_spec_path_cache:
2494 return self.client_spec_path_cache[depot_path]
2496 die( "Error: %s is not found in client spec path" % depot_path )
2499 def cloneExcludeCallback(option, opt_str, value, parser):
2500 # prepend "/" because the first "/" was consumed as part of the option itself.
2501 # ("-//depot/A/..." becomes "/depot/A/..." after option parsing)
2502 parser.values.cloneExclude += ["/" + re.sub(r"\.\.\.$", "", value)]
2504 class P4Sync(Command, P4UserMap):
2507 Command.__init__(self)
2508 P4UserMap.__init__(self)
2510 optparse.make_option("--branch", dest="branch"),
2511 optparse.make_option("--detect-branches", dest="detectBranches", action="store_true"),
2512 optparse.make_option("--changesfile", dest="changesFile"),
2513 optparse.make_option("--silent", dest="silent", action="store_true"),
2514 optparse.make_option("--detect-labels", dest="detectLabels", action="store_true"),
2515 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
2516 optparse.make_option("--import-local", dest="importIntoRemotes", action="store_false",
2517 help="Import into refs/heads/ , not refs/remotes"),
2518 optparse.make_option("--max-changes", dest="maxChanges",
2519 help="Maximum number of changes to import"),
2520 optparse.make_option("--changes-block-size", dest="changes_block_size", type="int",
2521 help="Internal block size to use when iteratively calling p4 changes"),
2522 optparse.make_option("--keep-path", dest="keepRepoPath", action='store_true',
2523 help="Keep entire BRANCH/DIR/SUBDIR prefix during import"),
2524 optparse.make_option("--use-client-spec", dest="useClientSpec", action='store_true',
2525 help="Only sync files that are included in the Perforce Client Spec"),
2526 optparse.make_option("-/", dest="cloneExclude",
2527 action="callback", callback=cloneExcludeCallback, type="string",
2528 help="exclude depot path"),
2530 self.description = """Imports from Perforce into a git repository.\n
2532 //depot/my/project/ -- to import the current head
2533 //depot/my/project/@all -- to import everything
2534 //depot/my/project/@1,6 -- to import only from revision 1 to 6
2536 (a ... is not needed in the path p4 specification, it's added implicitly)"""
2538 self.usage += " //depot/path[@revRange]"
2540 self.createdBranches = set()
2541 self.committedChanges = set()
2543 self.detectBranches = False
2544 self.detectLabels = False
2545 self.importLabels = False
2546 self.changesFile = ""
2547 self.syncWithOrigin = True
2548 self.importIntoRemotes = True
2549 self.maxChanges = ""
2550 self.changes_block_size = None
2551 self.keepRepoPath = False
2552 self.depotPaths = None
2553 self.p4BranchesInGit = []
2554 self.cloneExclude = []
2555 self.useClientSpec = False
2556 self.useClientSpec_from_options = False
2557 self.clientSpecDirs = None
2558 self.tempBranches = []
2559 self.tempBranchLocation = "refs/git-p4-tmp"
2560 self.largeFileSystem = None
2561 self.suppress_meta_comment = False
2563 if gitConfig('git-p4.largeFileSystem'):
2564 largeFileSystemConstructor = globals()[gitConfig('git-p4.largeFileSystem')]
2565 self.largeFileSystem = largeFileSystemConstructor(
2566 lambda git_mode, relPath, contents: self.writeToGitStream(git_mode, relPath, contents)
2569 if gitConfig("git-p4.syncFromOrigin") == "false":
2570 self.syncWithOrigin = False
2572 self.depotPaths = []
2573 self.changeRange = ""
2574 self.previousDepotPaths = []
2575 self.hasOrigin = False
2577 # map from branch depot path to parent branch
2578 self.knownBranches = {}
2579 self.initialParents = {}
2581 self.tz = "%+03d%02d" % (- time.timezone / 3600, ((- time.timezone % 3600) / 60))
2584 # Force a checkpoint in fast-import and wait for it to finish
2585 def checkpoint(self):
2586 self.gitStream.write("checkpoint\n\n")
2587 self.gitStream.write("progress checkpoint\n\n")
2588 out = self.gitOutput.readline()
2590 print("checkpoint finished: " + out)
2592 def isPathWanted(self, path):
2593 for p in self.cloneExclude:
2595 if p4PathStartsWith(path, p):
2597 # "-//depot/file1" without a trailing "/" should only exclude "file1", but not "file111" or "file1_dir/file2"
2598 elif path.lower() == p.lower():
2600 for p in self.depotPaths:
2601 if p4PathStartsWith(path, p):
2605 def extractFilesFromCommit(self, commit, shelved=False, shelved_cl = 0):
2608 while "depotFile%s" % fnum in commit:
2609 path = commit["depotFile%s" % fnum]
2610 found = self.isPathWanted(path)
2617 file["rev"] = commit["rev%s" % fnum]
2618 file["action"] = commit["action%s" % fnum]
2619 file["type"] = commit["type%s" % fnum]
2621 file["shelved_cl"] = int(shelved_cl)
2626 def extractJobsFromCommit(self, commit):
2629 while "job%s" % jnum in commit:
2630 job = commit["job%s" % jnum]
2635 def stripRepoPath(self, path, prefixes):
2636 """When streaming files, this is called to map a p4 depot path
2637 to where it should go in git. The prefixes are either
2638 self.depotPaths, or self.branchPrefixes in the case of
2639 branch detection."""
2641 if self.useClientSpec:
2642 # branch detection moves files up a level (the branch name)
2643 # from what client spec interpretation gives
2644 path = self.clientSpecDirs.map_in_client(path)
2645 if self.detectBranches:
2646 for b in self.knownBranches:
2647 if p4PathStartsWith(path, b + "/"):
2648 path = path[len(b)+1:]
2650 elif self.keepRepoPath:
2651 # Preserve everything in relative path name except leading
2652 # //depot/; just look at first prefix as they all should
2653 # be in the same depot.
2654 depot = re.sub("^(//[^/]+/).*", r'\1', prefixes[0])
2655 if p4PathStartsWith(path, depot):
2656 path = path[len(depot):]
2660 if p4PathStartsWith(path, p):
2661 path = path[len(p):]
2664 path = wildcard_decode(path)
2667 def splitFilesIntoBranches(self, commit):
2668 """Look at each depotFile in the commit to figure out to what
2669 branch it belongs."""
2671 if self.clientSpecDirs:
2672 files = self.extractFilesFromCommit(commit)
2673 self.clientSpecDirs.update_client_spec_path_cache(files)
2677 while "depotFile%s" % fnum in commit:
2678 path = commit["depotFile%s" % fnum]
2679 found = self.isPathWanted(path)
2686 file["rev"] = commit["rev%s" % fnum]
2687 file["action"] = commit["action%s" % fnum]
2688 file["type"] = commit["type%s" % fnum]
2691 # start with the full relative path where this file would
2693 if self.useClientSpec:
2694 relPath = self.clientSpecDirs.map_in_client(path)
2696 relPath = self.stripRepoPath(path, self.depotPaths)
2698 for branch in self.knownBranches.keys():
2699 # add a trailing slash so that a commit into qt/4.2foo
2700 # doesn't end up in qt/4.2, e.g.
2701 if p4PathStartsWith(relPath, branch + "/"):
2702 if branch not in branches:
2703 branches[branch] = []
2704 branches[branch].append(file)
2709 def writeToGitStream(self, gitMode, relPath, contents):
2710 self.gitStream.write('M %s inline %s\n' % (gitMode, relPath))
2711 self.gitStream.write('data %d\n' % sum(len(d) for d in contents))
2713 self.gitStream.write(d)
2714 self.gitStream.write('\n')
2716 def encodeWithUTF8(self, path):
2718 path.decode('ascii')
2721 if gitConfig('git-p4.pathEncoding'):
2722 encoding = gitConfig('git-p4.pathEncoding')
2723 path = path.decode(encoding, 'replace').encode('utf8', 'replace')
2725 print('Path with non-ASCII characters detected. Used %s to encode: %s ' % (encoding, path))
2728 # output one file from the P4 stream
2729 # - helper for streamP4Files
2731 def streamOneP4File(self, file, contents):
2732 relPath = self.stripRepoPath(file['depotFile'], self.branchPrefixes)
2733 relPath = self.encodeWithUTF8(relPath)
2735 if 'fileSize' in self.stream_file:
2736 size = int(self.stream_file['fileSize'])
2738 size = 0 # deleted files don't get a fileSize apparently
2739 sys.stdout.write('\r%s --> %s (%i MB)\n' % (file['depotFile'], relPath, size/1024/1024))
2742 (type_base, type_mods) = split_p4_type(file["type"])
2745 if "x" in type_mods:
2747 if type_base == "symlink":
2749 # p4 print on a symlink sometimes contains "target\n";
2750 # if it does, remove the newline
2751 data = ''.join(contents)
2753 # Some version of p4 allowed creating a symlink that pointed
2754 # to nothing. This causes p4 errors when checking out such
2755 # a change, and errors here too. Work around it by ignoring
2756 # the bad symlink; hopefully a future change fixes it.
2757 print("\nIgnoring empty symlink in %s" % file['depotFile'])
2759 elif data[-1] == '\n':
2760 contents = [data[:-1]]
2764 if type_base == "utf16":
2765 # p4 delivers different text in the python output to -G
2766 # than it does when using "print -o", or normal p4 client
2767 # operations. utf16 is converted to ascii or utf8, perhaps.
2768 # But ascii text saved as -t utf16 is completely mangled.
2769 # Invoke print -o to get the real contents.
2771 # On windows, the newlines will always be mangled by print, so put
2772 # them back too. This is not needed to the cygwin windows version,
2773 # just the native "NT" type.
2776 text = p4_read_pipe(['print', '-q', '-o', '-', '%s@%s' % (file['depotFile'], file['change'])])
2777 except Exception as e:
2778 if 'Translation of file content failed' in str(e):
2779 type_base = 'binary'
2783 if p4_version_string().find('/NT') >= 0:
2784 text = text.replace('\r\n', '\n')
2787 if type_base == "apple":
2788 # Apple filetype files will be streamed as a concatenation of
2789 # its appledouble header and the contents. This is useless
2790 # on both macs and non-macs. If using "print -q -o xx", it
2791 # will create "xx" with the data, and "%xx" with the header.
2792 # This is also not very useful.
2794 # Ideally, someday, this script can learn how to generate
2795 # appledouble files directly and import those to git, but
2796 # non-mac machines can never find a use for apple filetype.
2797 print("\nIgnoring apple filetype file %s" % file['depotFile'])
2800 # Note that we do not try to de-mangle keywords on utf16 files,
2801 # even though in theory somebody may want that.
2802 pattern = p4_keywords_regexp_for_type(type_base, type_mods)
2804 regexp = re.compile(pattern, re.VERBOSE)
2805 text = ''.join(contents)
2806 text = regexp.sub(r'$\1$', text)
2809 if self.largeFileSystem:
2810 (git_mode, contents) = self.largeFileSystem.processContent(git_mode, relPath, contents)
2812 self.writeToGitStream(git_mode, relPath, contents)
2814 def streamOneP4Deletion(self, file):
2815 relPath = self.stripRepoPath(file['path'], self.branchPrefixes)
2816 relPath = self.encodeWithUTF8(relPath)
2818 sys.stdout.write("delete %s\n" % relPath)
2820 self.gitStream.write("D %s\n" % relPath)
2822 if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):
2823 self.largeFileSystem.removeLargeFile(relPath)
2825 # handle another chunk of streaming data
2826 def streamP4FilesCb(self, marshalled):
2828 # catch p4 errors and complain
2830 if "code" in marshalled:
2831 if marshalled["code"] == "error":
2832 if "data" in marshalled:
2833 err = marshalled["data"].rstrip()
2835 if not err and 'fileSize' in self.stream_file:
2836 required_bytes = int((4 * int(self.stream_file["fileSize"])) - calcDiskFree())
2837 if required_bytes > 0:
2838 err = 'Not enough space left on %s! Free at least %i MB.' % (
2839 os.getcwd(), required_bytes/1024/1024
2844 if self.stream_have_file_info:
2845 if "depotFile" in self.stream_file:
2846 f = self.stream_file["depotFile"]
2847 # force a failure in fast-import, else an empty
2848 # commit will be made
2849 self.gitStream.write("\n")
2850 self.gitStream.write("die-now\n")
2851 self.gitStream.close()
2852 # ignore errors, but make sure it exits first
2853 self.importProcess.wait()
2855 die("Error from p4 print for %s: %s" % (f, err))
2857 die("Error from p4 print: %s" % err)
2859 if 'depotFile' in marshalled and self.stream_have_file_info:
2860 # start of a new file - output the old one first
2861 self.streamOneP4File(self.stream_file, self.stream_contents)
2862 self.stream_file = {}
2863 self.stream_contents = []
2864 self.stream_have_file_info = False
2866 # pick up the new file information... for the
2867 # 'data' field we need to append to our array
2868 for k in marshalled.keys():
2870 if 'streamContentSize' not in self.stream_file:
2871 self.stream_file['streamContentSize'] = 0
2872 self.stream_file['streamContentSize'] += len(marshalled['data'])
2873 self.stream_contents.append(marshalled['data'])
2875 self.stream_file[k] = marshalled[k]
2878 'streamContentSize' in self.stream_file and
2879 'fileSize' in self.stream_file and
2880 'depotFile' in self.stream_file):
2881 size = int(self.stream_file["fileSize"])
2883 progress = 100*self.stream_file['streamContentSize']/size
2884 sys.stdout.write('\r%s %d%% (%i MB)' % (self.stream_file['depotFile'], progress, int(size/1024/1024)))
2887 self.stream_have_file_info = True
2889 # Stream directly from "p4 files" into "git fast-import"
2890 def streamP4Files(self, files):
2896 filesForCommit.append(f)
2897 if f['action'] in self.delete_actions:
2898 filesToDelete.append(f)
2900 filesToRead.append(f)
2903 for f in filesToDelete:
2904 self.streamOneP4Deletion(f)
2906 if len(filesToRead) > 0:
2907 self.stream_file = {}
2908 self.stream_contents = []
2909 self.stream_have_file_info = False
2911 # curry self argument
2912 def streamP4FilesCbSelf(entry):
2913 self.streamP4FilesCb(entry)
2916 for f in filesToRead:
2917 if 'shelved_cl' in f:
2918 # Handle shelved CLs using the "p4 print file@=N" syntax to print
2920 fileArg = '%s@=%d' % (f['path'], f['shelved_cl'])
2922 fileArg = '%s#%s' % (f['path'], f['rev'])
2924 fileArgs.append(fileArg)
2926 p4CmdList(["-x", "-", "print"],
2928 cb=streamP4FilesCbSelf)
2931 if 'depotFile' in self.stream_file:
2932 self.streamOneP4File(self.stream_file, self.stream_contents)
2934 def make_email(self, userid):
2935 if userid in self.users:
2936 return self.users[userid]
2938 return "%s <a@b>" % userid
2940 def streamTag(self, gitStream, labelName, labelDetails, commit, epoch):
2941 """ Stream a p4 tag.
2942 commit is either a git commit, or a fast-import mark, ":<p4commit>"
2946 print("writing tag %s for commit %s" % (labelName, commit))
2947 gitStream.write("tag %s\n" % labelName)
2948 gitStream.write("from %s\n" % commit)
2950 if 'Owner' in labelDetails:
2951 owner = labelDetails["Owner"]
2955 # Try to use the owner of the p4 label, or failing that,
2956 # the current p4 user id.
2958 email = self.make_email(owner)
2960 email = self.make_email(self.p4UserId())
2961 tagger = "%s %s %s" % (email, epoch, self.tz)
2963 gitStream.write("tagger %s\n" % tagger)
2965 print("labelDetails=",labelDetails)
2966 if 'Description' in labelDetails:
2967 description = labelDetails['Description']
2969 description = 'Label from git p4'
2971 gitStream.write("data %d\n" % len(description))
2972 gitStream.write(description)
2973 gitStream.write("\n")
2975 def inClientSpec(self, path):
2976 if not self.clientSpecDirs:
2978 inClientSpec = self.clientSpecDirs.map_in_client(path)
2979 if not inClientSpec and self.verbose:
2980 print('Ignoring file outside of client spec: {0}'.format(path))
2983 def hasBranchPrefix(self, path):
2984 if not self.branchPrefixes:
2986 hasPrefix = [p for p in self.branchPrefixes
2987 if p4PathStartsWith(path, p)]
2988 if not hasPrefix and self.verbose:
2989 print('Ignoring file outside of prefix: {0}'.format(path))
2992 def commit(self, details, files, branch, parent = "", allow_empty=False):
2993 epoch = details["time"]
2994 author = details["user"]
2995 jobs = self.extractJobsFromCommit(details)
2998 print('commit into {0}'.format(branch))
3000 if self.clientSpecDirs:
3001 self.clientSpecDirs.update_client_spec_path_cache(files)
3003 files = [f for f in files
3004 if self.inClientSpec(f['path']) and self.hasBranchPrefix(f['path'])]
3006 if gitConfigBool('git-p4.keepEmptyCommits'):
3009 if not files and not allow_empty:
3010 print('Ignoring revision {0} as it would produce an empty commit.'
3011 .format(details['change']))
3014 self.gitStream.write("commit %s\n" % branch)
3015 self.gitStream.write("mark :%s\n" % details["change"])
3016 self.committedChanges.add(int(details["change"]))
3018 if author not in self.users:
3019 self.getUserMapFromPerforceServer()
3020 committer = "%s %s %s" % (self.make_email(author), epoch, self.tz)
3022 self.gitStream.write("committer %s\n" % committer)
3024 self.gitStream.write("data <<EOT\n")
3025 self.gitStream.write(details["desc"])
3027 self.gitStream.write("\nJobs: %s" % (' '.join(jobs)))
3029 if not self.suppress_meta_comment:
3030 self.gitStream.write("\n[git-p4: depot-paths = \"%s\": change = %s" %
3031 (','.join(self.branchPrefixes), details["change"]))
3032 if len(details['options']) > 0:
3033 self.gitStream.write(": options = %s" % details['options'])
3034 self.gitStream.write("]\n")
3036 self.gitStream.write("EOT\n\n")
3040 print("parent %s" % parent)
3041 self.gitStream.write("from %s\n" % parent)
3043 self.streamP4Files(files)
3044 self.gitStream.write("\n")
3046 change = int(details["change"])
3048 if change in self.labels:
3049 label = self.labels[change]
3050 labelDetails = label[0]
3051 labelRevisions = label[1]
3053 print("Change %s is labelled %s" % (change, labelDetails))
3055 files = p4CmdList(["files"] + ["%s...@%s" % (p, change)
3056 for p in self.branchPrefixes])
3058 if len(files) == len(labelRevisions):
3062 if info["action"] in self.delete_actions:
3064 cleanedFiles[info["depotFile"]] = info["rev"]
3066 if cleanedFiles == labelRevisions:
3067 self.streamTag(self.gitStream, 'tag_%s' % labelDetails['label'], labelDetails, branch, epoch)
3071 print("Tag %s does not match with change %s: files do not match."
3072 % (labelDetails["label"], change))
3076 print("Tag %s does not match with change %s: file count is different."
3077 % (labelDetails["label"], change))
3079 # Build a dictionary of changelists and labels, for "detect-labels" option.
3080 def getLabels(self):
3083 l = p4CmdList(["labels"] + ["%s..." % p for p in self.depotPaths])
3084 if len(l) > 0 and not self.silent:
3085 print("Finding files belonging to labels in %s" % self.depotPaths)
3088 label = output["label"]
3092 print("Querying files for label %s" % label)
3093 for file in p4CmdList(["files"] +
3094 ["%s...@%s" % (p, label)
3095 for p in self.depotPaths]):
3096 revisions[file["depotFile"]] = file["rev"]
3097 change = int(file["change"])
3098 if change > newestChange:
3099 newestChange = change
3101 self.labels[newestChange] = [output, revisions]
3104 print("Label changes: %s" % self.labels.keys())
3106 # Import p4 labels as git tags. A direct mapping does not
3107 # exist, so assume that if all the files are at the same revision
3108 # then we can use that, or it's something more complicated we should
3110 def importP4Labels(self, stream, p4Labels):
3112 print("import p4 labels: " + ' '.join(p4Labels))
3114 ignoredP4Labels = gitConfigList("git-p4.ignoredP4Labels")
3115 validLabelRegexp = gitConfig("git-p4.labelImportRegexp")
3116 if len(validLabelRegexp) == 0:
3117 validLabelRegexp = defaultLabelRegexp
3118 m = re.compile(validLabelRegexp)
3120 for name in p4Labels:
3123 if not m.match(name):
3125 print("label %s does not match regexp %s" % (name,validLabelRegexp))
3128 if name in ignoredP4Labels:
3131 labelDetails = p4CmdList(['label', "-o", name])[0]
3133 # get the most recent changelist for each file in this label
3134 change = p4Cmd(["changes", "-m", "1"] + ["%s...@%s" % (p, name)
3135 for p in self.depotPaths])
3137 if 'change' in change:
3138 # find the corresponding git commit; take the oldest commit
3139 changelist = int(change['change'])
3140 if changelist in self.committedChanges:
3141 gitCommit = ":%d" % changelist # use a fast-import mark
3144 gitCommit = read_pipe(["git", "rev-list", "--max-count=1",
3145 "--reverse", ":/\[git-p4:.*change = %d\]" % changelist], ignore_error=True)
3146 if len(gitCommit) == 0:
3147 print("importing label %s: could not find git commit for changelist %d" % (name, changelist))
3150 gitCommit = gitCommit.strip()
3153 # Convert from p4 time format
3155 tmwhen = time.strptime(labelDetails['Update'], "%Y/%m/%d %H:%M:%S")
3157 print("Could not convert label time %s" % labelDetails['Update'])
3160 when = int(time.mktime(tmwhen))
3161 self.streamTag(stream, name, labelDetails, gitCommit, when)
3163 print("p4 label %s mapped to git commit %s" % (name, gitCommit))
3166 print("Label %s has no changelists - possibly deleted?" % name)
3169 # We can't import this label; don't try again as it will get very
3170 # expensive repeatedly fetching all the files for labels that will
3171 # never be imported. If the label is moved in the future, the
3172 # ignore will need to be removed manually.
3173 system(["git", "config", "--add", "git-p4.ignoredP4Labels", name])
3175 def guessProjectName(self):
3176 for p in self.depotPaths:
3179 p = p[p.strip().rfind("/") + 1:]
3180 if not p.endswith("/"):
3184 def getBranchMapping(self):
3185 lostAndFoundBranches = set()
3187 user = gitConfig("git-p4.branchUser")
3189 command = "branches -u %s" % user
3191 command = "branches"
3193 for info in p4CmdList(command):
3194 details = p4Cmd(["branch", "-o", info["branch"]])
3196 while "View%s" % viewIdx in details:
3197 paths = details["View%s" % viewIdx].split(" ")
3198 viewIdx = viewIdx + 1
3199 # require standard //depot/foo/... //depot/bar/... mapping
3200 if len(paths) != 2 or not paths[0].endswith("/...") or not paths[1].endswith("/..."):
3203 destination = paths[1]
3205 if p4PathStartsWith(source, self.depotPaths[0]) and p4PathStartsWith(destination, self.depotPaths[0]):
3206 source = source[len(self.depotPaths[0]):-4]
3207 destination = destination[len(self.depotPaths[0]):-4]
3209 if destination in self.knownBranches:
3211 print("p4 branch %s defines a mapping from %s to %s" % (info["branch"], source, destination))
3212 print("but there exists another mapping from %s to %s already!" % (self.knownBranches[destination], destination))
3215 self.knownBranches[destination] = source
3217 lostAndFoundBranches.discard(destination)
3219 if source not in self.knownBranches:
3220 lostAndFoundBranches.add(source)
3222 # Perforce does not strictly require branches to be defined, so we also
3223 # check git config for a branch list.
3225 # Example of branch definition in git config file:
3227 # branchList=main:branchA
3228 # branchList=main:branchB
3229 # branchList=branchA:branchC
3230 configBranches = gitConfigList("git-p4.branchList")
3231 for branch in configBranches:
3233 (source, destination) = branch.split(":")
3234 self.knownBranches[destination] = source
3236 lostAndFoundBranches.discard(destination)
3238 if source not in self.knownBranches:
3239 lostAndFoundBranches.add(source)
3242 for branch in lostAndFoundBranches:
3243 self.knownBranches[branch] = branch
3245 def getBranchMappingFromGitBranches(self):
3246 branches = p4BranchesInGit(self.importIntoRemotes)
3247 for branch in branches.keys():
3248 if branch == "master":
3251 branch = branch[len(self.projectName):]
3252 self.knownBranches[branch] = branch
3254 def updateOptionDict(self, d):
3256 if self.keepRepoPath:
3257 option_keys['keepRepoPath'] = 1
3259 d["options"] = ' '.join(sorted(option_keys.keys()))
3261 def readOptions(self, d):
3262 self.keepRepoPath = ('options' in d
3263 and ('keepRepoPath' in d['options']))
3265 def gitRefForBranch(self, branch):
3266 if branch == "main":
3267 return self.refPrefix + "master"
3269 if len(branch) <= 0:
3272 return self.refPrefix + self.projectName + branch
3274 def gitCommitByP4Change(self, ref, change):
3276 print("looking in ref " + ref + " for change %s using bisect..." % change)
3279 latestCommit = parseRevision(ref)
3283 print("trying: earliest %s latest %s" % (earliestCommit, latestCommit))
3284 next = read_pipe("git rev-list --bisect %s %s" % (latestCommit, earliestCommit)).strip()
3289 log = extractLogMessageFromGitCommit(next)
3290 settings = extractSettingsGitLog(log)
3291 currentChange = int(settings['change'])
3293 print("current change %s" % currentChange)
3295 if currentChange == change:
3297 print("found %s" % next)
3300 if currentChange < change:
3301 earliestCommit = "^%s" % next
3303 if next == latestCommit:
3304 die("Infinite loop while looking in ref %s for change %s. Check your branch mappings" % (ref, change))
3305 latestCommit = "%s^@" % next
3309 def importNewBranch(self, branch, maxChange):
3310 # make fast-import flush all changes to disk and update the refs using the checkpoint
3311 # command so that we can try to find the branch parent in the git history
3312 self.gitStream.write("checkpoint\n\n");
3313 self.gitStream.flush();
3314 branchPrefix = self.depotPaths[0] + branch + "/"
3315 range = "@1,%s" % maxChange
3316 #print "prefix" + branchPrefix
3317 changes = p4ChangesForPaths([branchPrefix], range, self.changes_block_size)
3318 if len(changes) <= 0:
3320 firstChange = changes[0]
3321 #print "first change in branch: %s" % firstChange
3322 sourceBranch = self.knownBranches[branch]
3323 sourceDepotPath = self.depotPaths[0] + sourceBranch
3324 sourceRef = self.gitRefForBranch(sourceBranch)
3325 #print "source " + sourceBranch
3327 branchParentChange = int(p4Cmd(["changes", "-m", "1", "%s...@1,%s" % (sourceDepotPath, firstChange)])["change"])
3328 #print "branch parent: %s" % branchParentChange
3329 gitParent = self.gitCommitByP4Change(sourceRef, branchParentChange)
3330 if len(gitParent) > 0:
3331 self.initialParents[self.gitRefForBranch(branch)] = gitParent
3332 #print "parent git commit: %s" % gitParent
3334 self.importChanges(changes)
3337 def searchParent(self, parent, branch, target):
3339 for blob in read_pipe_lines(["git", "rev-list", "--reverse",
3340 "--no-merges", parent]):
3342 if len(read_pipe(["git", "diff-tree", blob, target])) == 0:
3345 print("Found parent of %s in commit %s" % (branch, blob))
3352 def importChanges(self, changes, origin_revision=0):
3354 for change in changes:
3355 description = p4_describe(change)
3356 self.updateOptionDict(description)
3359 sys.stdout.write("\rImporting revision %s (%s%%)" % (change, cnt * 100 / len(changes)))
3364 if self.detectBranches:
3365 branches = self.splitFilesIntoBranches(description)
3366 for branch in branches.keys():
3368 branchPrefix = self.depotPaths[0] + branch + "/"
3369 self.branchPrefixes = [ branchPrefix ]
3373 filesForCommit = branches[branch]
3376 print("branch is %s" % branch)
3378 self.updatedBranches.add(branch)
3380 if branch not in self.createdBranches:
3381 self.createdBranches.add(branch)
3382 parent = self.knownBranches[branch]
3383 if parent == branch:
3386 fullBranch = self.projectName + branch
3387 if fullBranch not in self.p4BranchesInGit:
3389 print("\n Importing new branch %s" % fullBranch);
3390 if self.importNewBranch(branch, change - 1):
3392 self.p4BranchesInGit.append(fullBranch)
3394 print("\n Resuming with change %s" % change);
3397 print("parent determined through known branches: %s" % parent)
3399 branch = self.gitRefForBranch(branch)
3400 parent = self.gitRefForBranch(parent)
3403 print("looking for initial parent for %s; current parent is %s" % (branch, parent))
3405 if len(parent) == 0 and branch in self.initialParents:
3406 parent = self.initialParents[branch]
3407 del self.initialParents[branch]
3411 tempBranch = "%s/%d" % (self.tempBranchLocation, change)
3413 print("Creating temporary branch: " + tempBranch)
3414 self.commit(description, filesForCommit, tempBranch)
3415 self.tempBranches.append(tempBranch)
3417 blob = self.searchParent(parent, branch, tempBranch)
3419 self.commit(description, filesForCommit, branch, blob)
3422 print("Parent of %s not found. Committing into head of %s" % (branch, parent))
3423 self.commit(description, filesForCommit, branch, parent)
3425 files = self.extractFilesFromCommit(description)
3426 self.commit(description, files, self.branch,
3428 # only needed once, to connect to the previous commit
3429 self.initialParent = ""
3431 print(self.gitError.read())
3434 def sync_origin_only(self):
3435 if self.syncWithOrigin:
3436 self.hasOrigin = originP4BranchesExist()
3439 print('Syncing with origin first, using "git fetch origin"')
3440 system("git fetch origin")
3442 def importHeadRevision(self, revision):
3443 print("Doing initial import of %s from revision %s into %s" % (' '.join(self.depotPaths), revision, self.branch))
3446 details["user"] = "git perforce import user"
3447 details["desc"] = ("Initial import of %s from the state at revision %s\n"
3448 % (' '.join(self.depotPaths), revision))
3449 details["change"] = revision
3453 fileArgs = ["%s...%s" % (p,revision) for p in self.depotPaths]
3455 for info in p4CmdList(["files"] + fileArgs):
3457 if 'code' in info and info['code'] == 'error':
3458 sys.stderr.write("p4 returned an error: %s\n"
3460 if info['data'].find("must refer to client") >= 0:
3461 sys.stderr.write("This particular p4 error is misleading.\n")
3462 sys.stderr.write("Perhaps the depot path was misspelled.\n");
3463 sys.stderr.write("Depot path: %s\n" % " ".join(self.depotPaths))
3465 if 'p4ExitCode' in info:
3466 sys.stderr.write("p4 exitcode: %s\n" % info['p4ExitCode'])
3470 change = int(info["change"])
3471 if change > newestRevision:
3472 newestRevision = change
3474 if info["action"] in self.delete_actions:
3475 # don't increase the file cnt, otherwise details["depotFile123"] will have gaps!
3476 #fileCnt = fileCnt + 1
3479 for prop in ["depotFile", "rev", "action", "type" ]:
3480 details["%s%s" % (prop, fileCnt)] = info[prop]
3482 fileCnt = fileCnt + 1
3484 details["change"] = newestRevision
3486 # Use time from top-most change so that all git p4 clones of
3487 # the same p4 repo have the same commit SHA1s.
3488 res = p4_describe(newestRevision)
3489 details["time"] = res["time"]
3491 self.updateOptionDict(details)
3493 self.commit(details, self.extractFilesFromCommit(details), self.branch)
3494 except IOError as err:
3495 print("IO error with git fast-import. Is your git version recent enough?")
3496 print("IO error details: {}".format(err))
3497 print(self.gitError.read())
3499 def openStreams(self):
3500 self.importProcess = subprocess.Popen(["git", "fast-import"],
3501 stdin=subprocess.PIPE,
3502 stdout=subprocess.PIPE,
3503 stderr=subprocess.PIPE);
3504 self.gitOutput = self.importProcess.stdout
3505 self.gitStream = self.importProcess.stdin
3506 self.gitError = self.importProcess.stderr
3508 def closeStreams(self):
3509 self.gitStream.close()
3510 if self.importProcess.wait() != 0:
3511 die("fast-import failed: %s" % self.gitError.read())
3512 self.gitOutput.close()
3513 self.gitError.close()
3515 def run(self, args):
3516 if self.importIntoRemotes:
3517 self.refPrefix = "refs/remotes/p4/"
3519 self.refPrefix = "refs/heads/p4/"
3521 self.sync_origin_only()
3523 branch_arg_given = bool(self.branch)
3524 if len(self.branch) == 0:
3525 self.branch = self.refPrefix + "master"
3526 if gitBranchExists("refs/heads/p4") and self.importIntoRemotes:
3527 system("git update-ref %s refs/heads/p4" % self.branch)
3528 system("git branch -D p4")
3530 # accept either the command-line option, or the configuration variable
3531 if self.useClientSpec:
3532 # will use this after clone to set the variable
3533 self.useClientSpec_from_options = True
3535 if gitConfigBool("git-p4.useclientspec"):
3536 self.useClientSpec = True
3537 if self.useClientSpec:
3538 self.clientSpecDirs = getClientSpec()
3540 # TODO: should always look at previous commits,
3541 # merge with previous imports, if possible.
3544 createOrUpdateBranchesFromOrigin(self.refPrefix, self.silent)
3546 # branches holds mapping from branch name to sha1
3547 branches = p4BranchesInGit(self.importIntoRemotes)
3549 # restrict to just this one, disabling detect-branches
3550 if branch_arg_given:
3551 short = self.branch.split("/")[-1]
3552 if short in branches:
3553 self.p4BranchesInGit = [ short ]
3555 self.p4BranchesInGit = branches.keys()
3557 if len(self.p4BranchesInGit) > 1:
3559 print("Importing from/into multiple branches")
3560 self.detectBranches = True
3561 for branch in branches.keys():
3562 self.initialParents[self.refPrefix + branch] = \
3566 print("branches: %s" % self.p4BranchesInGit)
3569 for branch in self.p4BranchesInGit:
3570 logMsg = extractLogMessageFromGitCommit(self.refPrefix + branch)
3572 settings = extractSettingsGitLog(logMsg)
3574 self.readOptions(settings)
3575 if ('depot-paths' in settings
3576 and 'change' in settings):
3577 change = int(settings['change']) + 1
3578 p4Change = max(p4Change, change)
3580 depotPaths = sorted(settings['depot-paths'])
3581 if self.previousDepotPaths == []:
3582 self.previousDepotPaths = depotPaths
3585 for (prev, cur) in zip(self.previousDepotPaths, depotPaths):
3586 prev_list = prev.split("/")
3587 cur_list = cur.split("/")
3588 for i in range(0, min(len(cur_list), len(prev_list))):
3589 if cur_list[i] != prev_list[i]:
3593 paths.append ("/".join(cur_list[:i + 1]))
3595 self.previousDepotPaths = paths
3598 self.depotPaths = sorted(self.previousDepotPaths)
3599 self.changeRange = "@%s,#head" % p4Change
3600 if not self.silent and not self.detectBranches:
3601 print("Performing incremental import into %s git branch" % self.branch)
3603 # accept multiple ref name abbreviations:
3604 # refs/foo/bar/branch -> use it exactly
3605 # p4/branch -> prepend refs/remotes/ or refs/heads/
3606 # branch -> prepend refs/remotes/p4/ or refs/heads/p4/
3607 if not self.branch.startswith("refs/"):
3608 if self.importIntoRemotes:
3609 prepend = "refs/remotes/"
3611 prepend = "refs/heads/"
3612 if not self.branch.startswith("p4/"):
3614 self.branch = prepend + self.branch
3616 if len(args) == 0 and self.depotPaths:
3618 print("Depot paths: %s" % ' '.join(self.depotPaths))
3620 if self.depotPaths and self.depotPaths != args:
3621 print("previous import used depot path %s and now %s was specified. "
3622 "This doesn't work!" % (' '.join (self.depotPaths),
3626 self.depotPaths = sorted(args)
3631 # Make sure no revision specifiers are used when --changesfile
3633 bad_changesfile = False
3634 if len(self.changesFile) > 0:
3635 for p in self.depotPaths:
3636 if p.find("@") >= 0 or p.find("#") >= 0:
3637 bad_changesfile = True
3640 die("Option --changesfile is incompatible with revision specifiers")
3643 for p in self.depotPaths:
3644 if p.find("@") != -1:
3645 atIdx = p.index("@")
3646 self.changeRange = p[atIdx:]
3647 if self.changeRange == "@all":
3648 self.changeRange = ""
3649 elif ',' not in self.changeRange:
3650 revision = self.changeRange
3651 self.changeRange = ""
3653 elif p.find("#") != -1:
3654 hashIdx = p.index("#")
3655 revision = p[hashIdx:]
3657 elif self.previousDepotPaths == []:
3658 # pay attention to changesfile, if given, else import
3659 # the entire p4 tree at the head revision
3660 if len(self.changesFile) == 0:
3663 p = re.sub ("\.\.\.$", "", p)
3664 if not p.endswith("/"):
3669 self.depotPaths = newPaths
3671 # --detect-branches may change this for each branch
3672 self.branchPrefixes = self.depotPaths
3674 self.loadUserMapFromCache()
3676 if self.detectLabels:
3679 if self.detectBranches:
3680 ## FIXME - what's a P4 projectName ?
3681 self.projectName = self.guessProjectName()
3684 self.getBranchMappingFromGitBranches()
3686 self.getBranchMapping()
3688 print("p4-git branches: %s" % self.p4BranchesInGit)
3689 print("initial parents: %s" % self.initialParents)
3690 for b in self.p4BranchesInGit:
3694 b = b[len(self.projectName):]
3695 self.createdBranches.add(b)
3700 self.importHeadRevision(revision)
3704 if len(self.changesFile) > 0:
3705 output = open(self.changesFile).readlines()
3708 changeSet.add(int(line))
3710 for change in changeSet:
3711 changes.append(change)
3715 # catch "git p4 sync" with no new branches, in a repo that
3716 # does not have any existing p4 branches
3718 if not self.p4BranchesInGit:
3719 die("No remote p4 branches. Perhaps you never did \"git p4 clone\" in here.")
3721 # The default branch is master, unless --branch is used to
3722 # specify something else. Make sure it exists, or complain
3723 # nicely about how to use --branch.
3724 if not self.detectBranches:
3725 if not branch_exists(self.branch):
3726 if branch_arg_given:
3727 die("Error: branch %s does not exist." % self.branch)
3729 die("Error: no branch %s; perhaps specify one with --branch." %
3733 print("Getting p4 changes for %s...%s" % (', '.join(self.depotPaths),
3735 changes = p4ChangesForPaths(self.depotPaths, self.changeRange, self.changes_block_size)
3737 if len(self.maxChanges) > 0:
3738 changes = changes[:min(int(self.maxChanges), len(changes))]
3740 if len(changes) == 0:
3742 print("No changes to import!")
3744 if not self.silent and not self.detectBranches:
3745 print("Import destination: %s" % self.branch)
3747 self.updatedBranches = set()
3749 if not self.detectBranches:
3751 # start a new branch
3752 self.initialParent = ""
3754 # build on a previous revision
3755 self.initialParent = parseRevision(self.branch)
3757 self.importChanges(changes)
3761 if len(self.updatedBranches) > 0:
3762 sys.stdout.write("Updated branches: ")
3763 for b in self.updatedBranches:
3764 sys.stdout.write("%s " % b)
3765 sys.stdout.write("\n")
3767 if gitConfigBool("git-p4.importLabels"):
3768 self.importLabels = True
3770 if self.importLabels:
3771 p4Labels = getP4Labels(self.depotPaths)
3772 gitTags = getGitTags()
3774 missingP4Labels = p4Labels - gitTags
3775 self.importP4Labels(self.gitStream, missingP4Labels)
3779 # Cleanup temporary branches created during import
3780 if self.tempBranches != []:
3781 for branch in self.tempBranches:
3782 read_pipe("git update-ref -d %s" % branch)
3783 os.rmdir(os.path.join(os.environ.get("GIT_DIR", ".git"), self.tempBranchLocation))
3785 # Create a symbolic ref p4/HEAD pointing to p4/<branch> to allow
3786 # a convenient shortcut refname "p4".
3787 if self.importIntoRemotes:
3788 head_ref = self.refPrefix + "HEAD"
3789 if not gitBranchExists(head_ref) and gitBranchExists(self.branch):
3790 system(["git", "symbolic-ref", head_ref, self.branch])
3794 class P4Rebase(Command):
3796 Command.__init__(self)
3798 optparse.make_option("--import-labels", dest="importLabels", action="store_true"),
3800 self.importLabels = False
3801 self.description = ("Fetches the latest revision from perforce and "
3802 + "rebases the current work (branch) against it")
3804 def run(self, args):
3806 sync.importLabels = self.importLabels
3809 return self.rebase()
3812 if os.system("git update-index --refresh") != 0:
3813 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.");
3814 if len(read_pipe("git diff-index HEAD --")) > 0:
3815 die("You have uncommitted changes. Please commit them before rebasing or stash them away with git stash.");
3817 [upstream, settings] = findUpstreamBranchPoint()
3818 if len(upstream) == 0:
3819 die("Cannot find upstream branchpoint for rebase")
3821 # the branchpoint may be p4/foo~3, so strip off the parent
3822 upstream = re.sub("~[0-9]+$", "", upstream)
3824 print("Rebasing the current branch onto %s" % upstream)
3825 oldHead = read_pipe("git rev-parse HEAD").strip()
3826 system("git rebase %s" % upstream)
3827 system("git diff-tree --stat --summary -M %s HEAD --" % oldHead)
3830 class P4Clone(P4Sync):
3832 P4Sync.__init__(self)
3833 self.description = "Creates a new git repository and imports from Perforce into it"
3834 self.usage = "usage: %prog [options] //depot/path[@revRange]"
3836 optparse.make_option("--destination", dest="cloneDestination",
3837 action='store', default=None,
3838 help="where to leave result of the clone"),
3839 optparse.make_option("--bare", dest="cloneBare",
3840 action="store_true", default=False),
3842 self.cloneDestination = None
3843 self.needsGit = False
3844 self.cloneBare = False
3846 def defaultDestination(self, args):
3847 ## TODO: use common prefix of args?
3849 depotDir = re.sub("(@[^@]*)$", "", depotPath)
3850 depotDir = re.sub("(#[^#]*)$", "", depotDir)
3851 depotDir = re.sub(r"\.\.\.$", "", depotDir)
3852 depotDir = re.sub(r"/$", "", depotDir)
3853 return os.path.split(depotDir)[1]
3855 def run(self, args):
3859 if self.keepRepoPath and not self.cloneDestination:
3860 sys.stderr.write("Must specify destination for --keep-path\n")
3865 if not self.cloneDestination and len(depotPaths) > 1:
3866 self.cloneDestination = depotPaths[-1]
3867 depotPaths = depotPaths[:-1]
3869 for p in depotPaths:
3870 if not p.startswith("//"):
3871 sys.stderr.write('Depot paths must start with "//": %s\n' % p)
3874 if not self.cloneDestination:
3875 self.cloneDestination = self.defaultDestination(args)
3877 print("Importing from %s into %s" % (', '.join(depotPaths), self.cloneDestination))
3879 if not os.path.exists(self.cloneDestination):
3880 os.makedirs(self.cloneDestination)
3881 chdir(self.cloneDestination)
3883 init_cmd = [ "git", "init" ]
3885 init_cmd.append("--bare")
3886 retcode = subprocess.call(init_cmd)
3888 raise CalledProcessError(retcode, init_cmd)
3890 if not P4Sync.run(self, depotPaths):
3893 # create a master branch and check out a work tree
3894 if gitBranchExists(self.branch):
3895 system([ "git", "branch", "master", self.branch ])
3896 if not self.cloneBare:
3897 system([ "git", "checkout", "-f" ])
3899 print('Not checking out any branch, use ' \
3900 '"git checkout -q -b master <branch>"')
3902 # auto-set this variable if invoked with --use-client-spec
3903 if self.useClientSpec_from_options:
3904 system("git config --bool git-p4.useclientspec true")
3908 class P4Unshelve(Command):
3910 Command.__init__(self)
3912 self.origin = "HEAD"
3913 self.description = "Unshelve a P4 changelist into a git commit"
3914 self.usage = "usage: %prog [options] changelist"
3916 optparse.make_option("--origin", dest="origin",
3917 help="Use this base revision instead of the default (%s)" % self.origin),
3919 self.verbose = False
3920 self.noCommit = False
3921 self.destbranch = "refs/remotes/p4-unshelved"
3923 def renameBranch(self, branch_name):
3924 """ Rename the existing branch to branch_name.N
3928 for i in range(0,1000):
3929 backup_branch_name = "{0}.{1}".format(branch_name, i)
3930 if not gitBranchExists(backup_branch_name):
3931 gitUpdateRef(backup_branch_name, branch_name) # copy ref to backup
3932 gitDeleteRef(branch_name)
3934 print("renamed old unshelve branch to {0}".format(backup_branch_name))
3938 sys.exit("gave up trying to rename existing branch {0}".format(sync.branch))
3940 def findLastP4Revision(self, starting_point):
3941 """ Look back from starting_point for the first commit created by git-p4
3942 to find the P4 commit we are based on, and the depot-paths.
3945 for parent in (range(65535)):
3946 log = extractLogMessageFromGitCommit("{0}^{1}".format(starting_point, parent))
3947 settings = extractSettingsGitLog(log)
3948 if 'change' in settings:
3951 sys.exit("could not find git-p4 commits in {0}".format(self.origin))
3953 def createShelveParent(self, change, branch_name, sync, origin):
3954 """ Create a commit matching the parent of the shelved changelist 'change'
3956 parent_description = p4_describe(change, shelved=True)
3957 parent_description['desc'] = 'parent for shelved changelist {}\n'.format(change)
3958 files = sync.extractFilesFromCommit(parent_description, shelved=False, shelved_cl=change)
3962 # if it was added in the shelved changelist, it won't exist in the parent
3963 if f['action'] in self.add_actions:
3966 # if it was deleted in the shelved changelist it must not be deleted
3967 # in the parent - we might even need to create it if the origin branch
3969 if f['action'] in self.delete_actions:
3972 parent_files.append(f)
3974 sync.commit(parent_description, parent_files, branch_name,
3975 parent=origin, allow_empty=True)
3976 print("created parent commit for {0} based on {1} in {2}".format(
3977 change, self.origin, branch_name))
3979 def run(self, args):
3983 if not gitBranchExists(self.origin):
3984 sys.exit("origin branch {0} does not exist".format(self.origin))
3989 # only one change at a time
3992 # if the target branch already exists, rename it
3993 branch_name = "{0}/{1}".format(self.destbranch, change)
3994 if gitBranchExists(branch_name):
3995 self.renameBranch(branch_name)
3996 sync.branch = branch_name
3998 sync.verbose = self.verbose
3999 sync.suppress_meta_comment = True
4001 settings = self.findLastP4Revision(self.origin)
4002 sync.depotPaths = settings['depot-paths']
4003 sync.branchPrefixes = sync.depotPaths
4006 sync.loadUserMapFromCache()
4009 # create a commit for the parent of the shelved changelist
4010 self.createShelveParent(change, branch_name, sync, self.origin)
4012 # create the commit for the shelved changelist itself
4013 description = p4_describe(change, True)
4014 files = sync.extractFilesFromCommit(description, True, change)
4016 sync.commit(description, files, branch_name, "")
4019 print("unshelved changelist {0} into {1}".format(change, branch_name))
4023 class P4Branches(Command):
4025 Command.__init__(self)
4027 self.description = ("Shows the git branches that hold imports and their "
4028 + "corresponding perforce depot paths")
4029 self.verbose = False
4031 def run(self, args):
4032 if originP4BranchesExist():
4033 createOrUpdateBranchesFromOrigin()
4035 cmdline = "git rev-parse --symbolic "
4036 cmdline += " --remotes"
4038 for line in read_pipe_lines(cmdline):
4041 if not line.startswith('p4/') or line == "p4/HEAD":
4045 log = extractLogMessageFromGitCommit("refs/remotes/%s" % branch)
4046 settings = extractSettingsGitLog(log)
4048 print("%s <= %s (%s)" % (branch, ",".join(settings["depot-paths"]), settings["change"]))
4051 class HelpFormatter(optparse.IndentedHelpFormatter):
4053 optparse.IndentedHelpFormatter.__init__(self)
4055 def format_description(self, description):
4057 return description + "\n"
4061 def printUsage(commands):
4062 print("usage: %s <command> [options]" % sys.argv[0])
4064 print("valid commands: %s" % ", ".join(commands))
4066 print("Try %s <command> --help for command specific help." % sys.argv[0])
4071 "submit" : P4Submit,
4072 "commit" : P4Submit,
4074 "rebase" : P4Rebase,
4076 "rollback" : P4RollBack,
4077 "branches" : P4Branches,
4078 "unshelve" : P4Unshelve,
4083 if len(sys.argv[1:]) == 0:
4084 printUsage(commands.keys())
4087 cmdName = sys.argv[1]
4089 klass = commands[cmdName]
4092 print("unknown command %s" % cmdName)
4094 printUsage(commands.keys())
4097 options = cmd.options
4098 cmd.gitdir = os.environ.get("GIT_DIR", None)
4102 options.append(optparse.make_option("--verbose", "-v", dest="verbose", action="store_true"))
4104 options.append(optparse.make_option("--git-dir", dest="gitdir"))
4106 parser = optparse.OptionParser(cmd.usage.replace("%prog", "%prog " + cmdName),
4108 description = cmd.description,
4109 formatter = HelpFormatter())
4111 (cmd, args) = parser.parse_args(sys.argv[2:], cmd);
4113 verbose = cmd.verbose
4115 if cmd.gitdir == None:
4116 cmd.gitdir = os.path.abspath(".git")
4117 if not isValidGitDir(cmd.gitdir):
4118 # "rev-parse --git-dir" without arguments will try $PWD/.git
4119 cmd.gitdir = read_pipe("git rev-parse --git-dir").strip()
4120 if os.path.exists(cmd.gitdir):
4121 cdup = read_pipe("git rev-parse --show-cdup").strip()
4125 if not isValidGitDir(cmd.gitdir):
4126 if isValidGitDir(cmd.gitdir + "/.git"):
4127 cmd.gitdir += "/.git"
4129 die("fatal: cannot locate git repository at %s" % cmd.gitdir)
4131 # so git commands invoked from the P4 workspace will succeed
4132 os.environ["GIT_DIR"] = cmd.gitdir
4134 if not cmd.run(args):
4139 if __name__ == '__main__':