Documentation
¶
Index ¶
- Constants
- Variables
- type Block
- type CellPath
- func (cp *CellPath) AddInteger(value uint, optional bool)
- func (cp *CellPath) AddIntegerSpan(value uint, optional bool, span Span)
- func (cp *CellPath) AddString(value string, optional, caseSensitive bool)
- func (cp *CellPath) AddStringSpan(value string, optional, caseSensitive bool, span Span)
- func (cp CellPath) Length() int
- func (cp CellPath) String() string
- type Closure
- type Command
- type Config
- type CustomValue
- type Declaration
- type Error
- type EvalArgument
- type Example
- type ExecCommand
- func (ec *ExecCommand) AddEnvVar(ctx context.Context, name string, value Value) error
- func (ec *ExecCommand) EnterForeground(ctx context.Context) (func(context.Context) error, error)
- func (ec *ExecCommand) EvalClosure(ctx context.Context, closure Value, args ...EvalArgument) (any, error)
- func (ec *ExecCommand) FindDeclaration(ctx context.Context, name string) (*Declaration, error)
- func (ec *ExecCommand) FlagValue(name string) (Value, bool)
- func (ec *ExecCommand) GetCurrentDir(ctx context.Context) (string, error)
- func (ec *ExecCommand) GetEnvVar(ctx context.Context, name string) (*Value, error)
- func (ec *ExecCommand) GetEnvVars(ctx context.Context) (map[string]Value, error)
- func (ec *ExecCommand) GetHelp(ctx context.Context) (string, error)
- func (ec *ExecCommand) GetPluginConfig(ctx context.Context) (*Value, error)
- func (ec *ExecCommand) GetSpanContents(ctx context.Context, span Span) ([]byte, error)
- func (ec *ExecCommand) ReturnListStream(ctx context.Context) (chan<- Value, error)
- func (ec *ExecCommand) ReturnRawStream(ctx context.Context, opts ...RawStreamOption) (io.WriteCloser, error)
- func (ec *ExecCommand) ReturnValue(ctx context.Context, v Value) error
- type Filesize
- type Flag
- type Glob
- type InOutTypes
- type IntRange
- type Label
- type NamedParams
- type Ordering
- type PathMember
- type Plugin
- type PluginSignature
- type PositionalArg
- type RangeBound
- type RawStreamOption
- type Record
- type Span
- type Value
Examples ¶
Constants ¶
const ( PathVariantString = 1 PathVariantInt = 2 )
CellPath member types, ie values returned by the Type() method of a PathMember.
Variables ¶
var ErrDeclNotFound = errors.New("command not found")
ErrDeclNotFound is returned by the ExecCommand.FindDeclaration method if the command with the given name couldn't be found in the scope of the plugin call.
var ErrDropStream = errors.New("received Drop stream message")
ErrDropStream is context cancellation (command's OnRun handler) or stream close error when consumer sent Drop message (ie plugin should stop producing into output stream).
var ErrGoodbye = errors.New("Goodbye")
ErrGoodbye is the exit cause when plugin received Goodbye message.
var ErrInterrupt = errors.New("received Interrupt signal")
ErrInterrupt is the exit cause when plugin received Interrupt signal.
Functions ¶
This section is empty.
Types ¶
type CellPath ¶
type CellPath struct {
Members []PathMember
Span Span
}
Represents a path into subfields of lists, records, and tables.
func (*CellPath) AddInteger ¶
func (*CellPath) AddIntegerSpan ¶
func (*CellPath) AddStringSpan ¶
type Closure ¶
type Closure struct {
BlockID uint
Captures msgpack.RawMessage
}
Closure Value is a reference to a parsed block of Nushell code, with variables captured from scope.
The plugin should not try to inspect the contents of the closure. It is recommended that this is only used as an argument to the ExecCommand.EvalClosure engine call.
type Command ¶
type Command struct {
Signature PluginSignature
Examples []Example
// callback executed on command invocation
OnRun func(context.Context, *ExecCommand) error
}
Command describes an command provided by the plugin.
type Config ¶
type Config struct {
// Logger the Plugin should use. If not provided the plugin will create
// Error level logger which logs to stderr.
Logger *slog.Logger
// if assigned incoming data is also copied to this writer.
// NB! this writer must not block!
SniffIn io.Writer
// if assigned outgoing data is also copied to this writer.
// NB! this writer must not block!
SniffOut io.Writer
}
Config is Plugin's configuration, mostly meant to allow debugging.
type CustomValue ¶
type CustomValue interface {
// The human-readable name of the custom value emitted by the plugin.
Name() string
// Whether the engine should send drop notification about this variable.
NotifyOnDrop() bool
// This method is called to notify the plugin that a CustomValue that had notify_on_drop set to
// true (ie the NotifyOnDrop method returns true) was dropped in the engine - i.e., all copies
// of it have gone out of scope.
Dropped(ctx context.Context) error
// Returns the result of following a numeric cell path (e.g. $custom_value.0) on the custom value.
// This is most commonly used with custom types that act like lists or tables.
// The result may be another custom value.
FollowPathInt(ctx context.Context, item uint) (Value, error)
// Returns the result of following a string cell path (e.g. $custom_value.field) on the custom value.
// This is most commonly used with custom types that act like lists or tables.
// The result may be another custom value.
FollowPathString(ctx context.Context, item string) (Value, error)
// Returns the result of evaluating an Operator on this custom value with another value.
// The rhs Value may be any value - not just the same custom value type.
// The result may be another custom value.
Operation(ctx context.Context, op operator.Operator, rhs Value) (Value, error)
// Compares the custom value to another value and returns the Ordering that should be used, if any.
// The argument may be any value - not just the same custom value type.
PartialCmp(ctx context.Context, v Value) Ordering
// Returns a plain value that is representative of the custom value, or an error if this is not possible.
// Sending a custom value back for this operation is not allowed.
ToBaseValue(ctx context.Context) (Value, error)
}
CustomValue is the interface user defined types have to implement to be used as Nu Custom Value.
The CustomValueOp plugin calls are routed to the appropriate method of the variable.
type Declaration ¶
type Declaration struct {
// contains filtered or unexported fields
}
Declaration represents Nu command which can be called from plugin. Use ExecCommand.FindDeclaration to obtain the Declaration.
func (Declaration) Call ¶
func (d Declaration) Call(ctx context.Context, args ...EvalArgument) (any, error)
Call implements CallDecl engine call. Use ExecCommand.FindDeclaration to obtain the Declaration.
Note that NamedParams can be used as argument of Call in addition to the Positional, InputValue and other EvalArguments.
Example ¶
// command's OnRun handler
_ = func(ctx context.Context, call *nu.ExecCommand) error {
// find the builtin "into int" command (Conversions)
dec, err := call.FindDeclaration(ctx, "into int")
if err != nil {
return err
}
// following call is the same as executing
// 'FF' | into int --radix 16
response, err := dec.Call(ctx, nu.InputValue(nu.Value{Value: "FF"}), nu.NamedParams{"radix": nu.Value{Value: 16}})
if err != nil {
return err
}
switch data := response.(type) {
case nu.Value:
return call.ReturnValue(ctx, data)
default:
return fmt.Errorf("unsupported return type %#v", response)
}
}
type Error ¶
type Error struct {
Err error // The main message for the error
Code string // A unique machine- and search-friendly error code to associate to the error. (e.g. nu::shell::missing_config_value)
Url string // A link to documentation about the error, used in conjunction with "code"
Help string // Additional help for the error, usually a hint about what the user might try
Labels []Label // Labeled spans attached to the error, demonstrating to the user where the problem is
Inner []Error // Errors that are related to or caused this error
}
Error is a generic type of error used by Nu for interfacing with external code, such as scripts and plugins. It represents the LabeledError in Nu.
type EvalArgument ¶
type EvalArgument interface {
// contains filtered or unexported methods
}
EvalArgument is type for ExecCommand.EvalClosure and Declaration.Call optional arguments.
func InputListStream ¶
func InputListStream(arg <-chan Value) EvalArgument
Example ¶
example of a command which sends list stream as a input to closure
_ = &nu.Command{
Signature: nu.PluginSignature{
Name: "demo",
RequiredPositional: []nu.PositionalArg{
{
Name: "closure",
Desc: "Closure to be evaluated",
Shape: syntaxshape.Closure(),
},
},
},
Examples: []nu.Example{
{Description: `Closure which adds +1 to each item in input stream and returns stream`, Example: `demo { $in | each {|n| $n + 1} }`},
},
OnRun: func(ctx context.Context, call *nu.ExecCommand) error {
// EvalClosure will block until the closure returns something so generate the
// input stream in goroutine
closureIn := make(chan nu.Value)
go func() {
defer close(closureIn)
for v := range 10 {
closureIn <- nu.Value{Value: v}
}
}()
closureOut, err := call.EvalClosure(ctx, call.Positional[0], nu.InputListStream(closureIn))
if err != nil {
return fmt.Errorf("evaluating closure: %w", err)
}
switch data := closureOut.(type) {
case <-chan nu.Value:
out, err := call.ReturnListStream(ctx)
if err != nil {
return fmt.Errorf("opening output stream: %w", err)
}
for v := range data {
out <- v
}
close(out)
default:
return fmt.Errorf("unexpected closure output type %T", data)
}
return nil
},
}
func InputRawStream ¶
func InputRawStream(arg io.Reader) EvalArgument
func InputValue ¶
func InputValue(arg Value) EvalArgument
InputValue allows to set single-value input for the call.
func RedirectStderr ¶
func RedirectStderr() EvalArgument
Whether to redirect stderr if the declared command ends in an external command.
Default is "false", this argument sets it to "true".
func RedirectStdout ¶
func RedirectStdout() EvalArgument
Whether to redirect stdout if the declared command ends in an external command.
Default is "false", this argument sets it to "true".
type ExecCommand ¶
type ExecCommand struct {
Name string
// Span of the command invocation
Head Span
// Values of positional arguments
Positional []Value
// Names and values of named arguments
Named NamedParams
/*
Input to the command. Is one of:
- nil: no input;
- Value: single value input;
- <-chan Value: stream of Values;
- io.ReadCloser: raw stream;
*/
Input any
// contains filtered or unexported fields
}
ExecCommand is passed as argument to the plugin command's OnRun handler.
It allows to make engine calls, access command's input (see Input, Named and Positional fields) and send response (see Return* methods).
func (*ExecCommand) AddEnvVar ¶
AddEnvVar engine call.
Set an environment variable in the caller's scope. The environment variable can only be propagated to the caller's scope if called before the plugin call response is sent.
func (*ExecCommand) EnterForeground ¶
EnterForeground engine call.
Moves the plugin to the foreground group for direct terminal access, in an operating system-defined manner. This should be called when the plugin is going to drive the terminal in raw mode, for example to implement a terminal UI.
This call will fail with an error if the plugin is already in the foreground.
The returned function implements the LeaveForeground method and the plugin should call it when it no longer needs to be in the foreground.
Note that the plugin will also automatically be removed from the foreground when the plugin call response is received, even if the plugin call returns a stream.
func (*ExecCommand) EvalClosure ¶
func (ec *ExecCommand) EvalClosure(ctx context.Context, closure Value, args ...EvalArgument) (any, error)
EvalClosure implements EvalClosure engine call.
Pass a Closure and optional arguments to the engine to be evaluated. Returned value follows the same rules as Input field of the ExecCommand (ie it could be nil, Value or stream).
func (*ExecCommand) FindDeclaration ¶
func (ec *ExecCommand) FindDeclaration(ctx context.Context, name string) (*Declaration, error)
FindDeclaration implements FindDecl engine call.
Returns ErrDeclNotFound if the command with the given name couldn't be found in the scope of the plugin call (NB! use errors.Is to check for the error as it might be wrapped into more descriptive error).
In case of success the returned Declaration can be used to call the command.
func (*ExecCommand) FlagValue ¶
func (ec *ExecCommand) FlagValue(name string) (Value, bool)
FlagValue returns value of named parameter/flag.
The returned bool flag indicates was the flag set by user (true) or not (false). When flag was not set by user the default value (defined in plugin signature) is returned. When signature doesn't define default value (or flag is not defined in the signature) then zero Value and false is returned.
For toggle flags (Shape is not assigned in the flag definition) Bool Value is always returned ie if user doesn't provide the flag or "--flagName=false" is used then Value==false is returned.
func (*ExecCommand) GetCurrentDir ¶
func (ec *ExecCommand) GetCurrentDir(ctx context.Context) (string, error)
GetCurrentDir engine call.
Get the current directory path in the caller's scope. This always returns an absolute path.
func (*ExecCommand) GetEnvVar ¶
GetEnvVar engine call.
Get an environment variable from the caller's scope, returns nil if the environment variable is not present.
func (*ExecCommand) GetEnvVars ¶
GetEnvVars engine call.
Get all environment variables from the caller's scope.
func (*ExecCommand) GetHelp ¶
func (ec *ExecCommand) GetHelp(ctx context.Context) (string, error)
GetHelp engine call.
Get fully formatted help text for the current command. This can help with implementing top-level commands that just list their subcommands, rather than implementing any specific functionality.
func (*ExecCommand) GetPluginConfig ¶
func (ec *ExecCommand) GetPluginConfig(ctx context.Context) (*Value, error)
GetPluginConfig engine call.
Get the configuration for the plugin, from its section in $env.config.plugins.NAME if present. Returns nil if there is no configuration for the plugin set.
If the plugin configuration was specified as a closure, the engine will evaluate that closure and return the result, which may cause an error response.
func (*ExecCommand) GetSpanContents ¶
GetSpanContents engine call.
Get the contents of a Span from the engine. This can be used for viewing the source code that generated a value.
func (*ExecCommand) ReturnListStream ¶
func (ec *ExecCommand) ReturnListStream(ctx context.Context) (chan<- Value, error)
ReturnListStream should be used when command returns multiple nu.Values.
When one of the values is [error] engine considers the plugin call to have been failed and prints that error message.
To signal the end of data chan must be closed (even when sending error)!
func (*ExecCommand) ReturnRawStream ¶
func (ec *ExecCommand) ReturnRawStream(ctx context.Context, opts ...RawStreamOption) (io.WriteCloser, error)
ReturnRawStream should be used when command returns raw stream.
To signal the end of data Writer must be closed.
Cancelling the context (ctx) will also "stop" the output stream, ie it signals that the plugin is about to quit and all work has to be abandoned.
func (*ExecCommand) ReturnValue ¶
func (ec *ExecCommand) ReturnValue(ctx context.Context, v Value) error
ReturnValue should be used when command returns single Value.
type Flag ¶
type Flag struct {
Long string // long name of the flag
Short rune // optional short name of the flag
Shape syntaxshape.SyntaxShape
Required bool
Desc string
VarId uint
Default *Value
}
Flag is a definition of a flag (Shape is unassigned) or named argument (Shape is assigned).
type Glob ¶
type Glob struct {
Value string
// If true, the expansion of wildcards is disabled and Value should be treated
// as a literal path.
NoExpand bool
}
Glob is Nushell Glob Value type - a filesystem glob, selecting multiple files or directories depending on the expansion of wildcards.
Note that Go stdlib glob implementation doesn't support doublestar / globstar pattern but thirdparty libraries which do exist.
type IntRange ¶
type IntRange struct {
Start int64
Step int64
End int64
Bound RangeBound // end bound kind of the range
}
IntRange is the IntRange variant of Nushell Range type.
When creating IntRange manually don't forget to assign Step as range with zero stride would be invalid.
Bound defaults to "included" which is also default in Nushell.
To iterate over values in the range use IntRange.All method.
Example ¶
var values []int64
// end bound defaults to Included
rng := IntRange{Start: -1, Step: 2, End: 5}
for v := range rng.All() {
values = append(values, v)
}
fmt.Printf("Included: %v\n", values)
// exclude end bound
rng.Bound = Excluded
values = slices.Collect(rng.All())
fmt.Printf("Excluded: %v\n", values)
Output: Included: [-1 1 3 5] Excluded: [-1 1 3]
type Label ¶
type Label struct {
Text string // The message for the label.
Span Span // The span in the source code that the label should point to.
}
Label is "label" type for Error.
type NamedParams ¶
type Ordering ¶
type Ordering int8
Ordering is result type for the PartialCmp CustomValueOp call.
Predefined constants Incomparable, Less, Equal and Greater should be used by CustomValue implementations.
type PathMember ¶
type PathMember interface {
// Type indicates whether the path member is uint or string,
// return either PathVariantInt or PathVariantString
Type() uint
// PathInt returns uint value of the path member, should be called
// only when Type returns PathVariantInt
PathInt() uint
// PathStr returns string value of the path member, should be called
// only when Type returns PathVariantString
PathStr() string
// Optional path members will not cause errors if they can't be
// accessed - the path access will just return Nothing instead.
Optional() bool
// Is the path element case-sensitive (true) or case-insensitive (false).
CaseSensitive() bool
Span() Span
// contains filtered or unexported methods
}
PathMember describes CellPath member.
type Plugin ¶
type Plugin struct {
// contains filtered or unexported fields
}
Plugin implements Nushell Plugin, single Plugin can implement multiple commands.
The zero value is not usable, the New constructor must be used to create Plugin.
type PluginSignature ¶
type PluginSignature struct {
Name string
// This should be a single sentence as it is the part shown for example in the completion menu.
Desc string
// Additional documentation of the command.
Description string
SearchTerms []string
Category string // https://docs.rs/nu-protocol/latest/nu_protocol/enum.Category.html
RequiredPositional []PositionalArg
OptionalPositional []PositionalArg
RestPositional *PositionalArg
// The "help" (short "h") flag will be added automatically when plugin
// is created, do not use these names for other flags or arguments.
Named []Flag
InputOutputTypes []InOutTypes
IsFilter bool
CreatesScope bool
AllowsUnknownArgs bool
AllowMissingExamples bool
}
func (PluginSignature) Validate ¶
func (sig PluginSignature) Validate() error
type PositionalArg ¶
type PositionalArg struct {
Name string
Desc string
Shape syntaxshape.SyntaxShape
VarId uint
Default *Value
}
type RangeBound ¶
type RangeBound uint8
const ( Included RangeBound = 0 Excluded RangeBound = 1 Unbounded RangeBound = 2 )
func (RangeBound) String ¶
func (rb RangeBound) String() string
type RawStreamOption ¶
type RawStreamOption interface {
// contains filtered or unexported methods
}
func BinaryStream ¶
func BinaryStream() RawStreamOption
BinaryStream indicates that the stream contains binary data of unknown encoding, and should be treated as a binary value. See also StringStream.
func BufferSize ¶
func BufferSize(size uint) RawStreamOption
BufferSize allows to hint the desired buffer size (but it is not guaranteed that buffer will be exactly that big). Writes are collected into buffer before sending to the consumer.
func FilePath ¶
func FilePath(fileName string) RawStreamOption
FilePath sets the stream metadata to "DataSource = FilePath" with given file name. The "content type" field of the metadata is set based on the file's extension using system mime type registry.
func StringStream ¶
func StringStream() RawStreamOption
StringStream indicates that the stream contains text data that is valid UTF-8, and should be treated as a string value. See also BinaryStream.
type Record ¶
Record is an associative key-value map. If records are contained in a list, this renders as a table. The keys are always strings, but the values may be any type.
type Value ¶
Value represents Nushell Value.
Generally type switch or type assertion has to be used to access the "underling value", ie
switch data := in.Value.(type) {
case []byte:
buf = data
case string:
buf = []byte(data)
default:
return fmt.Errorf("unsupported Value type %T", data)
}
Incoming data is encoded as follows:
- Nothing -> nil
- Bool -> bool
- Binary -> []byte
- String -> string
- Int -> int64
- Float -> float64
- Filesize -> Filesize
- Duration -> time.Duration
- Date -> time.Time
- Record -> Record
- List -> []Value
- Glob -> Glob
- Closure -> Closure
- Block -> Block
- Range -> IntRange
- CellPath -> CellPath
Outgoing values are encoded as:
- nil -> Nothing
- int, int8, int16, int32, int64 -> Int
- uint, uint8, uint16, uint32, uint64 -> Int
- float64, float32 -> Float
- bool -> Bool
- []byte -> Binary
- string -> String
- error -> LabeledError
- Filesize -> Filesize
- time.Duration -> Duration
- time.Time -> Date
- Record -> Record
- []Value -> List
- Glob -> Glob
- Closure -> Closure
- Block -> Block
- IntRange -> Range
- CustomValue -> Custom
- CellPath -> CellPath
func ToValue ¶
ToValue returns canonical Nu Value of the v.
Supported input types are:
- int and uint types
- float32 and float64
- time.Duration and time.Time
- string
- []byte
- Nu types defined by this package: IntRange, Record, Filesize, Glob, Block, Closure, CellPath, []Value
- nil
Slices and arrays (other than byte slices) are converted to List.
Maps and structs are converted to Record.
In case of unsupported type the Value returned will contain error.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package operator defines Operator type and constants for Nu Custom Value support.
|
Package operator defines Operator type and constants for Nu Custom Value support. |
|
Package syntaxshape defines type and functions to describe Nu syntax shapes.
|
Package syntaxshape defines type and functions to describe Nu syntax shapes. |
|
Package types defines types and functions to describe Nu types in plugin signatures.
|
Package types defines types and functions to describe Nu types in plugin signatures. |