miller/pkg/terminals/script/runner.go
John Kerl 91eaff1341
Lint round 5+6: staticcheck and errcheck to zero (#2130)
* refine the plan

* Fix all staticcheck lint findings (uncapped)

golangci-lint's default max-same-issues=3 was hiding most of the backlog:
the true pre-fix count was 69 staticcheck findings, not 34. This fixes all
of them, driving staticcheck to zero:

- ST1023/QF1011 (37): omit explicit types inferred from the RHS
- S1009/S1031 (15): drop redundant nil checks before len()/range
- SA9003 (9): remove comment-only empty branches, keeping the comments
- QF1007 (3): merge conditional assignment into declaration
- QF1006 (3): lift break conditions into loop conditions
- QF1001 (3): apply De Morgan's law / name the negated predicate

Also updates plans/lintfixes.md with the cap discovery and the corrected
errcheck picture (1202 uncapped, ~949 of them fmt.Fprint*).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Drive errcheck to zero: config for bulk categories, propagate real errors

Adds .golangci.yml with errcheck exclude-functions for fmt.Fprint* (usage
printers), (*bufio.Writer).Write/WriteString (sticky errors, surfaced at the
now-checked final Flush), and (*strings.Builder).WriteString; pins
max-issues-per-linter/max-same-issues to 0 so CI reports true counts.

Real error paths now propagate instead of being dropped:
- Finalize{Reader,Writer}Options in join/put/filter/split/tee and the
  repl/script entry points: 'mlr join -i badformat' now errors instead of
  silently using wrong separators
- final output-stream Flush in pkg/stream: write failure no longer exits 0
- DSL emit/print/dump redirect writes, matching their sibling branches
- CSV writer WriteCSVRecordMaybeColorized, close-time Flush in file output
  handlers, ENV[...] Setenv, REPL record-write and redirect-close errors
- termcvt write-side Close before rename (had "TODO: check return status")

The rest are deliberate ignores, marked with _ = and a comment where the
reason isn't obvious: unset-of-missing-path no-ops, read-side closes,
mid-stream FlushOnEveryRecord, init-time strftime registrations, in-memory
usage-capture pipes, and regtest-harness env/temp-file teardown.

golangci-lint now reports 0 issues on ./cmd/mlr ./pkg/... with all caps off.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 11:42:08 -04:00

170 lines
4 KiB
Go

package script
import (
"bufio"
"fmt"
"os"
"github.com/johnkerl/miller/v6/pkg/cli"
"github.com/johnkerl/miller/v6/pkg/dsl/cst"
"github.com/johnkerl/miller/v6/pkg/input"
"github.com/johnkerl/miller/v6/pkg/lib"
"github.com/johnkerl/miller/v6/pkg/mlrval"
"github.com/johnkerl/miller/v6/pkg/output"
"github.com/johnkerl/miller/v6/pkg/runtime"
"github.com/johnkerl/miller/v6/pkg/types"
)
func NewScript(
options *cli.TOptions,
doWarnings bool,
strictMode bool,
dslStrings []string,
) (*Script, error) {
recordReader, err := input.Create(&options.ReaderOptions, 1)
if err != nil {
return nil, err
}
recordWriter, err := output.Create(&options.WriterOptions)
if err != nil {
return nil, err
}
context := types.NewContext()
runtimeState := runtime.NewEmptyState(options, strictMode)
runtimeState.NoExitOnFunctionNotFound = true
runtimeState.Update(nil, context)
runtimeState.FilterExpression = mlrval.NULL
cstRootNode := cst.NewEmptyRoot(
&options.WriterOptions, cst.DSLInstanceTypeScript,
).WithRedefinableUDFUDS().WithStrictMode(strictMode)
// Collect all DSL: preloads first, then main script
allDSLStrings := []string{}
for _, filename := range options.DSLPreloadFileNames {
theseStrings, err := lib.LoadStringsFromFileOrDir(filename, ".mlr")
if err != nil {
return nil, fmt.Errorf("cannot load from \"%s\": %w", filename, err)
}
allDSLStrings = append(allDSLStrings, theseStrings...)
}
allDSLStrings = append(allDSLStrings, dslStrings...)
scr := &Script{
name: "script",
doWarnings: doWarnings,
cstRootNode: cstRootNode,
options: options,
recordReader: recordReader,
recordWriter: recordWriter,
runtimeState: runtimeState,
}
scr.recordOutputFileName = "(stdout)"
scr.recordOutputStream = os.Stdout
scr.bufferedRecordOutputStream = bufio.NewWriter(os.Stdout)
_, err = cstRootNode.Build(
allDSLStrings,
cst.DSLInstanceTypeScript,
false,
doWarnings,
nil,
)
if err != nil {
return nil, err
}
return scr, nil
}
func (scr *Script) openFiles(filenames []string) {
scr.options.FileNames = filenames
scr.readerChannel = make(chan []*types.RecordAndContext, 2)
scr.errorChannel = make(chan error, 1)
scr.downstreamDoneChannel = make(chan bool, 1)
go scr.recordReader.Read(
filenames,
*scr.runtimeState.Context,
scr.readerChannel,
scr.errorChannel,
scr.downstreamDoneChannel,
)
}
func (scr *Script) run() error {
// Wire NextRecordFunc before running
readerChannel := scr.readerChannel
errorChannel := scr.errorChannel
bufferedOutput := scr.bufferedRecordOutputStream
scr.runtimeState.NextRecordFunc = func() (*mlrval.Mlrmap, *types.Context, bool) {
for {
var recordsAndContexts []*types.RecordAndContext
var err error
select {
case recordsAndContexts = <-readerChannel:
case err = <-errorChannel:
}
if err != nil {
return nil, scr.runtimeState.Context, false
}
if recordsAndContexts == nil {
return nil, scr.runtimeState.Context, false
}
lib.InternalCodingErrorIf(len(recordsAndContexts) != 1)
rac := recordsAndContexts[0]
if rac.EndOfStream {
return nil, &rac.Context, false
}
if rac.Record == nil {
// Output string from print/dump etc; terminal output, nothing
// useful to do on write failure
_, _ = bufferedOutput.WriteString(rac.OutputString)
_ = bufferedOutput.Flush()
continue
}
// Actual record
return rac.Record, &rac.Context, true
}
}
// Execute begin blocks
err := scr.cstRootNode.ExecuteBeginBlocks(scr.runtimeState)
if err != nil {
return err
}
// Execute main block (script drives itself via next())
_, err = scr.cstRootNode.ExecuteMainBlock(scr.runtimeState)
if err != nil {
return err
}
// Execute end blocks
err = scr.cstRootNode.ExecuteEndBlocks(scr.runtimeState)
if err != nil {
return err
}
return nil
}
func (scr *Script) closeBufferedOutputStream() error {
if scr.recordOutputStream != os.Stdout {
err := scr.recordOutputStream.Close()
if err != nil {
return fmt.Errorf("error on close: %w", err)
}
}
return nil
}