|
17 | 17 | package commands |
18 | 18 |
|
19 | 19 | import ( |
| 20 | + "context" |
| 21 | + "strings" |
| 22 | + |
20 | 23 | "github.com/urfave/cli/v3" |
21 | 24 |
|
22 | 25 | "github.com/NVIDIA/nvidia-container-toolkit/cmd/nvidia-cdi-hook/chmod" |
@@ -51,3 +54,46 @@ func IssueUnsupportedHookWarning(logger logger.Interface, c *cli.Command) { |
51 | 54 | logger.Warningf("Unsupported CDI hook: %v", args[0]) |
52 | 55 | } |
53 | 56 | } |
| 57 | + |
| 58 | +// ConfigureCDIHookCommand configures a base command with supported CDI |
| 59 | +// hooks and error handling for unsupported hooks. |
| 60 | +func ConfigureCDIHookCommand(base *cli.Command, logger logger.Interface) *cli.Command { |
| 61 | + // We set the default action for the command to issue a warning and |
| 62 | + // exit with no error. |
| 63 | + // This means that if an unsupported hook is run, a container will not |
| 64 | + // fail to launch. An unsupported hook could be the result of a CDI |
| 65 | + // specification referring to a new hook that is not yet supported by an |
| 66 | + // older NVIDIA Container Toolkit version or a hook that has been removed |
| 67 | + // in newer version. |
| 68 | + base.Action = func(ctx context.Context, cmd *cli.Command) error { |
| 69 | + IssueUnsupportedHookWarning(logger, cmd) |
| 70 | + return nil |
| 71 | + } |
| 72 | + // Handle unrecognized commands when help is requested (e.g., help |
| 73 | + // unknowncommand) |
| 74 | + base.CommandNotFound = func(ctx context.Context, cmd *cli.Command, commandName string) { |
| 75 | + IssueUnsupportedHookWarning(logger, cmd) |
| 76 | + } |
| 77 | + // Handle usage errors. For unrecognized commands with flags, we suppress |
| 78 | + // the error to maintain backwards compatibility. |
| 79 | + base.OnUsageError = func(ctx context.Context, cmd *cli.Command, err error, isSubcommand bool) error { |
| 80 | + // If this is a flag parsing error for an unrecognized command, |
| 81 | + // suppress it and let the default Action handle it |
| 82 | + errMsg := err.Error() |
| 83 | + if strings.HasPrefix(errMsg, "flag provided but not defined: -") { |
| 84 | + // Check if the first argument is an unrecognized command |
| 85 | + args := cmd.Args().Slice() |
| 86 | + if len(args) > 0 && cmd.Command(args[0]) == nil { |
| 87 | + // This is an unrecognized hook with flags - issue a warning |
| 88 | + // and let the default Action handle it |
| 89 | + logger.Warningf("Unsupported CDI hook: %v", args[0]) |
| 90 | + return nil |
| 91 | + } |
| 92 | + } |
| 93 | + // For other usage errors, return the error as-is |
| 94 | + return err |
| 95 | + } |
| 96 | + base.Commands = New(logger) |
| 97 | + |
| 98 | + return base |
| 99 | +} |
0 commit comments