@@ -71,7 +71,11 @@ const expectedHeader = `// Copyright 202\d Google LLC
7171// you may not use this file except in compliance with the License\.
7272// You may obtain a copy of the License at`
7373
74- var headerRegex = regexp .MustCompile ("(?s)" + expectedHeader )
74+ var (
75+ headerRegex = regexp .MustCompile ("(?s)" + expectedHeader )
76+ dockerGoVersionRegex = regexp .MustCompile (`golang:(?P<version>[^ \n]+)` )
77+ modGoVersionRegex = regexp .MustCompile (`\ngo\s+(?P<version>[^ \n]+)` )
78+ )
7579
7680func TestHeaders (t * testing.T ) {
7781 sfs := os .DirFS ("." )
@@ -159,6 +163,63 @@ func hasValidHeader(path string, r io.Reader) (bool, error) {
159163 return headerRegex .Match (allBytes ), nil
160164}
161165
166+ // TestConsistentGoVersions walks the directory tree and checks Dockerfiles and go.mod files for specified Go versions.
167+ // It ensures that only one unique Go version is specified across all found files to maintain consistency. The test
168+ // fails if multiple Go versions are detected.
169+ // TODO(https://github.com/googleapis/librarian/issues/2739): remove this test once is resolved.
170+ func TestConsistentGoVersions (t * testing.T ) {
171+ goVersions := make (map [string ][]string )
172+ sfs := os .DirFS ("." )
173+ err := fs .WalkDir (sfs , "." , func (path string , d fs.DirEntry , err error ) error {
174+ if err != nil {
175+ return err
176+ }
177+
178+ if strings .HasSuffix (path , "Dockerfile" ) {
179+ return recordGoVersion (path , sfs , dockerGoVersionRegex , goVersions )
180+ }
181+
182+ if strings .HasSuffix (path , "go.mod" ) {
183+ return recordGoVersion (path , sfs , modGoVersionRegex , goVersions )
184+ }
185+
186+ return nil
187+ })
188+ if err != nil {
189+ t .Fatal (err )
190+ }
191+
192+ if len (goVersions ) > 1 {
193+ for ver , paths := range goVersions {
194+ t .Logf ("%s found in %s" , ver , strings .Join (paths , "\n " ))
195+ }
196+ t .Error ("found multiple golang versions" )
197+ }
198+ }
199+
200+ // recordGoVersion reads the content of the file at the given path, finds all matches of the provided regular
201+ // expression (re), and records the first capturing group (expected to be the version string) in the goVersions map
202+ // along with the file path.
203+ func recordGoVersion (path string , sfs fs.FS , re * regexp.Regexp , goVersions map [string ][]string ) error {
204+ f , err := sfs .Open (path )
205+ if err != nil {
206+ return err
207+ }
208+ defer f .Close ()
209+
210+ allBytes , err := io .ReadAll (f )
211+ if err != nil {
212+ return err
213+ }
214+
215+ matches := re .FindAllStringSubmatch (string (allBytes ), - 1 )
216+ for _ , match := range matches {
217+ goVersions [match [1 ]] = append (goVersions [match [1 ]], path )
218+ }
219+
220+ return nil
221+ }
222+
162223func TestGolangCILint (t * testing.T ) {
163224 rungo (
t ,
"run" ,
"github.com/golangci/golangci-lint/v2/cmd/[email protected] " ,
"run" )
164225}
0 commit comments