File: main.go

package info (click to toggle)
golang-github-hashicorp-terraform-json 0.5.0-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 2,572 kB
  • sloc: makefile: 31
file content (81 lines) | stat: -rw-r--r-- 1,437 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
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
77
78
79
80
81
package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"os/exec"

	tfjson "github.com/hashicorp/terraform-json"
)

var (
	diff   = flag.Bool("diff", false, "diff output instead of writing")
	schema = flag.Bool("schema", false, "input is a schema, not a plan")
)

func main() {
	flag.Parse()

	if flag.NArg() < 1 {
		fmt.Fprintf(os.Stderr, "usage: %s FILE\n\n", os.Args[0])
		os.Exit(1)
	}

	path := flag.Arg(0)

	f, err := os.Open(path)
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	defer f.Close()

	var parsed interface{}
	if *schema {
		parsed = &tfjson.ProviderSchemas{}
	} else {
		parsed = &tfjson.Plan{}
	}

	dec := json.NewDecoder(f)
	dec.DisallowUnknownFields()
	if err = dec.Decode(parsed); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	out, err := json.MarshalIndent(parsed, "", "  ")
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}

	out = append(out, byte('\n'))

	if *diff {
		var diffCmd string
		if _, err := exec.LookPath("colordiff"); err == nil {
			diffCmd = "colordiff"
		} else {
			diffCmd = "diff"
		}

		cmd := exec.Command(diffCmd, "-urN", path, "-")
		cmd.Stdin = bytes.NewBuffer(out)
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr
		if err := cmd.Run(); err != nil {
			if err.(*exec.ExitError).ProcessState.ExitCode() > 1 {
				os.Exit(1)
			}
		} else {
			fmt.Fprintln(os.Stderr, "[no diff]")
		}
	} else {
		os.Stdout.Write(out)
	}
}