From 0955ef608de3b0b15ca7690e3ab1e4b0913f4ad1 Mon Sep 17 00:00:00 2001 From: melsonic Date: Sun, 9 Mar 2025 22:05:16 +0530 Subject: [PATCH] ci: add validate command --- d2cli/help.go | 2 ++ d2cli/main.go | 2 ++ d2cli/validate.go | 35 +++++++++++++++++++++++++++++++++++ 3 files changed, 39 insertions(+) create mode 100644 d2cli/validate.go diff --git a/d2cli/help.go b/d2cli/help.go index eb80c85bf..6b95a2c33 100644 --- a/d2cli/help.go +++ b/d2cli/help.go @@ -23,6 +23,7 @@ Usage: %[1]s layout [name] %[1]s fmt file.d2 ... %[1]s play [--theme=0] [--sketch] file.d2 + %[1]s validate file.d2 ... %[1]s compiles and renders file.d2 to file.svg | file.png It defaults to file.svg if an output path is not provided. @@ -40,6 +41,7 @@ Subcommands: %[1]s themes - Lists available themes %[1]s fmt file.d2 ... - Format passed files %[1]s play file.d2 - Opens the file in playground, an online web viewer (https://play.d2lang.com) + %[1]s validate file.d2 ... - Validate input files See more docs and the source code at https://oss.terrastruct.com/d2. Hosted icons at https://icons.terrastruct.com. diff --git a/d2cli/main.go b/d2cli/main.go index dbf1ae2c4..3eb486d70 100644 --- a/d2cli/main.go +++ b/d2cli/main.go @@ -173,6 +173,8 @@ func Run(ctx context.Context, ms *xmain.State) (err error) { return fmtCmd(ctx, ms, *checkFlag) case "play": return playCmd(ctx, ms) + case "validate": + return validateCmd(ctx, ms) case "version": if len(ms.Opts.Flags.Args()) > 1 { return xmain.UsageErrorf("version subcommand accepts no arguments") diff --git a/d2cli/validate.go b/d2cli/validate.go new file mode 100644 index 000000000..29840ef5b --- /dev/null +++ b/d2cli/validate.go @@ -0,0 +1,35 @@ +package d2cli + +import ( + "context" + + "oss.terrastruct.com/d2/d2lib" + "oss.terrastruct.com/util-go/xdefer" + "oss.terrastruct.com/util-go/xmain" +) + +func validateCmd(ctx context.Context, ms *xmain.State) (err error) { + defer xdefer.Errorf(&err, "failed to validate") + + ms.Opts = xmain.NewOpts(ms.Env, ms.Opts.Flags.Args()[1:]) + if len(ms.Opts.Args) == 0 { + return xmain.UsageErrorf("validate must be passed at least one file to be validated") + } + + for _, inputPath := range ms.Opts.Args { + if inputPath != "-" { + inputPath = ms.AbsPath(inputPath) + } + + input, err := ms.ReadPath(inputPath) + if err != nil { + return err + } + + _, err = d2lib.Parse(ctx, string(input), nil) + if err != nil { + return err + } + } + return nil +}