Skip to content

Commit

Permalink
Merge pull request #67 from catatsuy/fix-add-remaining-data-processin…
Browse files Browse the repository at this point in the history
…g-for-cli

Handle edge cases for input without final newline in CLI processing
  • Loading branch information
catatsuy authored Aug 12, 2024
2 parents 7534988 + 719d4b0 commit c80fc00
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
26 changes: 26 additions & 0 deletions internal/cli/cli.go
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,16 @@ func (c *CLI) replaceProcess(searchRe *regexp.Regexp, replacement []byte, inputS
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
// Process the remaining data if any
if len(line) > 0 {
modifiedLine := searchRe.ReplaceAllFunc(line, func(match []byte) []byte {
matched = true
return replacement
})
if _, err := c.outStream.Write(modifiedLine); err != nil {
return false, fmt.Errorf("error writing to output: %w", err)
}
}
break
}
return false, fmt.Errorf("error reading input: %w", err)
Expand Down Expand Up @@ -342,6 +352,22 @@ func (c *CLI) filterProcess(filters []*regexp.Regexp, excludes []*regexp.Regexp,
line, err := reader.ReadBytes('\n')
if err != nil {
if err == io.EOF {
// Process the remaining data if any
if len(line) > 0 {
hit, hitRes := matchesFilters(line, filters)
if len(filters) == 0 || hit {
matched = hit
if excludeHit, _ := matchesFilters(line, excludes); !excludeHit {
if len(hitRes) > 0 && c.isColor {
line = colorText(line, hitRes)
}

if _, err := c.outStream.Write(line); err != nil {
return false, fmt.Errorf("error writing to output: %w", err)
}
}
}
}
break
}
return false, fmt.Errorf("error reading input: %w", err)
Expand Down
15 changes: 15 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ func TestRun_successProcess(t *testing.T) {
input: "searchb searchc\n",
expected: "replacementb replacementc\n",
},
"normal no last LF": {
args: []string{"purl", "-replace", "@search@replacement@"},
input: "searchb searchc",
expected: "replacementb replacementc",
},
"no match": {
args: []string{"purl", "-replace", "@search@replacement@"},
input: "no match\n",
Expand Down Expand Up @@ -86,6 +91,16 @@ func TestRun_successProcess(t *testing.T) {
input: "searchb\r\nreplace\r\nsearchcabcdefg\r\n",
expected: "searchb\r\nsearchcabcdefg\r\n",
},
"provide no LF text": {
args: []string{"purl", "-filter", "search"},
input: "searchb",
expected: "searchb",
},
"provide no match and no LF text": {
args: []string{"purl", "-filter", "search"},
input: "aaaab",
expected: "",
},
"provide CRLF text for replace": {
args: []string{"purl", "-replace", "@search@replacement@"},
input: "searcha search\r\nsearchc searchd\r\n",
Expand Down

0 comments on commit c80fc00

Please sign in to comment.