diff --git a/d2cli/help.go b/d2cli/help.go index 010118c22..6d1ea0567 100644 --- a/d2cli/help.go +++ b/d2cli/help.go @@ -39,7 +39,7 @@ Subcommands: %[1]s layout [name] - Display long help for a particular layout engine, including its configuration options %[1]s themes - Lists available themes %[1]s fmt file.d2 ... - Format passed files - %[1]s play file.d2 - Opens the file in playground + %[1]s play file.d2 - Opens the file in playground, an online web viewer (https://play.d2lang.com) 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 7823db6b8..de4dded2a 100644 --- a/d2cli/main.go +++ b/d2cli/main.go @@ -155,7 +155,7 @@ func Run(ctx context.Context, ms *xmain.State) (err error) { case "fmt": return fmtCmd(ctx, ms) case "play": - return playSubcommand(ctx, ms) + return playCmd(ctx, ms) case "version": if len(ms.Opts.Flags.Args()) > 1 { return xmain.UsageErrorf("version subcommand accepts no arguments") diff --git a/d2cli/play.go b/d2cli/play.go index 9bbd6cf25..f32590576 100644 --- a/d2cli/play.go +++ b/d2cli/play.go @@ -3,6 +3,7 @@ package d2cli import ( "context" "fmt" + "io" "os" "oss.terrastruct.com/d2/lib/urlenc" @@ -10,9 +11,9 @@ import ( "oss.terrastruct.com/util-go/xmain" ) -func playSubcommand(ctx context.Context, ms *xmain.State) error { +func playCmd(ctx context.Context, ms *xmain.State) error { if len(ms.Opts.Flags.Args()) != 2 { - return xmain.UsageErrorf("play must be passed one file to open") + return xmain.UsageErrorf("play must be passed one argument: either a filepath or '-' for stdin") } filepath := ms.Opts.Flags.Args()[1] @@ -33,7 +34,7 @@ func playSubcommand(ctx context.Context, ms *xmain.State) error { sketchNumber = 0 } - fileRaw, err := readFile(filepath) + fileRaw, err := readInput(filepath) if err != nil { return err } @@ -43,17 +44,24 @@ func playSubcommand(ctx context.Context, ms *xmain.State) error { return err } - url := fmt.Sprintf("https://play.d2lang.com/?l=&script=%s&sketch=%d&theme=%d&", encoded, sketchNumber, theme) + url := fmt.Sprintf("https://play.d2lang.com/?script=%s&sketch=%d&theme=%d&", encoded, sketchNumber, theme) openBrowser(ctx, ms, url) return nil } -func readFile(filepath string) (string, error) { +func readInput(filepath string) (string, error) { + if filepath == "-" { + data, err := io.ReadAll(os.Stdin) + if err != nil { + return "", fmt.Errorf("error reading from stdin: %w", err) + } + return string(data), nil + } + data, err := os.ReadFile(filepath) if err != nil { return "", xmain.UsageErrorf(err.Error()) } - return string(data), nil }