diff --git a/README.md b/README.md index 1d13242..7891240 100644 --- a/README.md +++ b/README.md @@ -25,13 +25,22 @@ dot [-K engine] [-T format] [-o path] [input] | input | a DOT file, or `-` | standard input | 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`. 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. +one. `-V` prints the version, `-h` the usage. + +The exit statuses are those of Graphviz's `dot`: 0 on success, 2 when the +input cannot be read (a file that is not there or may not be opened), and 1 +for every other failure: a flag, a format or a layout the command does not +know, a graph that does not parse, a rendering that fails, an output that +cannot be written. 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. 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. + +Two differences from Graphviz's `dot` are kept on purpose. `-` names standard +input, where Graphviz's `dot` takes it for an unknown option. A directory +given as the input is an error, with status 2 like any input that cannot be +read, where Graphviz's `dot` reads nothing from it, says nothing and exits 0. ``` 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 67550d6..5f25a96 100644 --- a/cmd/dot/contract_test.go +++ b/cmd/dot/contract_test.go @@ -3,8 +3,8 @@ package main // The command's contract at the process boundary, from the README: the // flags in their glued and spaced forms, -V and -h, the input as a file, // "-" or standard input, -o as a path in every shape, and the exit -// statuses 0, 1 and 2 with the usage on stderr for 2. Each case runs the -// built binary in a child. +// statuses 0, 1 and 2 with the usage on stderr for a command line the +// command cannot take. Each case runs the built binary in a child. import ( "bytes" @@ -143,15 +143,15 @@ func TestExitStatusesAndStreams(t *testing.T) { {"-h beats a bad graph", "nonsense", []string{"-h"}, 0, "usage:", false}, {"-V beats a bad graph", "nonsense", []string{"-V"}, 0, "", false}, {"-h with -V", "", []string{"-V", "-h"}, 0, "usage:", false}, - {"unknown flag", graph, []string{"-x"}, 2, "", true}, - {"unknown format", graph, []string{"-Tgif"}, 2, "", true}, - {"unknown layout", graph, []string{"-Kbogus"}, 2, "", true}, - {"a flag without its value", graph, []string{"-o"}, 2, "", true}, - {"two inputs", graph, []string{in, in}, 2, "", true}, - {"a long flag that is not help or version", graph, []string{"--format=svg"}, 2, "", true}, - {"usage error beats a missing file", "", []string{"-Tgif", filepath.Join(dir, "missing")}, 2, "", true}, - {"a missing file", "", []string{filepath.Join(dir, "missing.dot")}, 1, "", false}, - {"a directory as input", "", []string{dir}, 1, "", false}, + {"unknown flag", graph, []string{"-x"}, 1, "", true}, + {"unknown format", graph, []string{"-Tgif"}, 1, "", true}, + {"unknown layout", graph, []string{"-Kbogus"}, 1, "", true}, + {"a flag without its value", graph, []string{"-o"}, 1, "", true}, + {"two inputs", graph, []string{in, in}, 1, "", true}, + {"a long flag that is not help or version", graph, []string{"--format=svg"}, 1, "", true}, + {"usage error beats a missing file", "", []string{"-Tgif", filepath.Join(dir, "missing")}, 1, "", true}, + {"a missing file", "", []string{filepath.Join(dir, "missing.dot")}, 2, "", false}, + {"a directory as input", "", []string{dir}, 2, "", false}, {"a syntax error", "digraph { a -> ", nil, 1, "", false}, {"an undirected edge in a digraph", "digraph { a -- b }", nil, 1, "", false}, } @@ -195,6 +195,89 @@ func TestExitStatusesAndStreams(t *testing.T) { } } +// The statuses of a failure are those of Graphviz's dot: 2 for an input that +// cannot be read, 1 for a command line it cannot take. Each case is held to +// the native dot when there is one; a directory as the input, where the +// command differs from it on purpose, is in the table above alone. +func TestFailuresExitAsGraphvizsDot(t *testing.T) { + t.Parallel() + + dir := t.TempDir() + + if err := os.WriteFile(filepath.Join(dir, "in.dot"), []byte(graph), 0o600); err != nil { + t.Fatal(err) + } + + // A file that is there and may not be opened. Where the mode does not + // refuse the open (Windows, a run as root), the case is skipped. + if err := os.WriteFile(filepath.Join(dir, "closed.dot"), []byte(graph), 0o000); err != nil { + t.Fatal(err) + } + + closed, err := os.Open(filepath.Join(dir, "closed.dot")) + if err == nil { + _ = closed.Close() + } + + cases := []struct { + name string + args []string + code int + skip bool + }{ + {"a file that is not there", []string{"missing.dot"}, 2, false}, + {"a file that may not be opened", []string{"closed.dot"}, 2, err == nil}, + {"an empty name", []string{""}, 2, false}, + {"a flag neither knows", []string{"-Q", "in.dot"}, 1, false}, + {"a format neither knows", []string{"-Tnope", "in.dot"}, 1, false}, + {"a layout neither knows", []string{"-Knope", "in.dot"}, 1, false}, + {"-T without its value", []string{"in.dot", "-T"}, 1, false}, + {"-K without its value", []string{"in.dot", "-K"}, 1, false}, + {"-o without its value", []string{"in.dot", "-o"}, 1, false}, + {"a bad flag before a missing file", []string{"-Tnope", "missing.dot"}, 1, false}, + } + + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + t.Parallel() + + if c.skip { + t.Skip("the file opens whatever its mode") + } + + // A graph waits on standard input: none of these reads it. + got := dot(t, dir, graph, c.args...) + if got.code != c.code || got.stdout != "" || !strings.HasPrefix(got.stderr, "dot: ") { + t.Fatalf( + "exit %d, stdout %q, stderr %q; want %d, nothing and a message", + got.code, + got.stdout, + got.stderr, + c.code, + ) + } + + t.Run("as Graphviz's dot has it", func(t *testing.T) { + cmd := child(t, nativeDot(t), c.args...) + cmd.Dir = dir + cmd.Stdin = strings.NewReader(graph) + + out, err := cmd.Output() + + exit, ok := errors.AsType[*exec.ExitError](err) + if !ok || exit.ExitCode() != c.code || len(out) != 0 { + t.Errorf( + "the native dot wrote %d bytes and returned %v, want nothing and exit %d", + len(out), + err, + c.code, + ) + } + }) + }) + } +} + // 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. diff --git a/cmd/dot/main.go b/cmd/dot/main.go index 556b637..85e2322 100644 --- a/cmd/dot/main.go +++ b/cmd/dot/main.go @@ -8,6 +8,9 @@ // The input is a file in the DOT language, or standard input when absent or // "-". Without -o the rendering goes to standard output. Flags accept both the // glued form graphviz users type (-Tpng, -oout.png) and the spaced one. +// +// The exit statuses are those of Graphviz's dot: 0 on success, 2 for an input +// that cannot be read, 1 for every other failure. package main import ( @@ -39,16 +42,27 @@ const usage = `usage: dot [-K engine] [-T format] [-o path] [input] // options is the parsed command line. type options struct { - layout graphviz.Layout - format graphviz.Format - output string - input string + layout graphviz.Layout + format graphviz.Format + output string + input string + // named says an input was given: an empty name is one, a file that + // cannot be opened, and not standard input. + named bool version bool help bool } var errUsage = errors.New("usage") +// The statuses a failure exits with, as Graphviz's dot has them: an input it +// cannot read is told apart from every other failure, a command line it +// cannot take included. +const ( + statusFailed = 1 + statusNoInput = 2 +) + // layoutNamed is the layout engine graphviz knows by name. func layoutNamed(name string) (graphviz.Layout, bool) { switch name { @@ -110,11 +124,11 @@ func parseArgs(args []string) (options, error) { case arg == "-V", arg == "--version": opt.version = true case arg == "-", !strings.HasPrefix(arg, "-"): - if opt.input != "" { + if opt.named { return opt, fmt.Errorf("%w: one input at most, got %q and %q", errUsage, opt.input, arg) } - opt.input = arg + opt.input, opt.named = arg, true default: var err error if index, err = parseFlag(&opt, args, index); err != nil { @@ -198,7 +212,7 @@ func render(ctx context.Context, opt options, graph *graphviz.Graph, out io.Writ // 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 != "-" { + if opt.named && 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 @@ -219,7 +233,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { fmt.Fprintln(stderr, "dot:", err) fmt.Fprint(stderr, usage) - return 2 + return statusFailed } switch { @@ -234,7 +248,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { src, err := read(opt, stdin) if err != nil { fmt.Fprintln(stderr, "dot:", err) - return 1 + return statusNoInput } graph, err := graphviz.ParseBytes(src) @@ -247,7 +261,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { return 0 case err != nil: fmt.Fprintln(stderr, "dot: parse input:", err) - return 1 + return statusFailed } defer func() { _ = graph.Close() }() @@ -260,7 +274,7 @@ func run(args []string, stdin io.Reader, stdout, stderr io.Writer) int { if err != nil { fmt.Fprintln(stderr, "dot:", err) - return 1 + return statusFailed } return 0 diff --git a/cmd/dot/main_test.go b/cmd/dot/main_test.go index c69aee5..a7949f7 100644 --- a/cmd/dot/main_test.go +++ b/cmd/dot/main_test.go @@ -23,12 +23,12 @@ func TestParseArgs(t *testing.T) { {nil, options{layout: graphviz.DOT, format: graphviz.GV}, false}, { []string{"-Tpng", "-oout.png", "in.dot"}, - options{layout: graphviz.DOT, format: graphviz.PNG, output: "out.png", input: "in.dot"}, + options{layout: graphviz.DOT, format: graphviz.PNG, output: "out.png", input: "in.dot", named: true}, false, }, { []string{"-T", "svg", "-o", "out.svg", "-K", "neato", "-"}, - options{layout: graphviz.NEATO, format: graphviz.SVG, output: "out.svg", input: "-"}, + options{layout: graphviz.NEATO, format: graphviz.SVG, output: "out.svg", input: "-", named: true}, false, }, {[]string{"-h"}, options{layout: graphviz.DOT, format: graphviz.GV, help: true}, false}, @@ -38,6 +38,8 @@ func TestParseArgs(t *testing.T) { {[]string{"-o"}, options{}, true}, {[]string{"-x"}, options{}, true}, {[]string{"a.dot", "b.dot"}, options{}, true}, + {[]string{""}, options{layout: graphviz.DOT, format: graphviz.GV, named: true}, false}, + {[]string{"", ""}, options{}, true}, } for _, c := range cases { got, err := parseArgs(c.args) @@ -122,12 +124,12 @@ func TestErrors(t *testing.T) { t.Parallel() var out, errb bytes.Buffer - if code := run([]string{"-Tgif"}, nil, &out, &errb); code != 2 { - t.Errorf("bad flag: exit %d, want 2", code) + if code := run([]string{"-Tgif"}, nil, &out, &errb); code != 1 { + t.Errorf("bad flag: exit %d, want 1", code) } - if code := run([]string{filepath.Join(t.TempDir(), "missing.dot")}, nil, &out, &errb); code != 1 { - t.Errorf("missing input: exit %d, want 1", code) + if code := run([]string{filepath.Join(t.TempDir(), "missing.dot")}, nil, &out, &errb); code != 2 { + t.Errorf("missing input: exit %d, want 2", code) } if code := run(nil, strings.NewReader("digraph { a -> "), &out, &errb); code != 1 {