Skip to content

Commit

Permalink
fix: map subprocess errors to exit code 2 and improve logging
Browse files Browse the repository at this point in the history
  • Loading branch information
PeterSchafer committed Jul 24, 2024
1 parent 966a2f3 commit 9fde4fe
Show file tree
Hide file tree
Showing 4 changed files with 35 additions and 1 deletion.
2 changes: 1 addition & 1 deletion cliv2/cmd/cliv2/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -558,7 +558,7 @@ func MainWithErrorCode() int {
displayError(err, globalEngine.GetUserInterface(), globalConfiguration)

exitCode := cliv2.DeriveExitCode(err)
globalLogger.Printf("Exiting with %d", exitCode)
globalLogger.Printf("Exiting with %d (cause: %v)", exitCode, err)

targetId, targetIdError := instrumentation.GetTargetId(globalConfiguration.GetString(configuration.INPUT_DIRECTORY), instrumentation.AutoDetectedTargetId, instrumentation.WithConfiguredRepository(globalConfiguration))
if targetIdError != nil {
Expand Down
4 changes: 4 additions & 0 deletions cliv2/internal/cliv2/cliv2.go
Original file line number Diff line number Diff line change
Expand Up @@ -527,6 +527,10 @@ func DeriveExitCode(err error) int {

if errors.As(err, &exitError) {
returnCode = exitError.ExitCode()
// map errors in subprocesses to exit code 2 to remain the documented exit code range
if returnCode < 0 {
returnCode = constants.SNYK_EXIT_CODE_ERROR
}
} else if errors.Is(err, context.DeadlineExceeded) {
returnCode = constants.SNYK_EXIT_CODE_EX_UNAVAILABLE
} else if errors.As(err, &errorWithExitCode) {
Expand Down
9 changes: 9 additions & 0 deletions src/cli/commands/woof/getWoof.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,15 @@ export default function getWoof(args: MethodArgs): string {
if (previewFeaturesEnabled()) {
console.debug('This is a previewoof!');
}

if (options['exit-code'] != undefined) {
const exitCode = Number(options['exit-code']);
if (exitCode < 0) {
process.abort();
} else {
process.exit(exitCode);
}
}
}

return woofs[lang];
Expand Down
21 changes: 21 additions & 0 deletions test/jest/acceptance/exitcode.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { runSnykCLI } from '../util/runSnykCLI';

jest.setTimeout(1000 * 60);

describe('exit code behaviour', () => {
it.each([
{ input: 0, expected: 0 },
{ input: 1, expected: 1 },
{ input: 2, expected: 2 },
{ input: 3, expected: 3 },
{ input: -1, expected: 2 },
])(
'map legacy cli exit code $input to $expected',
async ({ input, expected }) => {
const { code } = await runSnykCLI(
`woof --exit-code=${input} --language=cat -d`,
);
expect(code).toEqual(expected);
},
);
});

0 comments on commit 9fde4fe

Please sign in to comment.