...
1 package jsonnetx
2
3 import (
4 "fmt"
5 "io/ioutil"
6 "os"
7
8 "github.com/bmatcuk/doublestar/v2"
9 "github.com/google/go-jsonnet/formatter"
10 "github.com/spf13/cobra"
11
12 "github.com/ory/x/cmdx"
13 "github.com/ory/x/flagx"
14 )
15
16
17 var FormatCommand = &cobra.Command{
18 Use: "format path/to/files/*.jsonnet [more/files.jsonnet, [supports/**/{foo,bar}.jsonnet]]",
19 Long: `Formats JSONNet files using the official JSONNet formatter.
20
21 Use -w or --write to write output back to files instead of stdout.
22
23 ` + GlobHelp,
24 Args: cobra.MinimumNArgs(1),
25 Run: func(cmd *cobra.Command, args []string) {
26 verbose := flagx.MustGetBool(cmd, "verbose")
27 for _, pattern := range args {
28 files, err := doublestar.Glob(pattern)
29 cmdx.Must(err, `Glob pattern "%s" is not valid: %s`, pattern, err)
30
31 shouldWrite := flagx.MustGetBool(cmd, "write")
32 for _, file := range files {
33 if fi, err := os.Stat(file); err != nil {
34 cmdx.Must(err, "Unable to stat file %s: %s", file, err)
35 } else if fi.IsDir() {
36 continue
37 }
38
39 if verbose {
40 fmt.Printf("Processing file: %s\n", file)
41 }
42
43 content, err := ioutil.ReadFile(file)
44 cmdx.Must(err, `Unable to read file "%s" because: %s`, file, err)
45
46 output, err := formatter.Format(file, string(content), formatter.DefaultOptions())
47 cmdx.Must(err, `JSONNet file "%s" could not be formatted: %s`, file, err)
48
49 if shouldWrite {
50 err := ioutil.WriteFile(file, []byte(output), 0644)
51 cmdx.Must(err, `Could not write to file "%s" because: %s`, file, err)
52 } else {
53 fmt.Println(output)
54 }
55 }
56 }
57 },
58 }
59
60 func init() {
61 FormatCommand.Flags().BoolP("write", "w", false, "Write formatted output back to file.")
62 FormatCommand.Flags().Bool("verbose", false, "Verbose output.")
63 }
64
View as plain text