From 5bec756976671f30903223ec46ff8a70dced4954 Mon Sep 17 00:00:00 2001 From: Jonathan Amsterdam Date: Fri, 12 May 2023 09:31:27 -0400 Subject: [PATCH] internal/cmd/weave: minor improvements - Add some documentation. - Check bufio.Scanner errors. - Generalize the package path in caption output. Change-Id: I1f30b555ec8533464fb29af05fdcb0c5d926c18e Reviewed-on: https://go-review.googlesource.com/c/example/+/494596 TryBot-Result: Gopher Robot Run-TryBot: Jonathan Amsterdam Reviewed-by: Alan Donovan --- internal/cmd/weave/weave.go | 42 ++++++++++++++++++++++++++++++++----- 1 file changed, 37 insertions(+), 5 deletions(-) diff --git a/internal/cmd/weave/weave.go b/internal/cmd/weave/weave.go index bf8264aa..07ed8bfe 100644 --- a/internal/cmd/weave/weave.go +++ b/internal/cmd/weave/weave.go @@ -3,7 +3,25 @@ // // Example usage: // -// $ go run weave.go go-types.md > README.md +// $ go run internal/cmd/weave go-types.md > README.md +// +// The weave command copies lines of the input file to standard output, with two +// exceptions: +// +// If a line begins with "%toc", it is replaced with a table of contents +// consisting of links to the top two levels of headers ("#" and "##"). +// +// If a line begins with "%include FILENAME TAG", it is replaced with the lines +// of the file between lines containing "!+TAG" and "!-TAG". TAG can be omitted, +// in which case the delimiters are simply "!+" and "!-". +// +// Before the included lines, a line of the form +// +// // go get PACKAGE +// +// is output, where PACKAGE is constructed from the module path, the +// base name of the current directory, and the directory of FILENAME. +// This caption can be supressed by putting "-" as the final word of the %include line. package main import ( @@ -30,9 +48,15 @@ func main() { } defer f.Close() + wd, err := os.Getwd() + if err != nil { + log.Fatal(err) + } + curDir := filepath.Base(wd) + fmt.Println("") - // Pass 1. + // Pass 1: extract table of contents. var toc []string in := bufio.NewScanner(f) for in.Scan() { @@ -56,6 +80,9 @@ func main() { toc = append(toc, line) } } + if in.Err() != nil { + log.Fatal(in.Err()) + } // Pass 2. if _, err := f.Seek(0, os.SEEK_SET); err != nil { @@ -78,8 +105,8 @@ func main() { // Show caption unless '-' follows. if len(words) < 4 || words[3] != "-" { - fmt.Printf(" // go get golang.org/x/example/gotypes/%s\n\n", - filepath.Dir(filename)) + fmt.Printf(" // go get golang.org/x/example/%s/%s\n\n", + curDir, filepath.Dir(filename)) } section := "" @@ -96,7 +123,9 @@ func main() { default: fmt.Println(line) } - + } + if in.Err() != nil { + log.Fatal(in.Err()) } } @@ -135,6 +164,9 @@ func include(file, tag string) (string, error) { text.WriteByte('\n') } } + if in.Err() != nil { + return "", in.Err() + } if text.Len() == 0 { return "", fmt.Errorf("no lines of %s matched tag %q", file, tag) }