aboutsummaryrefslogtreecommitdiff
path: root/internal/runjson.go
blob: 54fb6eb555e0aa1df886ce1854c46feb8e73322b (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
package internal

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"os"
	"os/exec"
)

// Zilch returns the zero value of a given type.
func Zilch[T any]() T { return *new(T) }

func RunJSON[T any](ctx context.Context, program string, args ...any) (T, error) {
	exePath, err := exec.LookPath(program)
	if err != nil {
		return Zilch[T](), fmt.Errorf("can't find %s: %w", program, err)
	}

	var argStr []string

	for _, arg := range args {
		argStr = append(argStr, fmt.Sprint(arg))
	}

	var stdout bytes.Buffer
	var stderr bytes.Buffer

	cmd := exec.CommandContext(ctx, exePath, argStr...)
	cmd.Stdout = &stdout
	cmd.Stderr = &stderr

	if err := cmd.Run(); err != nil {
		os.Stderr.Write(stderr.Bytes())
		return Zilch[T](), fmt.Errorf("can't run %s: %w", program, err)
	}

	var result T
	if err := json.NewDecoder(&stdout).Decode(&result); err != nil {
		return Zilch[T](), fmt.Errorf("can't decode json: %w", err)
	}

	return result, nil
}