...

Source file src/edge-infra.dev/pkg/lib/cli/sink/run.go

Documentation: edge-infra.dev/pkg/lib/cli/sink

     1  package sink
     2  
     3  import (
     4  	"io"
     5  
     6  	"github.com/go-logr/logr"
     7  
     8  	"edge-infra.dev/pkg/lib/cli/clog"
     9  	"edge-infra.dev/pkg/lib/fog"
    10  )
    11  
    12  // Run contains the execution-scoped CLI machinery and state for a single
    13  // [Command] invocation, e.g., output writers, logging, the parsed and computed
    14  // [Command], etc. Extensions can manipulate the [Run] state by implementing
    15  // [BeforeRunner] or [AfterRunner], allowing middleware-style state passing and
    16  // CLI logic reuse.
    17  type Run struct {
    18  	Log logr.Logger
    19  
    20  	// Read only execution state.
    21  	cmd  *Command
    22  	args []string
    23  	out  io.Writer
    24  	err  io.Writer
    25  }
    26  
    27  // Cmd returns the parsed and computed [Command] associated with this run
    28  func (r Run) Cmd() *Command {
    29  	return r.cmd
    30  }
    31  
    32  // Out returns the standard output stream for the command invocation
    33  func (r Run) Out() io.Writer {
    34  	return r.out
    35  }
    36  
    37  // Err returns the error output stream for the command invocation
    38  func (r Run) Err() io.Writer {
    39  	return r.err
    40  }
    41  
    42  // Args returns the non-flag arguments remaining after parsing command line input.
    43  func (r Run) Args() []string {
    44  	return r.args
    45  }
    46  
    47  func newRun(c *Command) Run {
    48  	r := Run{
    49  		cmd:  c,
    50  		out:  c.getOut(),
    51  		err:  c.getErr(),
    52  		args: c.args,
    53  	}
    54  
    55  	// TODO(aw185176): Decouple log construction so that Command isnt tightly
    56  	// coupled to specific logr impls
    57  	switch {
    58  	case c.logJSON:
    59  		r.Log = fog.New(
    60  			fog.WithLevel(c.logLvl),
    61  			fog.To(r.Err()),
    62  		)
    63  	default:
    64  		r.Log = clog.New(
    65  			clog.To(r.Err()),
    66  			clog.WithLevel(c.logLvl),
    67  			clog.WithCaller(clog.Error),
    68  		)
    69  	}
    70  
    71  	return r
    72  }
    73  

View as plain text