github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/core/pipe/pipe.go (about)

     1  package cmdpipe
     2  
     3  import (
     4  	"errors"
     5  
     6  	"github.com/lmorg/murex/lang"
     7  	"github.com/lmorg/murex/lang/parameters"
     8  	"github.com/lmorg/murex/lang/stdio"
     9  	"github.com/lmorg/murex/lang/types"
    10  )
    11  
    12  func init() {
    13  	lang.DefineFunction("pipe", cmdPipe, types.Null)
    14  	lang.DefineFunction("!pipe", cmdClosePipe, types.Null)
    15  }
    16  
    17  func cmdPipe(p *lang.Process) error {
    18  	p.Stdout.SetDataType(types.Null)
    19  
    20  	if p.Parameters.Len() == 0 {
    21  		return errors.New("missing parameters")
    22  	}
    23  
    24  	// import the registered pipes
    25  	supportedFlags := make(map[string]string)
    26  	pipes := stdio.DumpPipes()
    27  	for i := range pipes {
    28  		supportedFlags["--"+pipes[i]] = types.String
    29  	}
    30  
    31  	// define cli flags
    32  	flags, additional, err := p.Parameters.ParseFlags(&parameters.Arguments{
    33  		AllowAdditional: true,
    34  		Flags:           supportedFlags,
    35  	})
    36  
    37  	if err != nil {
    38  		return err
    39  	}
    40  
    41  	if len(additional) == 0 {
    42  		return errors.New("no name specified for named pipe. Usage: `pipe name [ --pipe-type creation-data ]")
    43  	}
    44  
    45  	if len(flags) > 1 {
    46  		return errors.New("too many types of pipe specified. Please use only one flag per")
    47  	}
    48  
    49  	for flag := range flags {
    50  		return lang.GlobalPipes.CreatePipe(additional[0], flag[2:], flags[flag])
    51  	}
    52  
    53  	for _, name := range additional {
    54  		err := lang.GlobalPipes.CreatePipe(name, "std", "")
    55  		if err != nil {
    56  			return err
    57  		}
    58  	}
    59  
    60  	return nil
    61  }
    62  
    63  func cmdClosePipe(p *lang.Process) error {
    64  	p.Stdout.SetDataType(types.Null)
    65  
    66  	var names []string
    67  
    68  	if p.IsMethod {
    69  		p.Stdin.ReadArray(p.Context, func(b []byte) {
    70  			names = append(names, string(b))
    71  		})
    72  
    73  		if len(names) == 0 {
    74  			return errors.New("stdin contained a zero length array")
    75  		}
    76  
    77  	} else {
    78  		if p.Parameters.Len() == 0 {
    79  			return errors.New("no pipes listed for closing")
    80  		}
    81  
    82  		names = p.Parameters.StringArray()
    83  	}
    84  
    85  	for _, name := range names {
    86  		if err := lang.GlobalPipes.Close(name); err != nil {
    87  			return err
    88  		}
    89  	}
    90  
    91  	return nil
    92  }