Kotlin conversion: SOPExceptionExitCodeMapper

This commit is contained in:
Paul Schaub 2023-11-15 11:55:50 +01:00
parent b251956f49
commit 5c2695228b
Signed by: vanitasvitae
GPG Key ID: 62BEE9264BF17311
2 changed files with 31 additions and 34 deletions

View File

@ -1,34 +0,0 @@
// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.cli.picocli;
import picocli.CommandLine;
import sop.exception.SOPGPException;
public class SOPExceptionExitCodeMapper implements CommandLine.IExitCodeExceptionMapper {
@Override
public int getExitCode(Throwable exception) {
if (exception instanceof SOPGPException) {
return ((SOPGPException) exception).getExitCode();
}
if (exception instanceof CommandLine.UnmatchedArgumentException) {
CommandLine.UnmatchedArgumentException ex = (CommandLine.UnmatchedArgumentException) exception;
// Unmatched option of subcommand (eg. `generate-key -k`)
if (ex.isUnknownOption()) {
return SOPGPException.UnsupportedOption.EXIT_CODE;
}
// Unmatched subcommand
return SOPGPException.UnsupportedSubcommand.EXIT_CODE;
}
// Invalid option (eg. `--label Invalid`)
if (exception instanceof CommandLine.ParameterException) {
return SOPGPException.UnsupportedOption.EXIT_CODE;
}
// Others, like IOException etc.
return 1;
}
}

View File

@ -0,0 +1,31 @@
// SPDX-FileCopyrightText: 2023 Paul Schaub <vanitasvitae@fsfe.org>
//
// SPDX-License-Identifier: Apache-2.0
package sop.cli.picocli
import picocli.CommandLine.*
import sop.exception.SOPGPException
class SOPExceptionExitCodeMapper : IExitCodeExceptionMapper {
override fun getExitCode(exception: Throwable): Int =
if (exception is SOPGPException) {
// SOPGPExceptions have well-defined exit code
exception.getExitCode()
} else if (exception is UnmatchedArgumentException) {
if (exception.isUnknownOption) {
// Unmatched option of subcommand (e.g. `generate-key --unknown`)
SOPGPException.UnsupportedOption.EXIT_CODE
} else {
// Unmatched subcommand
SOPGPException.UnsupportedSubcommand.EXIT_CODE
}
} else if (exception is ParameterException) {
// Invalid option (e.g. `--as invalid`)
SOPGPException.UnsupportedOption.EXIT_CODE
} else {
// Others, like IOException etc.
1
}
}