github.com/NeowayLabs/nash@v0.2.2-0.20200127205349-a227041ffd50/internal/sh/builtin/format.go (about)

     1  package builtin
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  
     7  	"github.com/madlambda/nash/errors"
     8  	"github.com/madlambda/nash/sh"
     9  )
    10  
    11  type (
    12  	formatFn struct {
    13  		fmt  string
    14  		args []interface{}
    15  	}
    16  )
    17  
    18  func newFormat() *formatFn {
    19  	return &formatFn{}
    20  }
    21  
    22  func (f *formatFn) ArgNames() []sh.FnArg {
    23  	return []sh.FnArg{
    24  		sh.NewFnArg("fmt", false),
    25  		sh.NewFnArg("arg...", true),
    26  	}
    27  }
    28  
    29  func (f *formatFn) Run(in io.Reader, out io.Writer, err io.Writer) ([]sh.Obj, error) {
    30  	return []sh.Obj{sh.NewStrObj(fmt.Sprintf(f.fmt, f.args...))}, nil
    31  }
    32  
    33  func (f *formatFn) SetArgs(args []sh.Obj) error {
    34  	if len(args) == 0 {
    35  		return errors.NewError("format expects at least 1 argument")
    36  	}
    37  
    38  	f.fmt = args[0].String()
    39  	f.args = nil
    40  
    41  	for _, arg := range args[1:] {
    42  		f.args = append(f.args, arg.String())
    43  	}
    44  
    45  	return nil
    46  }