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