Skip to content

Commit 9a80c0a

Browse files
committed
Use go/ast.IsGenerated
Use go/ast.IsGenerated (instead of our GeneratedCodeRegexp) to detect the generated code tag. Closes #3.
1 parent c59b0d5 commit 9a80c0a

File tree

3 files changed

+60
-1
lines changed

3 files changed

+60
-1
lines changed

codegen.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,7 @@ func (t *CodeTemplate) CreateFile(filePath string, data interface{}) error {
8989
code := t.Buffer.Bytes()
9090

9191
// Enforce code generation standard https://golang.org/s/generatedcode
92-
if !GeneratedCodeRegexp.Match(code) {
92+
if !isGenerated(code) {
9393
return nil, errors.New("output does not follow standard defined at https://golang.org/s/generatedcode")
9494
}
9595

generated_ast.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
//go:build go1.21
2+
3+
/*
4+
Copyright 2025 Olivier Mengué
5+
6+
Licensed under the Apache License, Version 2.0 (the "License");
7+
you may not use this file except in compliance with the License.
8+
You may obtain a copy of the License at
9+
10+
http://www.apache.org/licenses/LICENSE-2.0
11+
12+
Unless required by applicable law or agreed to in writing, software
13+
distributed under the License is distributed on an "AS IS" BASIS,
14+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
See the License for the specific language governing permissions and
16+
limitations under the License.
17+
*/
18+
19+
package codegen
20+
21+
import (
22+
"go/ast"
23+
"go/parser"
24+
"go/token"
25+
)
26+
27+
func isGenerated(code []byte) bool {
28+
// Code from https://cs.opensource.google/go/go/+/refs/tags/go1.24.5:src/go/ast/issues_test.go;l=127
29+
fset := token.NewFileSet()
30+
f, _ := parser.ParseFile(fset, "", code, parser.PackageClauseOnly|parser.ParseComments)
31+
if f == nil {
32+
return false
33+
}
34+
35+
return ast.IsGenerated(f)
36+
}

generated_regexp.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
//go:build !go1.21
2+
3+
/*
4+
Copyright 2025 Olivier Mengué
5+
6+
Licensed under the Apache License, Version 2.0 (the "License");
7+
you may not use this file except in compliance with the License.
8+
You may obtain a copy of the License at
9+
10+
http://www.apache.org/licenses/LICENSE-2.0
11+
12+
Unless required by applicable law or agreed to in writing, software
13+
distributed under the License is distributed on an "AS IS" BASIS,
14+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15+
See the License for the specific language governing permissions and
16+
limitations under the License.
17+
*/
18+
19+
package codegen
20+
21+
func isGenerated(code []byte) bool {
22+
return GeneratedCodeRegexp.Match(code)
23+
}

0 commit comments

Comments
 (0)