github.com/alkemics/goflow@v0.2.1/wrappers/gonodes/renderers.go (about)

     1  package gonodes
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  
     7  	"github.com/alkemics/goflow"
     8  	"github.com/alkemics/goflow/gfutil/gfgo"
     9  )
    10  
    11  type nodeRenderer struct {
    12  	goflow.NodeRenderer
    13  
    14  	graphPkg string
    15  
    16  	node gfgo.Node
    17  }
    18  
    19  func (n nodeRenderer) Imports() []goflow.Import {
    20  	return append(n.NodeRenderer.Imports(), n.node.Imports...)
    21  }
    22  func (n nodeRenderer) Doc() string                  { return n.node.Doc }
    23  func (n nodeRenderer) Dependencies() []goflow.Field { return n.node.Dependencies }
    24  func (n nodeRenderer) Inputs() []goflow.Field       { return n.node.Inputs }
    25  func (n nodeRenderer) Outputs() []goflow.Field      { return n.node.Outputs }
    26  func (n nodeRenderer) Run(inputs, outputs []goflow.Field) (string, error) {
    27  	statements := make([]string, 0)
    28  	call := fmt.Sprintf("%s.%s", n.node.Pkg, n.node.Typ)
    29  
    30  	if n.node.Method != "" {
    31  		if n.node.Constructor != "" {
    32  			depNames := goflow.FieldNames(n.node.Dependencies)
    33  			for i := range depNames {
    34  				depNames[i] = fmt.Sprintf("g.%s", depNames[i])
    35  			}
    36  			statements = append(statements, fmt.Sprintf(
    37  				"node := %s(%s)",
    38  				n.formatNode(n.node.Pkg, n.node.Constructor),
    39  				strings.Join(depNames, ", "),
    40  			))
    41  		} else {
    42  			statements = append(statements, fmt.Sprintf(
    43  				"node := %s{}",
    44  				n.formatNode(n.node.Pkg, n.node.Constructor),
    45  			))
    46  		}
    47  
    48  		call = fmt.Sprintf("node.%s", n.node.Method)
    49  	}
    50  
    51  	if len(outputs) == 0 {
    52  		statements = append(statements, fmt.Sprintf(
    53  			"%s(%s)",
    54  			call,
    55  			strings.Join(goflow.FieldNames(inputs), ", "),
    56  		))
    57  	} else {
    58  		statements = append(statements, fmt.Sprintf(
    59  			"%s = %s(%s)",
    60  			strings.Join(goflow.FieldNames(outputs), ", "),
    61  			call,
    62  			strings.Join(goflow.FieldNames(inputs), ", "),
    63  		))
    64  	}
    65  
    66  	return strings.Join(statements, "\n"), nil
    67  }
    68  
    69  func (n nodeRenderer) formatNode(pkg, name string) string {
    70  	if pkg == n.graphPkg {
    71  		return name
    72  	}
    73  	return fmt.Sprintf("%s.%s", pkg, name)
    74  }
    75  
    76  type depsGraphRenderer struct {
    77  	goflow.GraphRenderer
    78  
    79  	deps []goflow.Field
    80  }
    81  
    82  func (g depsGraphRenderer) Dependencies() []goflow.Field { return g.deps }