File: exec.go

package info (click to toggle)
adequate 0.17.6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 488 kB
  • sloc: python: 254; makefile: 111; sh: 75; ansic: 29
file content (41 lines) | stat: -rw-r--r-- 889 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
40
41
package main

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"os/exec"
	"strings"
)

type runCommandType func(args []string) ([]string, error)

func runCommand(args []string) ([]string, error) {
	cmd := exec.Command(args[0], args[1:]...)
	cmd.Dir = "/" // to not be affected if the current directory is removed
	out, err := cmd.CombinedOutput()
	lines := strings.Split(string(out), "\n")
	if err != nil {
		return lines, fmt.Errorf("%q failed: %w", strings.Join(args, " "), err)
	}

	lines, err = readLines(bytes.NewReader(out))
	if err != nil {
		return lines, fmt.Errorf("failed to read the output of %q: %w", args, err)
	}

	return lines, nil
}

func readLines(r io.Reader) ([]string, error) {
	var lines []string
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		lines = append(lines, scanner.Text())
	}
	if err := scanner.Err(); err != nil {
		return nil, err
	}
	return lines, nil
}