2020-06-17 17:57:44 +02:00
package mobycli
2020-05-29 12:02:07 +02:00
import (
"context"
"fmt"
"os"
"os/exec"
2020-06-05 17:30:27 +02:00
"strings"
2020-05-29 12:02:07 +02:00
2020-05-29 17:07:48 +02:00
"github.com/spf13/cobra"
2020-05-29 12:02:07 +02:00
apicontext "github.com/docker/api/context"
"github.com/docker/api/context/store"
)
2020-06-17 17:57:44 +02:00
// ComDockerCli name of the classic cli binary
const ComDockerCli = "com.docker.cli"
2020-06-05 17:30:27 +02:00
2020-06-17 22:52:49 +02:00
// Exec delegates to com.docker.cli if on moby context
2020-05-29 12:02:07 +02:00
func Exec ( ctx context . Context ) {
currentContext := apicontext . CurrentContext ( ctx )
s := store . ContextStore ( ctx )
_ , err := s . Get ( currentContext )
// Only run original docker command if the current context is not
// ours.
if err != nil {
2020-06-17 22:52:49 +02:00
shellOut ( ctx )
}
}
func shellOut ( ctx context . Context ) {
cmd := exec . CommandContext ( ctx , ComDockerCli , os . Args [ 1 : ] ... )
cmd . Stdin = os . Stdin
cmd . Stdout = os . Stdout
cmd . Stderr = os . Stderr
if err := cmd . Run ( ) ; err != nil {
if exiterr , ok := err . ( * exec . ExitError ) ; ok {
os . Exit ( exiterr . ExitCode ( ) )
2020-05-29 12:02:07 +02:00
}
2020-06-17 22:52:49 +02:00
fmt . Fprintln ( os . Stderr , err )
os . Exit ( 1 )
2020-05-29 12:02:07 +02:00
}
2020-06-17 22:52:49 +02:00
os . Exit ( 0 )
2020-05-29 12:02:07 +02:00
}
2020-05-29 17:07:48 +02:00
2020-06-17 17:57:44 +02:00
// ExecCmd delegates the cli command to com.docker.cli. The error is never returned (process will exit with docker classic exit code), the return type is to make it easier to use with cobra commands
2020-05-29 17:07:48 +02:00
func ExecCmd ( command * cobra . Command ) error {
2020-06-17 22:52:49 +02:00
shellOut ( command . Context ( ) )
2020-05-29 17:07:48 +02:00
return nil
}
2020-06-05 17:30:27 +02:00
// IsDefaultContextCommand checks if the command exists in the classic cli (issues a shellout --help)
func IsDefaultContextCommand ( dockerCommand string ) bool {
2020-06-17 17:57:44 +02:00
cmd := exec . Command ( ComDockerCli , dockerCommand , "--help" )
2020-06-05 17:30:27 +02:00
b , e := cmd . CombinedOutput ( )
if e != nil {
fmt . Println ( e )
}
output := string ( b )
contains := strings . Contains ( output , "Usage:\tdocker " + dockerCommand )
return contains
}
2020-06-12 17:54:14 +02:00
// ExecSilent executes a command and do redirect output to stdOut, return output
func ExecSilent ( ctx context . Context ) ( [ ] byte , error ) {
2020-06-17 17:57:44 +02:00
cmd := exec . CommandContext ( ctx , ComDockerCli , os . Args [ 1 : ] ... )
2020-06-12 17:54:14 +02:00
return cmd . CombinedOutput ( )
}