github.com/beauknowssoftware/makehcl@v0.0.0-20200322000747-1b9bb1e1c008/internal/cmd/graph_darwin.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"io/ioutil"
     6  	"os"
     7  	"os/exec"
     8  	"strings"
     9  
    10  	"github.com/beauknowssoftware/makehcl/internal/graph"
    11  	"github.com/jessevdk/go-flags"
    12  	"github.com/windler/dotgraph/renderer"
    13  )
    14  
    15  type graphType graph.Type
    16  
    17  func (t *graphType) Complete(match string) (result []flags.Completion) {
    18  	var options = []graph.Type{
    19  		graph.ImportGraph,
    20  	}
    21  
    22  	for _, o := range options {
    23  		if strings.HasPrefix(string(o), match) {
    24  			result = append(result, flags.Completion{
    25  				Item: string(o),
    26  			})
    27  		}
    28  	}
    29  
    30  	return
    31  }
    32  
    33  type GraphCommand struct {
    34  	GraphType          graphType      `short:"g" long:"graph-type" required:"true"`
    35  	Filename           flags.Filename `short:"f" long:"filename"`
    36  	IgnoreParserErrors bool           `short:"i" long:"ignore-parser-errors"`
    37  	Show               bool           `short:"s" long:"show"`
    38  }
    39  
    40  func (c *GraphCommand) Execute(_ []string) error {
    41  	var o graph.DoOptions
    42  	o.Filename = string(c.Filename)
    43  	o.IgnoreParserErrors = c.IgnoreParserErrors
    44  	o.GraphType = graph.Type(c.GraphType)
    45  
    46  	g, diag, err := graph.Do(o)
    47  
    48  	if diag.HasErrors() {
    49  		return diag
    50  	}
    51  
    52  	if err != nil {
    53  		return err
    54  	}
    55  
    56  	if c.Show {
    57  		return c.showGraph(g)
    58  	}
    59  
    60  	fmt.Println(g)
    61  
    62  	return nil
    63  }
    64  
    65  func (c *GraphCommand) showGraph(g *graph.Graph) (err error) {
    66  	var f *os.File
    67  
    68  	f, err = ioutil.TempFile("", "*.png")
    69  	if err != nil {
    70  		return
    71  	}
    72  
    73  	defer func() {
    74  		err = os.Remove(f.Name())
    75  	}()
    76  
    77  	if err := f.Close(); err != nil {
    78  		return err
    79  	}
    80  
    81  	r := renderer.PNGRenderer{
    82  		OutputFile: f.Name(),
    83  	}
    84  
    85  	r.Render(g.String())
    86  
    87  	cmd := exec.Command("open", f.Name(), "-W")
    88  	if err := cmd.Run(); err != nil {
    89  		return err
    90  	}
    91  
    92  	return
    93  }