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 <gobot@golang.org>
Run-TryBot: Jonathan Amsterdam <jba@google.com>
Reviewed-by: Alan Donovan <adonovan@google.com>
This commit is contained in:
Jonathan Amsterdam 2023-05-12 09:31:27 -04:00
Родитель 61060d64ef
Коммит 5bec756976
1 изменённых файлов: 37 добавлений и 5 удалений

Просмотреть файл

@ -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("<!-- Autogenerated by weave; DO NOT EDIT -->")
// 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)
}