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