diff --git a/README.md b/README.md index eea2507..1d13242 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,10 @@ Flags take Graphviz's glued form (`-Tpng`, `-oout.png`) as well as the spaced one. `-V` prints the version, `-h` the usage. Exit status is 0 on success, 1 on an input or rendering error, 2 on a usage error. An error Graphviz reports while it goes on drawing (a record or HTML label it cannot read) is a status 1 -with the rendering written all the same, as with Graphviz's `dot`. +with the rendering written all the same, as with Graphviz's `dot`. An input +with no graph in it, empty or comments alone, is nothing to draw: status 0 and +nothing written, no output file made or replaced, as with Graphviz's `dot` +again. ``` go tool pprof -dot cpu.prof | dot -Tpng -o profile.png diff --git a/cmd/dot/contract_test.go b/cmd/dot/contract_test.go index ed8e807..67550d6 100644 --- a/cmd/dot/contract_test.go +++ b/cmd/dot/contract_test.go @@ -153,7 +153,6 @@ func TestExitStatusesAndStreams(t *testing.T) { {"a missing file", "", []string{filepath.Join(dir, "missing.dot")}, 1, "", false}, {"a directory as input", "", []string{dir}, 1, "", false}, {"a syntax error", "digraph { a -> ", nil, 1, "", false}, - {"empty input", "", nil, 1, "", false}, {"an undirected edge in a digraph", "digraph { a -- b }", nil, 1, "", false}, } @@ -196,6 +195,112 @@ func TestExitStatusesAndStreams(t *testing.T) { } } +// A text with no graph in it, empty, blank or comments alone, is nothing to +// draw and no failure, as with Graphviz's dot: exit 0, nothing on either +// stream, and with -o no file made and the one at the path left as it was. +// A text that cannot be read stays a failure. +func TestATextWithNoGraphIsNothingToDraw(t *testing.T) { + t.Parallel() + + for name, text := range map[string]string{ + "empty": "", + "blank": " \t\n\n", + "a line comment": "// nothing\n", + "a block comment": "/* nothing */", + "a preprocessor line": "# 1 \"nothing\"\n", + } { + t.Run(name, func(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + + for _, format := range []string{"dot", "svg", "png"} { + got := dot(t, dir, text, "-T"+format) + if got.code != 0 || got.stdout != "" || got.stderr != "" { + t.Errorf( + "-T%s: exit %d, stdout %q, stderr %q; want 0 and nothing", + format, + got.code, + got.stdout, + got.stderr, + ) + } + } + + if got := dot( + t, + dir, + text, + "-Tsvg", + "-o", + "new.svg", + ); got.code != 0 || got.stdout != "" || + got.stderr != "" { + t.Errorf( + "-o to a new path: exit %d, stdout %q, stderr %q; want 0 and nothing", + got.code, + got.stdout, + got.stderr, + ) + } + + if entries := names(t, dir); len(entries) != 0 { + t.Errorf("-o to a new path left %v in the directory, want nothing", entries) + } + + kept := filepath.Join(dir, "kept.svg") + if err := os.WriteFile(kept, []byte("previous"), 0o600); err != nil { + t.Fatal(err) + } + + if got := dot( + t, + dir, + text, + "-Tsvg", + "-o", + "kept.svg", + ); got.code != 0 || got.stdout != "" || + got.stderr != "" { + t.Errorf( + "-o over a file: exit %d, stdout %q, stderr %q; want 0 and nothing", + got.code, + got.stdout, + got.stderr, + ) + } + + if data, err := os.ReadFile(kept); err != nil || string(data) != "previous" { + t.Errorf("-o over a file left %q (%v), want it as it was", data, err) + } + + if entries := names(t, dir); len(entries) != 1 { + t.Errorf("-o over a file left %v in the directory, want the one file", entries) + } + + t.Run("as Graphviz's dot has it", func(t *testing.T) { + out, err := native(t, nativeDot(t), text, "-Tsvg") + if err != nil || len(out) != 0 { + t.Errorf("the native dot wrote %d bytes and returned %v, want nothing and success", len(out), err) + } + }) + }) + } + + for name, text := range map[string]string{"a graph cut short": "digraph { a -> ", "a word": "nothing"} { + if got := dot(t, t.TempDir(), text, "-Tsvg"); got.code != 1 || got.stdout != "" || + !strings.HasPrefix(got.stderr, "dot: parse input:") { + t.Errorf( + "%s: exit %d, stdout %q, stderr %q; want 1 and a parse error", + name, + got.code, + got.stdout, + got.stderr, + ) + } + } +} + // Every -o shape: glued and spaced, a bare name, a relative path, an // absolute path, a path in a missing directory, the input's own path, and // an existing file, each leaving exactly the output behind and nothing diff --git a/cmd/dot/fuzz_test.go b/cmd/dot/fuzz_test.go index 2dabc02..2f7f8d6 100644 --- a/cmd/dot/fuzz_test.go +++ b/cmd/dot/fuzz_test.go @@ -2,18 +2,22 @@ package main // Past the fixed cases: any bytes as the input, under every format. The // command never panics or faults in the engine; it exits 0 with a rendering -// on stdout and nothing on stderr, or 1 with "dot: " on stderr. An exit 1 -// has a rendering on stdout only for an error Graphviz reported while it -// drew on, which stderr then says. Under -o the path holds a rendering when -// stdout had one, and is as it was when it had none. +// on stdout and nothing on stderr, or 1 with "dot: " on stderr. An exit 0 +// with nothing on stdout is a text with no graph in it, and only that. An +// exit 1 has a rendering on stdout only for an error Graphviz reported +// while it drew on, which stderr then says. Under -o the path holds a +// rendering when stdout had one, and is as it was when it had none. import ( "bytes" + "errors" "os" "path/filepath" "strings" "testing" + "github.com/forkcloser/go-graphviz" + "github.com/forkcloser/go-graphviz/cgraph" "github.com/forkcloser/go-graphviz/gvc" ) @@ -42,8 +46,17 @@ func FuzzInput(f *testing.F) { switch code { case 0: - if stderr.Len() != 0 || stdout.Len() == 0 { - t.Fatalf("exit 0 with stderr %q and %d bytes out", stderr.String(), stdout.Len()) + if stderr.Len() != 0 { + t.Fatalf("exit 0 with stderr %q", stderr.String()) + } + + parsed, err := graphviz.ParseBytes([]byte(input)) + if parsed != nil { + _ = parsed.Close() + } + + if (stdout.Len() == 0) != errors.Is(err, cgraph.ErrNoGraph) { + t.Fatalf("exit 0 with %d bytes out for a text that parses to %v", stdout.Len(), err) } case 1: if !strings.HasPrefix(stderr.String(), "dot: ") { diff --git a/cmd/dot/main.go b/cmd/dot/main.go index eb05f44..556b637 100644 --- a/cmd/dot/main.go +++ b/cmd/dot/main.go @@ -11,7 +11,6 @@ package main import ( - "bytes" "context" "errors" "fmt" @@ -22,6 +21,7 @@ import ( "strings" "github.com/forkcloser/go-graphviz" + "github.com/forkcloser/go-graphviz/cgraph" "github.com/forkcloser/go-graphviz/gvc" "github.com/forkcloser/xos" ) @@ -47,13 +47,7 @@ type options struct { help bool } -var ( - errUsage = errors.New("usage") - - // errNoGraph is empty or whitespace-only input, which parses to a nil - // graph without an error. - errNoGraph = errors.New("no graph found") -) +var errUsage = errors.New("usage") // layoutNamed is the layout engine graphviz knows by name. func layoutNamed(name string) (graphviz.Layout, bool) { @@ -184,23 +178,8 @@ func version() string { return "(devel)" } -// render reads DOT from in, lays it out and writes format to out. -func render(ctx context.Context, opt options, in io.Reader, out io.Writer) error { - src, err := io.ReadAll(in) - if err != nil { - return fmt.Errorf("read input: %w", err) - } - - graph, err := graphviz.ParseBytes(src) - if err != nil { - return fmt.Errorf("parse input: %w", err) - } - // Empty or whitespace-only input parses to a nil graph without an error, - // and rendering nil faults inside the WASM engine. - if graph == nil { - return fmt.Errorf("parse input: %w", errNoGraph) - } - +// render lays graph out and writes it to out in the format asked for. +func render(ctx context.Context, opt options, graph *graphviz.Graph, out io.Writer) error { engine, err := graphviz.New(ctx) if err != nil { return fmt.Errorf("start graphviz: %w", err) @@ -217,6 +196,23 @@ func render(ctx context.Context, opt options, in io.Reader, out io.Writer) error return nil } +// read is the DOT text of the input: the file named, or standard input. +func read(opt options, stdin io.Reader) ([]byte, error) { + if opt.input != "" && opt.input != "-" { + // Read whole and closed here, not held open through the render: + // with -o naming the input, the rendering is renamed over it. + //nolint:wrapcheck // os's *PathError already names the operation and the path + return xos.ReadFile(opt.input) + } + + src, err := io.ReadAll(stdin) + if err != nil { + return nil, fmt.Errorf("read input: %w", err) + } + + return src, nil +} + func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { opt, err := parseArgs(args) if err != nil { @@ -235,31 +231,34 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return 0 } - input := stdin + src, err := read(opt, stdin) + if err != nil { + fmt.Fprintln(stderr, "dot:", err) + return 1 + } - if opt.input != "" && opt.input != "-" { - // Read whole and closed here, not held open through the render: - // render reads its input whole anyway, and with -o naming the input - // the rendering is renamed over it. - src, err := xos.ReadFile(opt.input) - if err != nil { - fmt.Fprintln(stderr, "dot:", err) - return 1 - } + graph, err := graphviz.ParseBytes(src) - input = bytes.NewReader(src) + switch { + case errors.Is(err, cgraph.ErrNoGraph): + // A text with no graph in it, empty or comments alone, is nothing to + // draw: as Graphviz's dot, nothing is written, no file is made or + // replaced, and that is no failure. + return 0 + case err != nil: + fmt.Fprintln(stderr, "dot: parse input:", err) + return 1 } - if opt.output == "" { - if err := render(context.Background(), opt, input, stdout); err != nil { - fmt.Fprintln(stderr, "dot:", err) - return 1 - } + defer func() { _ = graph.Close() }() - return 0 + if opt.output == "" { + err = render(context.Background(), opt, graph, stdout) + } else { + err = renderToFile(context.Background(), opt, graph) } - if err := renderToFile(context.Background(), opt, input); err != nil { + if err != nil { fmt.Fprintln(stderr, "dot:", err) return 1 } @@ -271,7 +270,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { // it onto the path only once the render has completed: a failed render, an // interrupt or a full disk leaves whatever was at the path untouched rather // than a truncated file that a later build would take for a finished one. -func renderToFile(ctx context.Context, opt options, input io.Reader) error { +func renderToFile(ctx context.Context, opt options, graph *graphviz.Graph) error { dir, base := filepath.Split(opt.output) if dir == "" { // A bare name: beside it is the working directory, not the @@ -297,7 +296,7 @@ func renderToFile(ctx context.Context, opt options, input io.Reader) error { // An error that is gvc.ErrReported came after the whole rendering: the // file goes to its path all the same, and the error to the exit status. - reported := render(ctx, opt, input, tmp) + reported := render(ctx, opt, graph, tmp) if reported != nil && !errors.Is(reported, gvc.ErrReported) { return reported } diff --git a/cmd/dot/main_test.go b/cmd/dot/main_test.go index 263ffef..c69aee5 100644 --- a/cmd/dot/main_test.go +++ b/cmd/dot/main_test.go @@ -151,22 +151,6 @@ func FuzzParseArgs(f *testing.F) { }) } -func TestEmptyInputIsAnError(t *testing.T) { - t.Parallel() - - for _, in := range []string{"", " \n"} { - var out, errb bytes.Buffer - if code := run([]string{"-Tsvg"}, strings.NewReader(in), &out, &errb); code != 1 { - t.Errorf("%q: exit %d, want 1", in, code) - } - // A fresh engine parses empty input to a nil graph; one that has - // parsed before reports a syntax error. Either is a parse error. - if !strings.HasPrefix(errb.String(), "dot: parse input:") { - t.Errorf("%q: stderr %q", in, errb.String()) - } - } -} - // TestPprofGraph renders what `go tool pprof -dot` emits, the input the // limen profile recipe hands to this command. func TestPprofGraph(t *testing.T) { diff --git a/go.mod b/go.mod index 4835991..83bfa31 100644 --- a/go.mod +++ b/go.mod @@ -3,7 +3,7 @@ module github.com/forkcloser/dot go 1.26.0 require ( - github.com/forkcloser/go-graphviz v0.6.0 + github.com/forkcloser/go-graphviz v0.6.1-0.20261122214648-1880f8661dd1 github.com/forkcloser/xos v0.1.2 ) diff --git a/go.sum b/go.sum index a942f4e..9d9b311 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -github.com/forkcloser/go-graphviz v0.6.0 h1:dOB+9sLqtxs9J9OhblzgweOyGUP0Ks5Rm71ELG/4JF4= -github.com/forkcloser/go-graphviz v0.6.0/go.mod h1:SC+ch2AgTanRZJH8JpOw99BOCnLQdBLEu1xz4QuihcE= +github.com/forkcloser/go-graphviz v0.6.1-0.20261122214648-1880f8661dd1 h1:P6UQgrHNU2SYUXRm2SVE/qYhwAUJ7Ji14y6T5PZN3wU= +github.com/forkcloser/go-graphviz v0.6.1-0.20261122214648-1880f8661dd1/go.mod h1:SC+ch2AgTanRZJH8JpOw99BOCnLQdBLEu1xz4QuihcE= github.com/forkcloser/xos v0.1.2 h1:7TTH/bJ8hRIBIJPZp5WgIY//bgJFlyd+dpsgSEjnwOM= github.com/forkcloser/xos v0.1.2/go.mod h1:BxyGnZr+xW0m+0ph1xQ0qwHYs30hiXeUP7foOlKvxP0= github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU=