forked from terrastruct/d2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfmt.go
42 lines (32 loc) · 934 Bytes
/
fmt.go
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
package main
import (
"bytes"
"context"
"oss.terrastruct.com/util-go/xdefer"
"oss.terrastruct.com/util-go/xmain"
"oss.terrastruct.com/d2/d2format"
"oss.terrastruct.com/d2/d2parser"
)
func fmtCmd(ctx context.Context, ms *xmain.State) (err error) {
defer xdefer.Errorf(&err, "failed to fmt")
ms.Opts = xmain.NewOpts(ms.Env, ms.Log, ms.Opts.Flags.Args()[1:])
if len(ms.Opts.Args) == 0 {
return xmain.UsageErrorf("fmt must be passed the file to be formatted")
} else if len(ms.Opts.Args) > 1 {
return xmain.UsageErrorf("fmt accepts only one argument for the file to be formatted")
}
inputPath := ms.Opts.Args[0]
input, err := ms.ReadPath(inputPath)
if err != nil {
return err
}
m, err := d2parser.Parse(inputPath, bytes.NewReader(input), nil)
if err != nil {
return err
}
output := []byte(d2format.Format(m))
if !bytes.Equal(output, input) {
return ms.WritePath(inputPath, output)
}
return nil
}