git-p4: add read_pipe_text() internal function

The existing read_pipe() function returns an empty string on error, but also returns an empty string if the command returns an empty string. This leads to ugly constructions trying to detect error cases. Add read_pipe_text() which just returns None on error. Signed-off-by: Luke Diamand <luke@diamand.org> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Luke Diamand committed Apr 15, 2017 at 11:36 UTC 78871bf46f18cd92e744a993c1d6422ff30d8bca
1 file changed +28 -3
git-p4.py
+28 -3
@@ -160,17 +160,42 @@ def p4_write_pipe(c, stdin):
160 real_cmd = p4_build_cmd(c)
161 return write_pipe(real_cmd, stdin)
162
163 -def read_pipe(c, ignore_error=False):
163 +def read_pipe_full(c):
164 + """ Read output from command. Returns a tuple
165 + of the return status, stdout text and stderr
166 + text.
167 + """
168 if verbose:
169 sys.stderr.write('Reading pipe: %s\n' % str(c))
170
171 expand = isinstance(c,basestring)
172 p = subprocess.Popen(c, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=expand)
173 (out, err) = p.communicate()
170 - if p.returncode != 0 and not ignore_error:
171 - die('Command failed: %s\nError: %s' % (str(c), err))
174 + return (p.returncode, out, err)
175 +
176 +def read_pipe(c, ignore_error=False):
177 + """ Read output from command. Returns the output text on
178 + success. On failure, terminates execution, unless
179 + ignore_error is True, when it returns an empty string.
180 + """
181 + (retcode, out, err) = read_pipe_full(c)
182 + if retcode != 0:
183 + if ignore_error:
184 + out = ""
185 + else:
186 + die('Command failed: %s\nError: %s' % (str(c), err))
187 return out
188
189 +def read_pipe_text(c):
190 + """ Read output from a command with trailing whitespace stripped.
191 + On error, returns None.
192 + """
193 + (retcode, out, err) = read_pipe_full(c)
194 + if retcode != 0:
195 + return None
196 + else:
197 + return out.rstrip()
198 +
199 def p4_read_pipe(c, ignore_error=False):
200 real_cmd = p4_build_cmd(c)
201 return read_pipe(real_cmd, ignore_error)