| 17 | const minimumGoVersionForGenerateStdHTTPServer = 22 |
| 18 | |
| 19 | func findAndParseGoModuleForDepth(dir string, maxDepth int) (string, *modfile.File, error) { |
| 20 | absDir, err := filepath.Abs(dir) |
| 21 | if err != nil { |
| 22 | return "", nil, fmt.Errorf("failed to determine absolute path for %v: %w", dir, err) |
| 23 | } |
| 24 | currentDir := absDir |
| 25 | |
| 26 | for i := 0; i <= maxDepth; i++ { |
| 27 | goModPath := filepath.Join(currentDir, "go.mod") |
| 28 | if _, err := os.Stat(goModPath); err == nil { |
| 29 | goModContent, err := os.ReadFile(goModPath) |
| 30 | if err != nil { |
| 31 | return "", nil, fmt.Errorf("failed to read `go.mod`: %w", err) |
| 32 | } |
| 33 | |
| 34 | mod, err := modfile.ParseLax("go.mod", goModContent, nil) |
| 35 | if err != nil { |
| 36 | return "", nil, fmt.Errorf("failed to parse `go.mod`: %w", err) |
| 37 | } |
| 38 | |
| 39 | return goModPath, mod, nil |
| 40 | } |
| 41 | |
| 42 | goModPath = filepath.Join(currentDir, "tools.mod") |
| 43 | if _, err := os.Stat(goModPath); err == nil { |
| 44 | goModContent, err := os.ReadFile(goModPath) |
| 45 | if err != nil { |
| 46 | return "", nil, fmt.Errorf("failed to read `tools.mod`: %w", err) |
| 47 | } |
| 48 | |
| 49 | parsedModFile, err := modfile.ParseLax("tools.mod", goModContent, nil) |
| 50 | if err != nil { |
| 51 | return "", nil, fmt.Errorf("failed to parse `tools.mod`: %w", err) |
| 52 | } |
| 53 | |
| 54 | return goModPath, parsedModFile, nil |
| 55 | } |
| 56 | |
| 57 | parentDir := filepath.Dir(currentDir) |
| 58 | // NOTE that this may not work particularly well on Windows |
| 59 | if parentDir == "/" { |
| 60 | break |
| 61 | } |
| 62 | |
| 63 | currentDir = parentDir |
| 64 | } |
| 65 | |
| 66 | return "", nil, fmt.Errorf("no `go.mod` or `tools.mod` file found within %d levels upwards from %s", maxDepth, absDir) |
| 67 | } |
| 68 | |
| 69 | // hasMinimalMinorGoDirective indicates that the Go module (`mod`) has a minor version greater than or equal to the `expected`'s |
| 70 | // This only applies to the `go` directive: |