Skip to content

Commit

Permalink
internal/cmd/weave: minor improvements
Browse files Browse the repository at this point in the history
- 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 <[email protected]>
Run-TryBot: Jonathan Amsterdam <[email protected]>
Reviewed-by: Alan Donovan <[email protected]>
  • Loading branch information
jba committed May 15, 2023
1 parent 61060d6 commit 5bec756
Showing 1 changed file with 37 additions and 5 deletions.
42 changes: 37 additions & 5 deletions internal/cmd/weave/weave.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand All @@ -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() {
Expand All @@ -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 {
Expand All @@ -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 := ""
Expand All @@ -96,7 +123,9 @@ func main() {
default:
fmt.Println(line)
}

}
if in.Err() != nil {
log.Fatal(in.Err())
}
}

Expand Down Expand Up @@ -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)
}
Expand Down

0 comments on commit 5bec756

Please sign in to comment.