|
| 1 | +// / ctx: https://ctx.ist |
| 2 | +// ,'`./ do you remember? |
| 3 | +// `.,'\ |
| 4 | +// \ Copyright 2026-present Context contributors. |
| 5 | +// SPDX-License-Identifier: Apache-2.0 |
| 6 | + |
| 7 | +package audit |
| 8 | + |
| 9 | +import ( |
| 10 | + "go/ast" |
| 11 | + "strings" |
| 12 | + "testing" |
| 13 | +) |
| 14 | + |
| 15 | +// printfMethods lists cobra cmd.Printf-style methods |
| 16 | +// that bypass the write package formatting pipeline. |
| 17 | +var printfMethods = map[string]bool{ |
| 18 | + "Printf": true, |
| 19 | + "PrintErrf": true, |
| 20 | +} |
| 21 | + |
| 22 | +// TestNoPrintfCalls ensures cmd.Printf and |
| 23 | +// cmd.PrintErrf are not used anywhere. All formatted |
| 24 | +// output must go through internal/write/ which uses |
| 25 | +// cmd.Print/cmd.Println with pre-formatted strings |
| 26 | +// from desc.Text(). |
| 27 | +// |
| 28 | +// Test files are exempt. |
| 29 | +// |
| 30 | +// See specs/ast-audit-tests.md for rationale. |
| 31 | +func TestNoPrintfCalls(t *testing.T) { |
| 32 | + pkgs := loadPackages(t) |
| 33 | + var violations []string |
| 34 | + |
| 35 | + for _, pkg := range pkgs { |
| 36 | + for _, file := range pkg.Syntax { |
| 37 | + fpath := pkg.Fset.Position(file.Pos()).Filename |
| 38 | + if isTestFile(fpath) { |
| 39 | + continue |
| 40 | + } |
| 41 | + |
| 42 | + // Allow calls inside internal/write/. |
| 43 | + if strings.Contains(pkg.PkgPath, "internal/write/") || |
| 44 | + strings.HasSuffix(pkg.PkgPath, "internal/write") { |
| 45 | + continue |
| 46 | + } |
| 47 | + |
| 48 | + ast.Inspect(file, func(n ast.Node) bool { |
| 49 | + call, ok := n.(*ast.CallExpr) |
| 50 | + if !ok { |
| 51 | + return true |
| 52 | + } |
| 53 | + |
| 54 | + sel, ok := call.Fun.(*ast.SelectorExpr) |
| 55 | + if !ok { |
| 56 | + return true |
| 57 | + } |
| 58 | + |
| 59 | + if !printfMethods[sel.Sel.Name] { |
| 60 | + return true |
| 61 | + } |
| 62 | + |
| 63 | + ident, ok := sel.X.(*ast.Ident) |
| 64 | + if !ok { |
| 65 | + return true |
| 66 | + } |
| 67 | + |
| 68 | + if ident.Name == "cmd" { |
| 69 | + violations = append(violations, |
| 70 | + posString(pkg.Fset, call.Pos())+ |
| 71 | + ": cmd."+sel.Sel.Name+ |
| 72 | + "() — use write/ helpers", |
| 73 | + ) |
| 74 | + } |
| 75 | + |
| 76 | + return true |
| 77 | + }) |
| 78 | + } |
| 79 | + } |
| 80 | + |
| 81 | + for _, v := range violations { |
| 82 | + t.Error(v) |
| 83 | + } |
| 84 | +} |
0 commit comments