Skip to content

Commit 6cec21a

Browse files
yangskyboxlabsgitster
authored andcommitted
git-p4: encode/decode communication with p4 for python3
The marshalled dict in the response given on STDOUT by p4 uses `str` for keys and string values. When run using python3, these values are deserialized as `bytes`, leading to a whole host of problems as the rest of the code assumes `str` is used throughout. This patch changes the deserialization behaviour such that, as much as possible, text output from p4 is decoded to native unicode strings. Exceptions are made for the field `data` as it is usually arbitrary binary data. `depotFile[0-9]*`, `path`, and `clientFile` are also exempt as they contain path strings not encoded with UTF-8, and must survive round-trip back to p4. Conversely, text data being piped to p4 must always be encoded when running under python3. encode_text_stream() and decode_text_stream() were added to make these transformations more convenient. Signed-off-by: Yang Zhao <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 1f8b46d commit 6cec21a

File tree

1 file changed

+46
-13
lines changed

1 file changed

+46
-13
lines changed

git-p4.py

Lines changed: 46 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -135,6 +135,21 @@ def die(msg):
135135
sys.stderr.write(msg + "\n")
136136
sys.exit(1)
137137

138+
# We need different encoding/decoding strategies for text data being passed
139+
# around in pipes depending on python version
140+
if bytes is not str:
141+
# For python3, always encode and decode as appropriate
142+
def decode_text_stream(s):
143+
return s.decode() if isinstance(s, bytes) else s
144+
def encode_text_stream(s):
145+
return s.encode() if isinstance(s, str) else s
146+
else:
147+
# For python2.7, pass read strings as-is, but also allow writing unicode
148+
def decode_text_stream(s):
149+
return s
150+
def encode_text_stream(s):
151+
return s.encode('utf_8') if isinstance(s, unicode) else s
152+
138153
def write_pipe(c, stdin):
139154
if verbose:
140155
sys.stderr.write('Writing pipe: %s\n' % str(c))
@@ -151,6 +166,8 @@ def write_pipe(c, stdin):
151166

152167
def p4_write_pipe(c, stdin):
153168
real_cmd = p4_build_cmd(c)
169+
if bytes is not str and isinstance(stdin, str):
170+
stdin = encode_text_stream(stdin)
154171
return write_pipe(real_cmd, stdin)
155172

156173
def read_pipe_full(c):
@@ -164,7 +181,7 @@ def read_pipe_full(c):
164181
expand = not isinstance(c, list)
165182
p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand)
166183
(out, err) = p.communicate()
167-
return (p.returncode, out, err)
184+
return (p.returncode, out, decode_text_stream(err))
168185

169186
def read_pipe(c, ignore_error=False):
170187
""" Read output from command. Returns the output text on
@@ -187,11 +204,11 @@ def read_pipe_text(c):
187204
if retcode != 0:
188205
return None
189206
else:
190-
return out.rstrip()
207+
return decode_text_stream(out).rstrip()
191208

192-
def p4_read_pipe(c, ignore_error=False):
209+
def p4_read_pipe(c, ignore_error=False, raw=False):
193210
real_cmd = p4_build_cmd(c)
194-
return read_pipe(real_cmd, ignore_error)
211+
return read_pipe(real_cmd, ignore_error, raw=raw)
195212

196213
def read_pipe_lines(c):
197214
if verbose:
@@ -200,7 +217,7 @@ def read_pipe_lines(c):
200217
expand = not isinstance(c, list)
201218
p = subprocess.Popen(c, stdout=subprocess.PIPE, shell=expand)
202219
pipe = p.stdout
203-
val = pipe.readlines()
220+
val = [decode_text_stream(line) for line in pipe.readlines()]
204221
if pipe.close() or p.wait():
205222
die('Command failed: %s' % str(c))
206223

@@ -231,6 +248,7 @@ def p4_has_move_command():
231248
cmd = p4_build_cmd(["move", "-k", "@from", "@to"])
232249
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
233250
(out, err) = p.communicate()
251+
err = decode_text_stream(err)
234252
# return code will be 1 in either case
235253
if err.find("Invalid option") >= 0:
236254
return False
@@ -611,6 +629,20 @@ def p4CmdList(cmd, stdin=None, stdin_mode='w+b', cb=None, skip_info=False,
611629
try:
612630
while True:
613631
entry = marshal.load(p4.stdout)
632+
if bytes is not str:
633+
# Decode unmarshalled dict to use str keys and values, except for:
634+
# - `data` which may contain arbitrary binary data
635+
# - `depotFile[0-9]*`, `path`, or `clientFile` which may contain non-UTF8 encoded text
636+
decoded_entry = {}
637+
for key, value in entry.items():
638+
key = key.decode()
639+
if isinstance(value, bytes) and not (key in ('data', 'path', 'clientFile') or key.startswith('depotFile')):
640+
value = value.decode()
641+
decoded_entry[key] = value
642+
# Parse out data if it's an error response
643+
if decoded_entry.get('code') == 'error' and 'data' in decoded_entry:
644+
decoded_entry['data'] = decoded_entry['data'].decode()
645+
entry = decoded_entry
614646
if skip_info:
615647
if 'code' in entry and entry['code'] == 'info':
616648
continue
@@ -828,6 +860,7 @@ def branch_exists(branch):
828860
cmd = [ "git", "rev-parse", "--symbolic", "--verify", branch ]
829861
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
830862
out, _ = p.communicate()
863+
out = decode_text_stream(out)
831864
if p.returncode:
832865
return False
833866
# expect exactly one line of output: the branch name
@@ -1971,7 +2004,7 @@ def applyCommit(self, id):
19712004
tmpFile = os.fdopen(handle, "w+b")
19722005
if self.isWindows:
19732006
submitTemplate = submitTemplate.replace("\n", "\r\n")
1974-
tmpFile.write(submitTemplate)
2007+
tmpFile.write(encode_text_stream(submitTemplate))
19752008
tmpFile.close()
19762009

19772010
if self.prepare_p4_only:
@@ -2018,7 +2051,7 @@ def applyCommit(self, id):
20182051
if self.edit_template(fileName):
20192052
# read the edited message and submit
20202053
tmpFile = open(fileName, "rb")
2021-
message = tmpFile.read()
2054+
message = decode_text_stream(tmpFile.read())
20222055
tmpFile.close()
20232056
if self.isWindows:
20242057
message = message.replace("\r\n", "\n")
@@ -2707,7 +2740,7 @@ def splitFilesIntoBranches(self, commit):
27072740
return branches
27082741

27092742
def writeToGitStream(self, gitMode, relPath, contents):
2710-
self.gitStream.write('M %s inline %s\n' % (gitMode, relPath))
2743+
self.gitStream.write(encode_text_stream(u'M {} inline {}\n'.format(gitMode, relPath)))
27112744
self.gitStream.write('data %d\n' % sum(len(d) for d in contents))
27122745
for d in contents:
27132746
self.gitStream.write(d)
@@ -2748,7 +2781,7 @@ def streamOneP4File(self, file, contents):
27482781
git_mode = "120000"
27492782
# p4 print on a symlink sometimes contains "target\n";
27502783
# if it does, remove the newline
2751-
data = ''.join(contents)
2784+
data = ''.join(decode_text_stream(c) for c in contents)
27522785
if not data:
27532786
# Some version of p4 allowed creating a symlink that pointed
27542787
# to nothing. This causes p4 errors when checking out such
@@ -2802,7 +2835,7 @@ def streamOneP4File(self, file, contents):
28022835
pattern = p4_keywords_regexp_for_type(type_base, type_mods)
28032836
if pattern:
28042837
regexp = re.compile(pattern, re.VERBOSE)
2805-
text = ''.join(contents)
2838+
text = ''.join(decode_text_stream(c) for c in contents)
28062839
text = regexp.sub(r'$\1$', text)
28072840
contents = [ text ]
28082841

@@ -2817,7 +2850,7 @@ def streamOneP4Deletion(self, file):
28172850
if verbose:
28182851
sys.stdout.write("delete %s\n" % relPath)
28192852
sys.stdout.flush()
2820-
self.gitStream.write("D %s\n" % relPath)
2853+
self.gitStream.write(encode_text_stream(u'D {}\n'.format(relPath)))
28212854

28222855
if self.largeFileSystem and self.largeFileSystem.isLargeFile(relPath):
28232856
self.largeFileSystem.removeLargeFile(relPath)
@@ -2917,9 +2950,9 @@ def streamP4FilesCbSelf(entry):
29172950
if 'shelved_cl' in f:
29182951
# Handle shelved CLs using the "p4 print file@=N" syntax to print
29192952
# the contents
2920-
fileArg = '%s@=%d' % (f['path'], f['shelved_cl'])
2953+
fileArg = f['path'] + encode_text_stream('@={}'.format(f['shelved_cl']))
29212954
else:
2922-
fileArg = '%s#%s' % (f['path'], f['rev'])
2955+
fileArg = f['path'] + encode_text_stream('#{}'.format(f['rev']))
29232956

29242957
fileArgs.append(fileArg)
29252958

0 commit comments

Comments
 (0)