diff --git a/codegen.go b/codegen.go index 85bd1e5..e326ac7 100644 --- a/codegen.go +++ b/codegen.go @@ -89,7 +89,7 @@ func (t *CodeTemplate) CreateFile(filePath string, data interface{}) error { code := t.Buffer.Bytes() // Enforce code generation standard https://golang.org/s/generatedcode - if !GeneratedCodeRegexp.Match(code) { + if !isGenerated(code) { return nil, errors.New("output does not follow standard defined at https://golang.org/s/generatedcode") } diff --git a/generated_ast.go b/generated_ast.go new file mode 100644 index 0000000..8426a09 --- /dev/null +++ b/generated_ast.go @@ -0,0 +1,37 @@ +//go:build go1.21 +// +build go1.21 + +/* +Copyright 2025 Olivier Mengué + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package codegen + +import ( + "go/ast" + "go/parser" + "go/token" +) + +func isGenerated(code []byte) bool { + // Code from https://cs.opensource.google/go/go/+/refs/tags/go1.24.5:src/go/ast/issues_test.go;l=127 + fset := token.NewFileSet() + f, _ := parser.ParseFile(fset, "", code, parser.PackageClauseOnly|parser.ParseComments) + if f == nil { + return false + } + + return ast.IsGenerated(f) +} diff --git a/generated_regexp.go b/generated_regexp.go new file mode 100644 index 0000000..c25d3ae --- /dev/null +++ b/generated_regexp.go @@ -0,0 +1,24 @@ +//go:build !go1.21 +// +build !go1.21 + +/* +Copyright 2025 Olivier Mengué + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +package codegen + +func isGenerated(code []byte) bool { + return GeneratedCodeRegexp.Match(code) +}