exec.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package mobycli
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "os/exec"
  7. "strings"
  8. "github.com/spf13/cobra"
  9. apicontext "github.com/docker/api/context"
  10. "github.com/docker/api/context/store"
  11. )
  12. // ComDockerCli name of the classic cli binary
  13. const ComDockerCli = "com.docker.cli"
  14. // Exec delegates to com.docker.cli if on moby context
  15. func Exec(ctx context.Context) {
  16. currentContext := apicontext.CurrentContext(ctx)
  17. s := store.ContextStore(ctx)
  18. currentCtx, err := s.Get(currentContext)
  19. // Only run original docker command if the current context is not
  20. // ours.
  21. if err != nil || currentCtx.Type() == store.DefaultContextType {
  22. shellOut(ctx)
  23. }
  24. }
  25. func shellOut(ctx context.Context) {
  26. cmd := exec.CommandContext(ctx, ComDockerCli, os.Args[1:]...)
  27. cmd.Stdin = os.Stdin
  28. cmd.Stdout = os.Stdout
  29. cmd.Stderr = os.Stderr
  30. if err := cmd.Run(); err != nil {
  31. if exiterr, ok := err.(*exec.ExitError); ok {
  32. os.Exit(exiterr.ExitCode())
  33. }
  34. fmt.Fprintln(os.Stderr, err)
  35. os.Exit(1)
  36. }
  37. os.Exit(0)
  38. }
  39. // 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
  40. func ExecCmd(command *cobra.Command) error {
  41. shellOut(command.Context())
  42. return nil
  43. }
  44. // IsDefaultContextCommand checks if the command exists in the classic cli (issues a shellout --help)
  45. func IsDefaultContextCommand(dockerCommand string) bool {
  46. cmd := exec.Command(ComDockerCli, dockerCommand, "--help")
  47. b, e := cmd.CombinedOutput()
  48. if e != nil {
  49. fmt.Println(e)
  50. }
  51. output := string(b)
  52. contains := strings.Contains(output, "Usage:\tdocker "+dockerCommand)
  53. return contains
  54. }
  55. // ExecSilent executes a command and do redirect output to stdOut, return output
  56. func ExecSilent(ctx context.Context) ([]byte, error) {
  57. cmd := exec.CommandContext(ctx, ComDockerCli, os.Args[1:]...)
  58. return cmd.CombinedOutput()
  59. }