| 1 | // Copyright 2020 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package driverutil |
| 6 | |
| 7 | // This file defines helpers for implementing [analysis.Pass.ReadFile]. |
| 8 | |
| 9 | import ( |
| 10 | "fmt" |
| 11 | "slices" |
| 12 | |
| 13 | "golang.org/x/tools/go/analysis" |
| 14 | ) |
| 15 | |
| 16 | // A ReadFileFunc is a function that returns the |
| 17 | // contents of a file, such as [os.ReadFile]. |
| 18 | type ReadFileFunc = func(filename string) ([]byte, error) |
| 19 | |
| 20 | // CheckedReadFile returns a wrapper around a Pass.ReadFile |
| 21 | // function that performs the appropriate checks. |
| 22 | func CheckedReadFile(pass *analysis.Pass, readFile ReadFileFunc) ReadFileFunc { |
| 23 | return func(filename string) ([]byte, error) { |
| 24 | if err := CheckReadable(pass, filename); err != nil { |
| 25 | return nil, err |
| 26 | } |
| 27 | return readFile(filename) |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // CheckReadable enforces the access policy defined by the ReadFile field of [analysis.Pass]. |
| 32 | func CheckReadable(pass *analysis.Pass, filename string) error { |
| 33 | if slices.Contains(pass.OtherFiles, filename) || |
| 34 | slices.Contains(pass.IgnoredFiles, filename) { |
| 35 | return nil |
| 36 | } |
| 37 | for _, f := range pass.Files { |
| 38 | if pass.Fset.File(f.FileStart).Name() == filename { |
| 39 | return nil |
| 40 | } |
| 41 | } |
| 42 | return fmt.Errorf("Pass.ReadFile: %s is not among OtherFiles, IgnoredFiles, or names of Files", filename) |
| 43 | } |