Skip to content

Commit 9e0901a

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 9e0901a

File tree

3 files changed

+61
-1
lines changed

3 files changed

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

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)