Skip to content

Commit 8f567d2

Browse files
gh-aw-botCopilotgithub-actions[bot]pelikhan
authored
Add linter for discarded exec command stderr (#80119)
* Initial plan * Add exec command stderr analyzer Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Guard named output error reassignment Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Avoid unchecked analyzer slice indexes Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> * Apply filtered changes * Fix exec output alias tracking Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> --------- Co-authored-by: gh-aw-bot <259018956+gh-aw-bot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com> Co-authored-by: pelikhan <4175913+pelikhan@users.noreply.github.com>
1 parent fb1695d commit 8f567d2

10 files changed

Lines changed: 2274 additions & 3 deletions

File tree

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
# ADR-80119: Add Linter for Discarded exec.Cmd Output Stderr
2+
3+
**Date**: 2026-11-22
4+
**Status**: Draft
5+
**Deciders**: Unknown — PR author `gh-aw-bot` (linter-miner workflow); reviewers [TODO: verify]
6+
7+
---
8+
9+
### Context
10+
11+
`exec.Cmd.Output()` returns a `*exec.ExitError` on failure, and that error carries the child process's stderr in its `Stderr` field, but only if the caller reads it. `exec.Cmd.CombinedOutput()` returns stdout and stderr together, so discarding its result loses the diagnostics entirely. Both patterns are easy to write and easy to miss in review. The PR's code-pattern scan found roughly 98 `exec.Command` call sites under `pkg/` and `cmd/`, where command failures can lose stderr. Existing linters in `pkg/linters` cover discarded errors and `exec.Command` context usage, but none checks how the results of `Output()` and `CombinedOutput()` are handled.
12+
13+
### Decision
14+
15+
We will add a custom `go/analysis` analyzer, `execcommandoutputerrdiscard`, that reports `exec.Cmd.Output()` calls whose error neither retains `*exec.ExitError.Stderr` nor propagates the error, and `exec.Cmd.CombinedOutput()` calls whose output is discarded. The analyzer is registered in `pkg/linters/registry.go`, documented in `pkg/linters/README.md` and `pkg/linters/doc.go`, and listed in `notYetEnforced` in `doc_sync_test.go`, so it gives advisory signal only until existing call sites are reviewed. The primary driver is diagnosability: keeping stderr from failed commands so that CLI and CI failures can be explained.
16+
17+
### Alternatives Considered
18+
19+
#### Alternative 1: Enforce the check in CI immediately
20+
21+
The analyzer could block CI from the first day. This gives the strongest guarantee. We did not choose it because the PR records that existing exec output error handling needs review before enforcement, and its full-repository `make golint-custom` run did not complete (a constrained runner killed a Go compiler process). Enforcing now would likely block unrelated PRs on unreviewed call sites. This was a close call. [TODO: verify the current number of violations across `pkg/` and `cmd/`.]
22+
23+
#### Alternative 2: Rely on review and a documented convention
24+
25+
Contributors could be told to always capture stderr from `Output()` and `CombinedOutput()` results, with no new linter. This adds no maintenance cost. We did not choose it because the pattern is easy to write and easy to miss, and roughly 98 call sites suggest review alone will not keep up.
26+
27+
#### Alternative 3: Route all command execution through a shared helper
28+
29+
A single command-runner helper could always capture stderr into the returned error, so callers could not drop it. This removes the problem at the source. The PR does not discuss this option, and it is not chosen here because it requires refactoring many call sites before any protection exists, and it does not stop direct `exec.Cmd` use. [TODO: verify whether such a helper already exists in `pkg/`.]
30+
31+
### Consequences
32+
33+
#### Positive
34+
- Failures from `Output()` and `CombinedOutput()` that discard stderr are reported before merge, which makes CLI and CI failures easier to debug.
35+
- The analyzer resolves `os/exec` methods through `go/types`, so unrelated `Output` methods are not flagged. The fixtures cover this case.
36+
- It follows existing linter conventions: `analyzerutil`, shared `astutil` helpers, `//nolint:execcommandoutputerrdiscard` suppression, generated-file skipping, `analysistest` fixtures, a registry entry, and doc-sync tests.
37+
38+
#### Negative
39+
- The analysis is intraprocedural. It tracks result bindings within the enclosing function body and does not follow results passed to helper functions, so it can miss handling in other functions or report patterns it does not recognize. [TODO: verify the false-positive rate on the full repository.]
40+
- The full-repository run did not complete, so the number of existing violations is unknown from the PR. The analyzer stays advisory until those are remediated.
41+
- The change adds about 636 lines of analyzer code and 245 lines of fixtures. The linter count (100 to 101) must stay synchronized across `doc.go`, `README.md`, `spec_test.go`, and `doc_sync_test.go`.
42+
43+
#### Neutral
44+
- The analyzer is part of the suite but not enforced in CI. Enforcement starts when its entry is removed from `notYetEnforced` after review.
45+
- The original linter-miner draft flagged `README.md` as a protected file. Reviewers should confirm the README edits are intended.
46+
47+
---
48+
49+
*ADR created by [adr-writer agent]. Review and finalize before changing status from Draft to Accepted.*

‎pkg/linters/README.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ The method names mentioned in analyzer descriptions (such as `Err`, `Flush`, `Re
2828
- `errorsnewerrorstring` — reports `errors.New(err.Error())` calls that discard the original error and break error-chain matching.
2929
- `errortypeassertion` — reports type assertions from `error` to concrete types and recommends `errors.As`.
3030
- `errstringmatch` — reports `strings.Contains(err.Error(), "...")` patterns and recommends `errors.Is` / `errors.As`.
31+
- `execcommandoutputerrdiscard` — reports `exec.Cmd.Output()` failures that do not preserve stderr diagnostics and `CombinedOutput()` results that are discarded on failure.
3132
- `fileclosenotdeferred` — reports non-deferred file `Close()` calls that can leak resources.
3233
- `filepathwalkpreferwalkdir` — reports `filepath.Walk` calls and recommends `filepath.WalkDir`.
3334
- `execcommandwithoutcontext` — reports `exec.Command(...)` calls inside functions that already receive `context.Context` and should use `exec.CommandContext(...)`.
@@ -211,6 +212,7 @@ environment variable and gates findings on the recorded execution hit count for
211212
| `errorsnewerrorstring` | Custom `go/analysis` analyzer that flags `errors.New(err.Error())` calls that discard the original error and break `errors.Is` / `errors.As` matching |
212213
| `errortypeassertion` | Custom `go/analysis` analyzer that flags type assertions from `error` to concrete types and recommends `errors.As` |
213214
| `errstringmatch` | Custom `go/analysis` analyzer that flags brittle `strings.Contains(err.Error(), "...")` checks |
215+
| `execcommandoutputerrdiscard` | Custom `go/analysis` analyzer that reports `exec.Cmd.Output()` failures that do not preserve stderr diagnostics and `CombinedOutput()` results discarded on failure |
214216
| `execcommandwithoutcontext` | Custom `go/analysis` analyzer that flags `exec.Command(...)` calls that should use `exec.CommandContext(...)` in context-receiving functions |
215217
| `fileclosenotdeferred` | Custom `go/analysis` analyzer that flags file `Close()` calls that are not deferred immediately |
216218
| `filepathwalkpreferwalkdir` | Custom `go/analysis` analyzer that flags `filepath.Walk` calls and recommends `filepath.WalkDir` |
@@ -311,6 +313,7 @@ import (
311313
"github.com/github/gh-aw/pkg/linters/errormessage"
312314
"github.com/github/gh-aw/pkg/linters/errorsnewerrorstring"
313315
"github.com/github/gh-aw/pkg/linters/errstringmatch"
316+
"github.com/github/gh-aw/pkg/linters/execcommandoutputerrdiscard"
314317
"github.com/github/gh-aw/pkg/linters/execcommandwithoutcontext"
315318
"github.com/github/gh-aw/pkg/linters/fileclosenotdeferred"
316319
"github.com/github/gh-aw/pkg/linters/hardcodedfilepath"
@@ -348,6 +351,7 @@ _ = excessivefuncparams.Analyzer
348351
_ = errormessage.Analyzer
349352
_ = errorsnewerrorstring.Analyzer
350353
_ = errstringmatch.Analyzer
354+
_ = execcommandoutputerrdiscard.Analyzer
351355
_ = execcommandwithoutcontext.Analyzer
352356
_ = fileclosenotdeferred.Analyzer
353357
_ = hardcodedfilepath.Analyzer
@@ -392,6 +396,7 @@ _ = typeassertionnil.Analyzer
392396
- `github.com/github/gh-aw/pkg/linters/errormessage` — error-message analyzer subpackage (also re-exported as `ErrorMessageAnalyzer`)
393397
- `github.com/github/gh-aw/pkg/linters/errortypeassertion` — error-type-assertion analyzer subpackage
394398
- `github.com/github/gh-aw/pkg/linters/errstringmatch` — err-string-match analyzer subpackage
399+
- `github.com/github/gh-aw/pkg/linters/execcommandoutputerrdiscard` — exec-command-output-error-discard analyzer subpackage
395400
- `github.com/github/gh-aw/pkg/linters/execcommandwithoutcontext` — exec-command-without-context analyzer subpackage
396401
- `github.com/github/gh-aw/pkg/linters/excessivefuncparams` — excessive-func-params analyzer subpackage
397402
- `github.com/github/gh-aw/pkg/linters/fileclosenotdeferred` — file-close-not-deferred analyzer subpackage

‎pkg/linters/doc.go‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Package linters is a namespace for gh-aw's custom Go analysis linters.
22
//
3-
// All 100 active analyzers:
3+
// All 101 active analyzers:
44
//
55
// - appendbytestring — flags append(b, []byte(s)...) calls where s is a string that can be simplified to append(b, s...)
66
// - appendoneelement — flags append(s, []T{x}...) calls where a single-element slice literal is spread and can be simplified to append(s, x)
@@ -22,6 +22,7 @@
2222
// - errortypeassertion — flags type assertions from error to concrete types and recommends errors.As
2323
// - errstringmatch — flags brittle strings.Contains(err.Error(), "...") checks
2424
// - excessivefuncparams — flags function declarations with too many positional parameters
25+
// - execcommandoutputerrdiscard — reports exec.Cmd output calls whose failures discard stderr diagnostics
2526
// - execcommandwithoutcontext — flags exec.Command calls inside functions that already receive context.Context
2627
// - fileclosenotdeferred — flags file Close() calls that are not deferred
2728
// - filepathwalkpreferwalkdir — reports filepath.Walk calls and recommends filepath.WalkDir

‎pkg/linters/doc_sync_test.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ var notYetEnforced = map[string]string{
3434
"errormessage": "dedicated lint-error-messages CI job is intentionally advisory (continue-on-error per #54800)",
3535
"errorsnewerrorstring": "requires an enforcement-readiness audit before CI enables it",
3636
"excessivefuncparams": "existing production violations need remediation before enforcement; nolint suppression already works",
37+
"execcommandoutputerrdiscard": "existing exec output error handling needs review before CI enforcement",
3738
"filepathwalkpreferwalkdir": "existing filepath.Walk calls need remediation before CI enforcement",
3839
"formatintitoa": "existing FormatInt conversions need remediation before CI enforcement",
3940
"fprintferrorunchecked": "existing production violations need remediation before enforcement; nolint suppression already works",

0 commit comments

Comments
 (0)