From 0a4e55f9a190b500835e10d187ca4f88a96917e2 Mon Sep 17 00:00:00 2001 From: Billy Keyes Date: Sun, 14 Jul 2024 23:44:16 -0400 Subject: [PATCH] Return preamble when a patch has no files (#46) While empty patches with only a header were parsable, the parser discarded the preamble content. This meant callers had to handle this case specially. Now, if we reach the end of the input without finding a file, Parse() returns the full content of the patch as the preamble. --- gitdiff/file_header.go | 2 +- gitdiff/parser.go | 6 +++--- gitdiff/parser_test.go | 18 ++++++++++++++++-- gitdiff/testdata/no_files.patch | 8 ++++++++ 4 files changed, 28 insertions(+), 6 deletions(-) create mode 100644 gitdiff/testdata/no_files.patch diff --git a/gitdiff/file_header.go b/gitdiff/file_header.go index 77ceb5d..7ae4bc9 100644 --- a/gitdiff/file_header.go +++ b/gitdiff/file_header.go @@ -57,7 +57,7 @@ func (p *parser) ParseNextFileHeader() (*File, string, error) { return nil, "", err } } - return nil, "", nil + return nil, preamble.String(), nil } func (p *parser) ParseGitFileHeader() (*File, error) { diff --git a/gitdiff/parser.go b/gitdiff/parser.go index d2b29cb..e8f8430 100644 --- a/gitdiff/parser.go +++ b/gitdiff/parser.go @@ -33,6 +33,9 @@ func Parse(r io.Reader) ([]*File, string, error) { if err != nil { return files, preamble, err } + if len(files) == 0 { + preamble = pre + } if file == nil { break } @@ -50,9 +53,6 @@ func Parse(r io.Reader) ([]*File, string, error) { } } - if len(files) == 0 { - preamble = pre - } files = append(files, file) } diff --git a/gitdiff/parser_test.go b/gitdiff/parser_test.go index 30f59f4..15a5d67 100644 --- a/gitdiff/parser_test.go +++ b/gitdiff/parser_test.go @@ -281,8 +281,13 @@ this is another line --- could this be a header? nope, it's just some dashes `, - Output: nil, - Preamble: "", + Output: nil, + Preamble: ` +this is a line +this is another line +--- could this be a header? +nope, it's just some dashes +`, }, "detatchedFragmentLike": { Input: ` @@ -290,6 +295,10 @@ a wild fragment appears? @@ -1,3 +1,4 ~1,5 @@ `, Output: nil, + Preamble: ` +a wild fragment appears? +@@ -1,3 +1,4 ~1,5 @@ +`, }, "detatchedFragment": { Input: ` @@ -426,6 +435,11 @@ Date: Tue Apr 2 22:55:40 2019 -0700 }, Preamble: textPreamble, }, + "noFiles": { + InputFile: "testdata/no_files.patch", + Output: nil, + Preamble: textPreamble, + }, "newBinaryFile": { InputFile: "testdata/new_binary_file.patch", Output: []*File{ diff --git a/gitdiff/testdata/no_files.patch b/gitdiff/testdata/no_files.patch new file mode 100644 index 0000000..9eea12d --- /dev/null +++ b/gitdiff/testdata/no_files.patch @@ -0,0 +1,8 @@ +commit 5d9790fec7d95aa223f3d20936340bf55ff3dcbe +Author: Morton Haypenny +Date: Tue Apr 2 22:55:40 2019 -0700 + + A file with multiple fragments. + + The content is arbitrary. +