address pr comments

This commit is contained in:
Alexander Wang 2025-02-04 06:40:08 -07:00
parent 7c2b8221ba
commit 5f5792847c
No known key found for this signature in database
GPG key ID: BE3937D0D52D8927
3 changed files with 16 additions and 8 deletions

View file

@ -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.

View file

@ -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")

View file

@ -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
}