aboutsummaryrefslogtreecommitdiff
path: root/cmd/diff.go
blob: 8d6a85fb8a25c0ed466d617a419a3435201b12b8 (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
66
67
68
69
70
71
72
73
74
75
76
package cmd

import (
	"golang.flu0r1ne.net/zsu/snap"
	"os/exec"
	"os"
	"io"
	"log"
	"fmt"
	"errors"
)

func Diff(params []string) {

	if(len(params) == 0) {
		die.Fatal("Reference file is required")
	}

	if(len(params) > 2) {
		die.Fatal("Too many arguments provided")
	}

	reference := params[0]

	from, to := snap.ToRelative("@-"), snap.ToRelative("@")
	if len(params) > 1 {
		from, to = snap.ParseDiff(params[1])
	}

	oracle := snap.GetOracle(reference)

	fromPath := oracle.PathTo(from)
	toPath := oracle.PathTo(to)

	_, noColor := os.LookupEnv("NO_COLOR")

	colorOpt := "--color=always"
	if noColor {
		colorOpt = "--color=never"
	}

	diff := exec.Command("diff", colorOpt, fromPath, toPath)
	diff.Env = os.Environ()
	
	stderr, err := diff.StderrPipe()
	if err != nil {
		log.Fatal(err);
	}

	stdout, err := diff.StdoutPipe()
	if err != nil {
		log.Fatal(err);
	}

	if err := diff.Start(); err != nil {
		log.Fatal(err)
	}

	outtext, _ := io.ReadAll(stdout)
	errtext, _ := io.ReadAll(stderr)
	
	fmt.Fprintf(os.Stderr, "%s", errtext)
	fmt.Fprintf(os.Stdout, "%s", outtext)

	if err := diff.Wait(); err != nil {
		var exiterr *exec.ExitError

		// GNU Diff exits 1 if the files differ
		if errors.As(err, &exiterr) && exiterr.ExitCode() == 1 {
			os.Exit(exiterr.ExitCode())
		}

		die.Fatalf("Error encountered while executing diff.")
		os.Exit(2)
	}
}