2023-02-27 22:04:02 +00:00
|
|
|
package d2cli
|
2022-12-01 10:48:30 +00:00
|
|
|
|
|
|
|
|
import (
|
|
|
|
|
"bytes"
|
|
|
|
|
"context"
|
2023-08-02 18:38:53 +00:00
|
|
|
"os"
|
|
|
|
|
"path/filepath"
|
2022-12-01 10:48:30 +00:00
|
|
|
|
2022-12-01 19:32:57 +00:00
|
|
|
"oss.terrastruct.com/util-go/xdefer"
|
2022-12-01 10:48:30 +00:00
|
|
|
|
2022-12-01 19:19:39 +00:00
|
|
|
"oss.terrastruct.com/util-go/xmain"
|
|
|
|
|
|
2022-12-01 10:48:30 +00:00
|
|
|
"oss.terrastruct.com/d2/d2format"
|
|
|
|
|
"oss.terrastruct.com/d2/d2parser"
|
2024-12-16 23:09:31 +00:00
|
|
|
"oss.terrastruct.com/d2/lib/log"
|
2022-12-01 10:48:30 +00:00
|
|
|
)
|
|
|
|
|
|
2024-12-16 23:09:31 +00:00
|
|
|
func fmtCmd(ctx context.Context, ms *xmain.State, check bool) (err error) {
|
2022-12-01 17:21:16 +00:00
|
|
|
defer xdefer.Errorf(&err, "failed to fmt")
|
2022-12-01 10:48:30 +00:00
|
|
|
|
2023-10-31 22:52:48 +00:00
|
|
|
ms.Opts = xmain.NewOpts(ms.Env, ms.Opts.Flags.Args()[1:])
|
2022-12-01 10:48:30 +00:00
|
|
|
if len(ms.Opts.Args) == 0 {
|
2023-01-27 14:48:01 +00:00
|
|
|
return xmain.UsageErrorf("fmt must be passed at least one file to be formatted")
|
2022-12-01 10:48:30 +00:00
|
|
|
}
|
|
|
|
|
|
2024-12-16 23:09:31 +00:00
|
|
|
unformattedCount := 0
|
|
|
|
|
|
2023-01-27 14:48:01 +00:00
|
|
|
for _, inputPath := range ms.Opts.Args {
|
2023-08-02 18:38:53 +00:00
|
|
|
if inputPath != "-" {
|
|
|
|
|
inputPath = ms.AbsPath(inputPath)
|
|
|
|
|
d, err := os.Stat(inputPath)
|
|
|
|
|
if err == nil && d.IsDir() {
|
|
|
|
|
inputPath = filepath.Join(inputPath, "index.d2")
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2023-01-27 14:48:01 +00:00
|
|
|
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) {
|
2024-12-16 23:09:31 +00:00
|
|
|
if check {
|
|
|
|
|
unformattedCount += 1
|
|
|
|
|
log.Warn(ctx, inputPath)
|
|
|
|
|
} else {
|
|
|
|
|
if err := ms.WritePath(inputPath, output); err != nil {
|
|
|
|
|
return err
|
|
|
|
|
}
|
2023-08-02 01:31:38 +00:00
|
|
|
}
|
2023-01-27 14:48:01 +00:00
|
|
|
}
|
2022-12-01 10:48:30 +00:00
|
|
|
}
|
2024-12-16 23:09:31 +00:00
|
|
|
|
|
|
|
|
if unformattedCount > 0 {
|
|
|
|
|
pluralFiles := "file"
|
|
|
|
|
if unformattedCount > 1 {
|
|
|
|
|
pluralFiles = "files"
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
return xmain.ExitErrorf(1, "found %d unformatted %s. Run d2 fmt to fix.", unformattedCount, pluralFiles)
|
|
|
|
|
}
|
|
|
|
|
|
2022-12-19 21:20:41 +00:00
|
|
|
return nil
|
2022-12-01 10:48:30 +00:00
|
|
|
}
|