reduce usages of globalOptions variable

This commit is contained in:
Michael Eischer
2025-09-14 14:52:02 +02:00
parent e4395a9d73
commit 6bd85d2412
18 changed files with 58 additions and 62 deletions

View File

@@ -586,7 +586,7 @@ func runBackup(ctx context.Context, opts BackupOptions, gopts GlobalOptions, ter
filename := path.Join("/", opts.StdinFilename) filename := path.Join("/", opts.StdinFilename)
var source io.ReadCloser = os.Stdin var source io.ReadCloser = os.Stdin
if opts.StdinCommand { if opts.StdinCommand {
source, err = fs.NewCommandReader(ctx, args, globalOptions.stderr) source, err = fs.NewCommandReader(ctx, args, msg.E)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -262,22 +262,19 @@ func TestBackupNonExistingFile(t *testing.T) {
testSetupBackupData(t, env) testSetupBackupData(t, env)
_ = withRestoreGlobalOptions(func() error { env.gopts.stderr = io.Discard
globalOptions.stderr = io.Discard
p := filepath.Join(env.testdata, "0", "0", "9") p := filepath.Join(env.testdata, "0", "0", "9")
dirs := []string{ dirs := []string{
filepath.Join(p, "0"), filepath.Join(p, "0"),
filepath.Join(p, "1"), filepath.Join(p, "1"),
filepath.Join(p, "nonexisting"), filepath.Join(p, "nonexisting"),
filepath.Join(p, "5"), filepath.Join(p, "5"),
} }
opts := BackupOptions{} opts := BackupOptions{}
testRunBackup(t, "", dirs, opts, env.gopts) testRunBackup(t, "", dirs, opts, env.gopts)
return nil
})
} }
func TestBackupSelfHealing(t *testing.T) { func TestBackupSelfHealing(t *testing.T) {

View File

@@ -163,7 +163,7 @@ func runCache(opts CacheOptions, gopts GlobalOptions, args []string, term ui.Ter
}) })
} }
_ = tab.Write(globalOptions.stdout) _ = tab.Write(gopts.stdout)
printer.S("%d cache dirs in %s", len(dirs), cachedir) printer.S("%d cache dirs in %s", len(dirs), cachedir)
return nil return nil

View File

@@ -1,7 +1,6 @@
package main package main
import ( import (
"bytes"
"context" "context"
"testing" "testing"
@@ -25,15 +24,15 @@ func testRunCheckMustFail(t testing.TB, gopts GlobalOptions) {
} }
func testRunCheckOutput(gopts GlobalOptions, checkUnused bool) (string, error) { func testRunCheckOutput(gopts GlobalOptions, checkUnused bool) (string, error) {
buf := bytes.NewBuffer(nil) buf, err := withCaptureStdout(gopts, func(gopts GlobalOptions) error {
gopts.stdout = buf return withTermStatus(gopts, func(ctx context.Context, term ui.Terminal) error {
err := withTermStatus(gopts, func(ctx context.Context, term ui.Terminal) error { opts := CheckOptions{
opts := CheckOptions{ ReadData: true,
ReadData: true, CheckUnused: checkUnused,
CheckUnused: checkUnused, }
} _, err := runCheck(context.TODO(), opts, gopts, nil, term)
_, err := runCheck(context.TODO(), opts, gopts, nil, term) return err
return err })
}) })
return buf.String(), err return buf.String(), err
} }

View File

@@ -204,20 +204,20 @@ func runDebugDump(ctx context.Context, gopts GlobalOptions, args []string, term
switch tpe { switch tpe {
case "indexes": case "indexes":
return dumpIndexes(ctx, repo, globalOptions.stdout, printer) return dumpIndexes(ctx, repo, gopts.stdout, printer)
case "snapshots": case "snapshots":
return debugPrintSnapshots(ctx, repo, globalOptions.stdout) return debugPrintSnapshots(ctx, repo, gopts.stdout)
case "packs": case "packs":
return printPacks(ctx, repo, globalOptions.stdout, printer) return printPacks(ctx, repo, gopts.stdout, printer)
case "all": case "all":
printer.S("snapshots:") printer.S("snapshots:")
err := debugPrintSnapshots(ctx, repo, globalOptions.stdout) err := debugPrintSnapshots(ctx, repo, gopts.stdout)
if err != nil { if err != nil {
return err return err
} }
printer.S("indexes:") printer.S("indexes:")
err = dumpIndexes(ctx, repo, globalOptions.stdout, printer) err = dumpIndexes(ctx, repo, gopts.stdout, printer)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -426,7 +426,7 @@ func runDiff(ctx context.Context, opts DiffOptions, gopts GlobalOptions, args []
} }
if gopts.JSON { if gopts.JSON {
enc := json.NewEncoder(globalOptions.stdout) enc := json.NewEncoder(gopts.stdout)
c.printChange = func(change *Change) { c.printChange = func(change *Change) {
err := enc.Encode(change) err := enc.Encode(change)
if err != nil { if err != nil {
@@ -460,7 +460,7 @@ func runDiff(ctx context.Context, opts DiffOptions, gopts GlobalOptions, args []
updateBlobs(repo, stats.BlobsAfter.Sub(both).Sub(stats.BlobsCommon), &stats.Added, printer.E) updateBlobs(repo, stats.BlobsAfter.Sub(both).Sub(stats.BlobsCommon), &stats.Added, printer.E)
if gopts.JSON { if gopts.JSON {
err := json.NewEncoder(globalOptions.stdout).Encode(stats) err := json.NewEncoder(gopts.stdout).Encode(stats)
if err != nil { if err != nil {
printer.E("JSON encode failed: %v", err) printer.E("JSON encode failed: %v", err)
} }

View File

@@ -253,7 +253,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
} }
if gopts.Verbose >= 1 && !gopts.JSON { if gopts.Verbose >= 1 && !gopts.JSON {
err = PrintSnapshotGroupHeader(globalOptions.stdout, k) err = PrintSnapshotGroupHeader(gopts.stdout, k)
if err != nil { if err != nil {
return err return err
} }
@@ -276,7 +276,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
} }
if len(keep) != 0 && !gopts.Quiet && !gopts.JSON { if len(keep) != 0 && !gopts.Quiet && !gopts.JSON {
printer.P("keep %d snapshots:\n", len(keep)) printer.P("keep %d snapshots:\n", len(keep))
if err := PrintSnapshots(globalOptions.stdout, keep, reasons, opts.Compact); err != nil { if err := PrintSnapshots(gopts.stdout, keep, reasons, opts.Compact); err != nil {
return err return err
} }
printer.P("\n") printer.P("\n")
@@ -285,7 +285,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
if len(remove) != 0 && !gopts.Quiet && !gopts.JSON { if len(remove) != 0 && !gopts.Quiet && !gopts.JSON {
printer.P("remove %d snapshots:\n", len(remove)) printer.P("remove %d snapshots:\n", len(remove))
if err := PrintSnapshots(globalOptions.stdout, remove, nil, opts.Compact); err != nil { if err := PrintSnapshots(gopts.stdout, remove, nil, opts.Compact); err != nil {
return err return err
} }
printer.P("\n") printer.P("\n")
@@ -330,7 +330,7 @@ func runForget(ctx context.Context, opts ForgetOptions, pruneOptions PruneOption
} }
if gopts.JSON && len(jsonGroups) > 0 { if gopts.JSON && len(jsonGroups) > 0 {
err = printJSONForget(globalOptions.stdout, jsonGroups) err = printJSONForget(gopts.stdout, jsonGroups)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -75,7 +75,7 @@ func writeManpages(root *cobra.Command, dir string, printer progress.Printer) er
return doc.GenManTree(root, header, dir) return doc.GenManTree(root, header, dir)
} }
func writeCompletion(filename string, shell string, generate func(w io.Writer) error, printer progress.Printer) (err error) { func writeCompletion(filename string, shell string, generate func(w io.Writer) error, printer progress.Printer, gopts GlobalOptions) (err error) {
if terminal.StdoutIsTerminal() { if terminal.StdoutIsTerminal() {
printer.P("writing %s completion file to %v", shell, filename) printer.P("writing %s completion file to %v", shell, filename)
} }
@@ -89,7 +89,7 @@ func writeCompletion(filename string, shell string, generate func(w io.Writer) e
defer func() { err = outFile.Close() }() defer func() { err = outFile.Close() }()
outWriter = outFile outWriter = outFile
} else { } else {
outWriter = globalOptions.stdout outWriter = gopts.stdout
} }
err = generate(outWriter) err = generate(outWriter)
@@ -136,28 +136,28 @@ func runGenerate(opts generateOptions, gopts GlobalOptions, args []string, term
} }
if opts.BashCompletionFile != "" { if opts.BashCompletionFile != "" {
err := writeCompletion(opts.BashCompletionFile, "bash", cmdRoot.GenBashCompletion, printer) err := writeCompletion(opts.BashCompletionFile, "bash", cmdRoot.GenBashCompletion, printer, gopts)
if err != nil { if err != nil {
return err return err
} }
} }
if opts.FishCompletionFile != "" { if opts.FishCompletionFile != "" {
err := writeCompletion(opts.FishCompletionFile, "fish", func(w io.Writer) error { return cmdRoot.GenFishCompletion(w, true) }, printer) err := writeCompletion(opts.FishCompletionFile, "fish", func(w io.Writer) error { return cmdRoot.GenFishCompletion(w, true) }, printer, gopts)
if err != nil { if err != nil {
return err return err
} }
} }
if opts.ZSHCompletionFile != "" { if opts.ZSHCompletionFile != "" {
err := writeCompletion(opts.ZSHCompletionFile, "zsh", cmdRoot.GenZshCompletion, printer) err := writeCompletion(opts.ZSHCompletionFile, "zsh", cmdRoot.GenZshCompletion, printer, gopts)
if err != nil { if err != nil {
return err return err
} }
} }
if opts.PowerShellCompletionFile != "" { if opts.PowerShellCompletionFile != "" {
err := writeCompletion(opts.PowerShellCompletionFile, "powershell", cmdRoot.GenPowerShellCompletion, printer) err := writeCompletion(opts.PowerShellCompletionFile, "powershell", cmdRoot.GenPowerShellCompletion, printer, gopts)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -134,7 +134,7 @@ func runInit(ctx context.Context, opts InitOptions, gopts GlobalOptions, args []
ID: s.Config().ID, ID: s.Config().ID,
Repository: location.StripPassword(gopts.backends, gopts.Repo), Repository: location.StripPassword(gopts.backends, gopts.Repo),
} }
return json.NewEncoder(globalOptions.stdout).Encode(status) return json.NewEncoder(gopts.stdout).Encode(status)
} }
return nil return nil

View File

@@ -97,7 +97,7 @@ func listKeys(ctx context.Context, s *repository.Repository, gopts GlobalOptions
} }
if gopts.JSON { if gopts.JSON {
return json.NewEncoder(globalOptions.stdout).Encode(keys) return json.NewEncoder(gopts.stdout).Encode(keys)
} }
tab := table.New() tab := table.New()
@@ -110,5 +110,5 @@ func listKeys(ctx context.Context, s *repository.Repository, gopts GlobalOptions
tab.AddRow(key) tab.AddRow(key)
} }
return tab.Write(globalOptions.stdout) return tab.Write(gopts.stdout)
} }

View File

@@ -384,11 +384,11 @@ func runLs(ctx context.Context, opts LsOptions, gopts GlobalOptions, args []stri
if gopts.JSON { if gopts.JSON {
printer = &jsonLsPrinter{ printer = &jsonLsPrinter{
enc: json.NewEncoder(globalOptions.stdout), enc: json.NewEncoder(gopts.stdout),
} }
} else if opts.Ncdu { } else if opts.Ncdu {
printer = &ncduLsPrinter{ printer = &ncduLsPrinter{
out: globalOptions.stdout, out: gopts.stdout,
} }
} else { } else {
printer = &textLsPrinter{ printer = &textLsPrinter{

View File

@@ -19,7 +19,7 @@ import (
func testRunRebuildIndex(t testing.TB, gopts GlobalOptions) { func testRunRebuildIndex(t testing.TB, gopts GlobalOptions) {
rtest.OK(t, withRestoreGlobalOptions(func() error { rtest.OK(t, withRestoreGlobalOptions(func() error {
return withTermStatus(gopts, func(ctx context.Context, term ui.Terminal) error { return withTermStatus(gopts, func(ctx context.Context, term ui.Terminal) error {
globalOptions.stdout = io.Discard gopts.stdout = io.Discard
return runRebuildIndex(context.TODO(), RepairIndexOptions{}, gopts, term) return runRebuildIndex(context.TODO(), RepairIndexOptions{}, gopts, term)
}) })
})) }))
@@ -133,7 +133,7 @@ func TestRebuildIndexFailsOnAppendOnly(t *testing.T) {
return &appendOnlyBackend{r}, nil return &appendOnlyBackend{r}, nil
} }
return withTermStatus(env.gopts, func(ctx context.Context, term ui.Terminal) error { return withTermStatus(env.gopts, func(ctx context.Context, term ui.Terminal) error {
globalOptions.stdout = io.Discard env.gopts.stdout = io.Discard
return runRebuildIndex(context.TODO(), RepairIndexOptions{}, env.gopts, term) return runRebuildIndex(context.TODO(), RepairIndexOptions{}, env.gopts, term)
}) })
}) })

View File

@@ -338,7 +338,7 @@ func TestRestoreWithPermissionFailure(t *testing.T) {
snapshots := testListSnapshots(t, env.gopts, 1) snapshots := testListSnapshots(t, env.gopts, 1)
_ = withRestoreGlobalOptions(func() error { _ = withRestoreGlobalOptions(func() error {
globalOptions.stderr = io.Discard env.gopts.stderr = io.Discard
testRunRestore(t, env.gopts, filepath.Join(env.base, "restore"), snapshots[0].String()) testRunRestore(t, env.gopts, filepath.Join(env.base, "restore"), snapshots[0].String())
return nil return nil
}) })

View File

@@ -105,7 +105,7 @@ func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts GlobalOptions
} }
if gopts.JSON { if gopts.JSON {
err := printSnapshotGroupJSON(globalOptions.stdout, snapshotGroups, grouped) err := printSnapshotGroupJSON(gopts.stdout, snapshotGroups, grouped)
if err != nil { if err != nil {
printer.E("error printing snapshots: %v", err) printer.E("error printing snapshots: %v", err)
} }
@@ -118,12 +118,12 @@ func runSnapshots(ctx context.Context, opts SnapshotOptions, gopts GlobalOptions
} }
if grouped { if grouped {
err := PrintSnapshotGroupHeader(globalOptions.stdout, k) err := PrintSnapshotGroupHeader(gopts.stdout, k)
if err != nil { if err != nil {
return err return err
} }
} }
err := PrintSnapshots(globalOptions.stdout, list, nil, opts.Compact) err := PrintSnapshots(gopts.stdout, list, nil, opts.Compact)
if err != nil { if err != nil {
return err return err
} }

View File

@@ -171,7 +171,7 @@ func runStats(ctx context.Context, opts StatsOptions, gopts GlobalOptions, args
} }
if gopts.JSON { if gopts.JSON {
err = json.NewEncoder(globalOptions.stdout).Encode(stats) err = json.NewEncoder(gopts.stdout).Encode(stats)
if err != nil { if err != nil {
return fmt.Errorf("encoding output: %v", err) return fmt.Errorf("encoding output: %v", err)
} }

View File

@@ -476,7 +476,7 @@ func innerOpen(ctx context.Context, s string, gopts GlobalOptions, opts options.
return nil, err return nil, err
} }
rt, err := backend.Transport(globalOptions.TransportOptions) rt, err := backend.Transport(gopts.TransportOptions)
if err != nil { if err != nil {
return nil, errors.Fatalf("%s", err) return nil, errors.Fatalf("%s", err)
} }

View File

@@ -28,7 +28,7 @@ type CommandReader struct {
alreadyClosedReadErr error alreadyClosedReadErr error
} }
func NewCommandReader(ctx context.Context, args []string, logOutput io.Writer) (*CommandReader, error) { func NewCommandReader(ctx context.Context, args []string, errorOutput func(msg string, args ...interface{})) (*CommandReader, error) {
if len(args) == 0 { if len(args) == 0 {
return nil, fmt.Errorf("no command was specified as argument") return nil, fmt.Errorf("no command was specified as argument")
} }
@@ -48,7 +48,7 @@ func NewCommandReader(ctx context.Context, args []string, logOutput io.Writer) (
go func() { go func() {
sc := bufio.NewScanner(stderr) sc := bufio.NewScanner(stderr)
for sc.Scan() { for sc.Scan() {
_, _ = fmt.Fprintf(logOutput, "subprocess %v: %v\n", command.Args[0], sc.Text()) errorOutput("subprocess %v: %v", command.Args[0], sc.Text())
} }
}() }()

View File

@@ -12,7 +12,7 @@ import (
) )
func TestCommandReaderSuccess(t *testing.T) { func TestCommandReaderSuccess(t *testing.T) {
reader, err := fs.NewCommandReader(context.TODO(), []string{"true"}, io.Discard) reader, err := fs.NewCommandReader(context.TODO(), []string{"true"}, func(msg string, args ...interface{}) {})
test.OK(t, err) test.OK(t, err)
_, err = io.Copy(io.Discard, reader) _, err = io.Copy(io.Discard, reader)
@@ -22,7 +22,7 @@ func TestCommandReaderSuccess(t *testing.T) {
} }
func TestCommandReaderFail(t *testing.T) { func TestCommandReaderFail(t *testing.T) {
reader, err := fs.NewCommandReader(context.TODO(), []string{"false"}, io.Discard) reader, err := fs.NewCommandReader(context.TODO(), []string{"false"}, func(msg string, args ...interface{}) {})
test.OK(t, err) test.OK(t, err)
_, err = io.Copy(io.Discard, reader) _, err = io.Copy(io.Discard, reader)
@@ -30,17 +30,17 @@ func TestCommandReaderFail(t *testing.T) {
} }
func TestCommandReaderInvalid(t *testing.T) { func TestCommandReaderInvalid(t *testing.T) {
_, err := fs.NewCommandReader(context.TODO(), []string{"w54fy098hj7fy5twijouytfrj098y645wr"}, io.Discard) _, err := fs.NewCommandReader(context.TODO(), []string{"w54fy098hj7fy5twijouytfrj098y645wr"}, func(msg string, args ...interface{}) {})
test.Assert(t, err != nil, "missing error") test.Assert(t, err != nil, "missing error")
} }
func TestCommandReaderEmptyArgs(t *testing.T) { func TestCommandReaderEmptyArgs(t *testing.T) {
_, err := fs.NewCommandReader(context.TODO(), []string{}, io.Discard) _, err := fs.NewCommandReader(context.TODO(), []string{}, func(msg string, args ...interface{}) {})
test.Assert(t, err != nil, "missing error") test.Assert(t, err != nil, "missing error")
} }
func TestCommandReaderOutput(t *testing.T) { func TestCommandReaderOutput(t *testing.T) {
reader, err := fs.NewCommandReader(context.TODO(), []string{"echo", "hello world"}, io.Discard) reader, err := fs.NewCommandReader(context.TODO(), []string{"echo", "hello world"}, func(msg string, args ...interface{}) {})
test.OK(t, err) test.OK(t, err)
var buf bytes.Buffer var buf bytes.Buffer