cmd/root: Make 'toolbox' create or fall back to a container if possible

This makes 'toolbox', without any commands specified, behave a lot like
'toolbox enter'. When there aren't any toolbox containers, it will
offer to create a new container matching the same parameters passed to
the command. If there's just one toolbox container available, then it
will fall back to it.

This makes the command line interface a lot similar to that of
github.com/coreos/toolbox, which makes things easier for those
switching over from it.

Some changes by Debarshi Ray.

https://github.com/containers/toolbox/pull/811
This commit is contained in:
Ondřej Míchal 2021-06-25 16:04:52 +02:00 committed by Debarshi Ray
parent 73450bd8ac
commit 6c86cabbe5
2 changed files with 55 additions and 18 deletions

View file

@ -177,17 +177,62 @@ func rootHelp(cmd *cobra.Command, args []string) {
}
func rootRun(cmd *cobra.Command, args []string) error {
var builder strings.Builder
fmt.Fprintf(&builder, "missing command\n")
fmt.Fprintf(&builder, "\n")
fmt.Fprintf(&builder, "create Create a new toolbox container\n")
fmt.Fprintf(&builder, "enter Enter an existing toolbox container\n")
fmt.Fprintf(&builder, "list List all existing toolbox containers and images\n")
fmt.Fprintf(&builder, "\n")
fmt.Fprintf(&builder, "Run '%s --help' for usage.", executableBase)
if len(args) != 0 {
panic("unexpected argument: commands known or unknown shouldn't reach here")
}
errMsg := builder.String()
return errors.New(errMsg)
if utils.IsInsideContainer() {
if !utils.IsInsideToolboxContainer() {
return errors.New("this is not a toolbox container")
}
if _, err := utils.ForwardToHost(); err != nil {
return err
}
return nil
}
container, image, release, err := utils.ResolveContainerAndImageNames("", "", "", "")
if err != nil {
return err
}
userShell := os.Getenv("SHELL")
if userShell == "" {
return errors.New("failed to get the current user's default shell")
}
command := []string{userShell, "-l"}
hostID, err := utils.GetHostID()
if err != nil {
return fmt.Errorf("failed to get the host ID: %w", err)
}
hostVariantID, err := utils.GetHostVariantID()
if err != nil {
return errors.New("failed to get the host VARIANT_ID")
}
var emitEscapeSequence bool
if hostID == "fedora" && (hostVariantID == "silverblue" || hostVariantID == "workstation") {
emitEscapeSequence = true
}
if err := runCommand(container,
true,
image,
release,
command,
emitEscapeSequence,
true,
false); err != nil {
return err
}
return nil
}
func rootUsage(cmd *cobra.Command) error {

View file

@ -4,14 +4,6 @@ load 'libs/bats-support/load'
load 'libs/bats-assert/load'
load 'libs/helpers.bash'
@test "help: Try to run toolbox with no command (shows usage screen)" {
run $TOOLBOX
assert_failure
assert_line --index 0 "Error: missing command"
assert_output --partial "Run 'toolbox --help' for usage."
}
@test "help: Run command 'help'" {
run $TOOLBOX help