sequencer: introduce a helper to read files written by scripts
As we are slowly teaching the sequencer to perform the hard work for the interactive rebase, we need to read files that were written by shell scripts. These files typically contain a single line and are invariably ended by a line feed (and possibly a carriage return before that). Let's use a helper to read such files and to remove the line ending. Signed-off-by: Johannes Schindelin <johannes.schindelin@gmx.de> Signed-off-by: Junio C Hamano <gitster@pobox.com>
Johannes Schindelin committed
Oct 21, 2016 at 14:25 UTC
1dfc84e9e040aa694548731eae434934379b928f
1 file changed
+34
sequencer.c
+34
@@ -234,6 +234,40 @@ static int write_message(struct strbuf *msgbuf, const char *filename)
234
return 0;
235
}
236
237
+/*
238
+ * Reads a file that was presumably written by a shell script, i.e. with an
239
+ * end-of-line marker that needs to be stripped.
240
+ *
241
+ * Note that only the last end-of-line marker is stripped, consistent with the
242
+ * behavior of "$(cat path)" in a shell script.
243
+ *
244
+ * Returns 1 if the file was read, 0 if it could not be read or does not exist.
245
+ */
246
+static int read_oneliner(struct strbuf *buf,
247
+ const char *path, int skip_if_empty)
248
+{
249
+ int orig_len = buf->len;
250
+
251
+ if (!file_exists(path))
252
+ return 0;
253
+
254
+ if (strbuf_read_file(buf, path, 0) < 0) {
255
+ warning_errno(_("could not read '%s'"), path);
256
+ return 0;
257
+ }
258
+
259
+ if (buf->len > orig_len && buf->buf[buf->len - 1] == '\n') {
260
+ if (--buf->len > orig_len && buf->buf[buf->len - 1] == '\r')
261
+ --buf->len;
262
+ buf->buf[buf->len] = '\0';
263
+ }
264
+
265
+ if (skip_if_empty && buf->len == orig_len)
266
+ return 0;
267
+
268
+ return 1;
269
+}
270
+
271
static struct tree *empty_tree(void)
272
{
273
return lookup_tree(EMPTY_TREE_SHA1_BIN);