diff --git a/internal/tool/command.go b/internal/tool/command.go index 590db82..419b5f9 100644 --- a/internal/tool/command.go +++ b/internal/tool/command.go @@ -132,6 +132,12 @@ func runCommand(cmd *exec.Cmd) (*string, *string, error) { var stderr bytes.Buffer cmd.Stderr = &stderr cmdOutput, err := cmd.Output() + // Opengrep exits 2 when some files had errors but still prints the full JSON report, + // whose errors are reported as file errors, so its results are kept + var exitErr *exec.ExitError + if errors.As(err, &exitErr) && exitErr.ExitCode() == 2 && json.Valid(cmdOutput) { + err = nil + } if err != nil { stderrString := stderr.String() return nil, &stderrString, err diff --git a/internal/tool/command_test.go b/internal/tool/command_test.go index 914abd6..de4cadc 100644 --- a/internal/tool/command_test.go +++ b/internal/tool/command_test.go @@ -79,6 +79,44 @@ func TestRunCommand_Error(t *testing.T) { assert.Empty(t, stderr, "Expected empty stderr for a failed command") } +func TestRunCommand_ExitCode2WithReport(t *testing.T) { + // Arrange + report := `{"results": [], "errors": [{"level": "error", "message": "Out of memory"}]}` + mockCmd := exec.Command("sh", "-c", "echo '"+report+"'; echo 'Scan Status' >&2; exit 2") + + // Act + stdout, stderr, err := runCommand(mockCmd) + + // Assert + assert.NoError(t, err) + assert.Nil(t, stderr) + assert.Equal(t, report+"\n", *stdout) +} + +func TestRunCommand_ExitCode2WithoutReport(t *testing.T) { + // Arrange + mockCmd := exec.Command("sh", "-c", "echo 'not a report'; exit 2") + + // Act + stdout, _, err := runCommand(mockCmd) + + // Assert + assert.Error(t, err) + assert.Nil(t, stdout) +} + +func TestRunCommand_OtherExitCodeWithReport(t *testing.T) { + // Arrange + mockCmd := exec.Command("sh", "-c", `echo '{"results": [], "errors": []}'; exit 7`) + + // Act + stdout, _, err := runCommand(mockCmd) + + // Assert + assert.Error(t, err) + assert.Nil(t, stdout) +} + func TestParseCommandOutput(t *testing.T) { // Arrange mockPatternDescriptions := []codacy.PatternDescription{