File: exec.go

package info (click to toggle)
emd 1.0.1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 260 kB
  • sloc: sh: 159; makefile: 4
file content (39 lines) | stat: -rw-r--r-- 756 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package utils

import (
	"fmt"
	"os/exec"
	"strings"
)

// CliError is an error of cli command
type CliError struct {
	Err error
	Cmd string
}

func (c *CliError) Error() string {
	return fmt.Sprintf("%v\n\nThe command was:\n%v", c.Err, c.Cmd)
}

// GetCmdStr returns the string of a command
func GetCmdStr(bin string, args []string) string {
	s := bin
	for _, a := range args {
		if strings.Index(a, "\"") > -1 {
			a = strings.Replace(a, "\"", "\\\"", -1)
		}
		s += fmt.Sprintf(" %v", a)
	}
	return s
}

// Exec a command
func Exec(bin string, args []string) (string, error) {
	cmd := exec.Command(bin, args...)
	out, err := cmd.CombinedOutput()
	if err != nil {
		return "", &CliError{Err: err, Cmd: GetCmdStr(bin, args)}
	}
	return string(out), nil
}