| // Package osutils provide tools that interact with the OS or the shell. | |
| package osutils | |
| import ( | |
| "bufio" | |
| "bytes" | |
| "github.com/golang/glog" | |
| "io" | |
| "os" | |
| "os/exec" | |
| "strings" | |
| ) | |
| // Run returns the stdout and stderr the output of running the given command | |
| // with the given arguments. | |
| func Run(command string, args []string, hideStderr bool) (string, error) { | |
| cmd := exec.Command(command, args...) | |
| glog.Infof("running command `%s`", cmd) | |
| var stdout, stderr bytes.Buffer | |
| cmd.Stdout = &stdout | |
| cmd.Stderr = &stderr | |
| if !hideStderr { | |
| // Displays stderr as it comes to the os.stderr | |
| // Useful when running install as the executing logs | |
| // are displayed on the os.stderr as it runs | |
| cmd.Stderr = io.MultiWriter(os.Stderr, &stderr) | |
| } | |
| err := cmd.Run() | |
| // Discarding errors if hideStderr is true, similar to setting '2>/dev/null'. | |
| if hideStderr { | |
| return stdout.String(), nil | |
| } | |
| return stdout.String(), err | |
| } | |
| // Parse returns a mapping of contents of the osFile. | |
| // | |
| // Syntax of contents in the os realease file : <key>=<value> | |
| // Returns a mapping of the key to value | |
| func Parse(osFile string) (map[string]string, error) { | |
| f, err := os.Open(osFile) | |
| if err != nil { | |
| return nil, err | |
| } | |
| defer f.Close() | |
| osReleaseFile := make(map[string]string) | |
| scanner := bufio.NewScanner(f) | |
| for scanner.Scan() { | |
| line := scanner.Text() | |
| key, value, found := strings.Cut(line, "=") | |
| if found { | |
| osReleaseFile[key] = value | |
| } | |
| } | |
| return osReleaseFile, nil | |
| } |