...

Source file src/edge-infra.dev/pkg/lib/cli/sh/sh.go

Documentation: edge-infra.dev/pkg/lib/cli/sh

     1  package sh
     2  
     3  import (
     4  	"log"
     5  	"os"
     6  	"strings"
     7  
     8  	"github.com/codeskyblue/go-sh"
     9  )
    10  
    11  // Shell contains the created Session and Run convenience methods
    12  type Shell struct {
    13  	*sh.Session
    14  }
    15  
    16  // New creates a Shell with all environment variables copied to it.
    17  func New() *Shell {
    18  	session := sh.NewSession()
    19  	env := os.Environ()
    20  	for _, variable := range env {
    21  		tokens := strings.Split(variable, "=")
    22  		session.SetEnv(tokens[0], tokens[1])
    23  	}
    24  	return &Shell{Session: session}
    25  }
    26  
    27  // NewInDir creates a new shell in the provided directory.
    28  func NewInDir(dir string) *Shell {
    29  	shell := New()
    30  	shell.SetDir(dir)
    31  	return shell
    32  }
    33  
    34  // Run shell command without breaking command up into variadic arguments,
    35  // returns output and err
    36  func (sh Shell) Run(command string) (string, error) {
    37  	tokens := strings.Split(command, " ")
    38  	out, err := sh.Command(tokens[0], tokens[1:]).Output()
    39  	if err != nil {
    40  		return string(out), err
    41  	}
    42  	return string(out), nil
    43  }
    44  
    45  // RunE runs the shell command but discards the string output, to enable inlining
    46  // for situations where only the error matters.
    47  func (sh Shell) RunE(command string) error {
    48  	_, err := sh.Run(command)
    49  	return err
    50  }
    51  
    52  // Run shell command without breaking command up into variadic arguments,
    53  // returns combine outputs and err
    54  func (sh Shell) RunCombineOutput(command string) (string, error) {
    55  	tokens := strings.Split(command, " ")
    56  	out, err := sh.Command(tokens[0], tokens[1:]).CombinedOutput()
    57  	if err != nil {
    58  		return string(out), err
    59  	}
    60  	return string(out), nil
    61  }
    62  
    63  // RunOrDie command that will fatally error if the command does not succeed
    64  func (sh Shell) RunOrDie(command string) string {
    65  	out, err := sh.Run(command)
    66  	if err != nil {
    67  		log.Fatal(err)
    68  	}
    69  	return out
    70  }
    71  

View as plain text