aboutsummaryrefslogtreecommitdiff
path: root/internal/yae/utilities.go
blob: 73042fde0f1be3ac321f5f8c237c0c04f6ac57b6 (plain)
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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package yae

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

func FetchSHA256(url string, unpack bool) (string, error) {
	arguments := []string{"--type", "sha256", url}

	if unpack {
		arguments = append([]string{"--unpack"}, arguments...)
	}

	output, err := command("nix-prefetch-url", false, arguments...)

	if err != nil {
		return "", err
	}

	lines := strings.Split(output, "\n")

	return strings.Trim(lines[len(lines)-2], "\n"), nil
}

func FetchSRIHash(sha256 string) (string, error) {
	output, err := command("nix", false, "hash", "convert", "--hash-algo", "sha256", "--from", "nix32", sha256)

	if err != nil {
		return "", err
	}

	return strings.Trim(output, "\n"), nil
}

func command(name string, show bool, args ...string) (string, error) {
	executable, err := exec.LookPath(name)
	out := []byte{}

	if show {
		cmd := exec.Command(executable, args...)
		cmd.Stdin = os.Stdin
		cmd.Stderr = os.Stderr
		out, err = cmd.Output()
	} else {
		cmd := exec.Command(executable, args...)
		out, err = cmd.Output()
	}

	return string(out), err
}

func Lister(items []string) string {
	if len(items) == 0 {
		return ""
	} else if len(items) == 1 {
		return items[0]
	} else if len(items) == 2 {
		return fmt.Sprintf("%s & %s", items[0], items[1])
	}

	return fmt.Sprintf("%s, & %s", strings.Join(items[:len(items)-1], ", "), items[len(items)-1])
}