dmitri.shuralyov.com/go/generated/...

add Parse(src io.Reader) function

This makes it possible to use this package in contexts where the .go
file is in memory or otherwise not available on disk.

For now, keep ParseFile around as a trivial helper. If it ends up being
not used in the wild much, perhaps it could be deprecated/removed later.

Fixes https://github.com/shurcooL/go/issues/31.
dmitshur committed 7 years ago commit c6f4016b8c9c279153dc353bb22eb4011e41cc70
Collapse all
generated.go
@@ -21,12 +21,12 @@ import (
	"bytes"
	"io"
	"os"
)

// ParseFile parses the source code of a single Go source file
// specified by filename, and reports whether the file contains
// Parse parses the source code of a single Go source file
// provided via src, and reports whether the file contains
// a "// Code generated ... DO NOT EDIT." line comment
// matching the specification at https://golang.org/s/generatedcode:
//
// 	Generated files are marked by a line of text that matches
// 	the regular expression, in Go syntax:
@@ -36,20 +36,12 @@ import (
// 	The .* means the tool can put whatever folderol it wants in there,
// 	but the comment must be a single line and must start with Code generated
// 	and end with DO NOT EDIT., with a period.
//
// 	The text may appear anywhere in the file.
//
// If the source couldn't be read, the error indicates the specific
// failure.
func ParseFile(filename string) (hasGeneratedComment bool, err error) {
	f, err := os.Open(filename)
	if err != nil {
		return false, err
	}
	defer f.Close()
	br := bufio.NewReader(f)
func Parse(src io.Reader) (hasGeneratedComment bool, err error) {
	br := bufio.NewReader(src)
	for {
		s, err := br.ReadBytes('\n')
		if err == io.EOF {
			return containsComment(s), nil
		} else if err != nil {
@@ -72,5 +64,16 @@ func containsComment(s []byte) bool {

var (
	prefix = []byte("// Code generated ")
	suffix = []byte(" DO NOT EDIT.")
)

// ParseFile opens the file specified by filename and uses Parse to parse it.
// If the source couldn't be read, the error indicates the specific failure.
func ParseFile(filename string) (hasGeneratedComment bool, err error) {
	f, err := os.Open(filename)
	if err != nil {
		return false, err
	}
	defer f.Close()
	return Parse(f)
}