mirror of
https://github.com/schollz/cowyo.git
synced 2023-08-10 21:13:00 +03:00
52 lines
1.7 KiB
Go
52 lines
1.7 KiB
Go
|
// Package analysis provides a routine that determines if a file is generated or handcrafted.
|
||
|
//
|
||
|
// Deprecated: Use github.com/shurcooL/go/generated package instead. This implementation
|
||
|
// was done ad-hoc before a standard was proposed.
|
||
|
package analysis
|
||
|
|
||
|
import (
|
||
|
"bufio"
|
||
|
"io"
|
||
|
"os"
|
||
|
"path/filepath"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// IsFileGenerated returns true if the specified file is generated, or false if it's handcrafted.
|
||
|
// rootDir is the filepath of root directory, but name is a '/'-separated path to file.
|
||
|
//
|
||
|
// It considers vendored files as "generated", in the sense that they are not the canonical
|
||
|
// version of a file. This behavior would ideally be factored out into a higher level utility,
|
||
|
// since it has nothing to do with generated comments.
|
||
|
//
|
||
|
// Deprecated: Use generated.ParseFile instead, which is more well defined because it
|
||
|
// implements a specification.
|
||
|
func IsFileGenerated(rootDir, name string) (bool, error) {
|
||
|
// Detect from name.
|
||
|
switch {
|
||
|
case strings.HasPrefix(name, "vendor/") || strings.Contains(name, "/vendor/"):
|
||
|
return true, nil
|
||
|
case strings.HasPrefix(name, "Godeps/"):
|
||
|
return true, nil
|
||
|
}
|
||
|
|
||
|
// Detect from file contents.
|
||
|
f, err := os.Open(filepath.Join(rootDir, filepath.FromSlash(name)))
|
||
|
if err != nil {
|
||
|
return false, err
|
||
|
}
|
||
|
defer f.Close()
|
||
|
r := bufio.NewReader(f)
|
||
|
s, err := r.ReadString('\n')
|
||
|
if err == io.EOF {
|
||
|
// Empty file or exactly 1 line is not considered to be generated.
|
||
|
return false, nil
|
||
|
} else if err != nil {
|
||
|
return false, err
|
||
|
}
|
||
|
if strings.Contains(s, "Code generated by") { // Consistent with https://golang.org/cl/15073.
|
||
|
return true, nil
|
||
|
}
|
||
|
return (strings.Contains(s, "GENERATED") || strings.Contains(s, "generated")) && strings.Contains(s, "DO NOT EDIT"), nil
|
||
|
}
|