github.com/wawandco/oxpecker@v1.5.7-0.20210910201653-5958d4afdd89/tools/grift/command.go (about)

     1  package grift
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"text/tabwriter"
     8  
     9  	"github.com/markbates/grift/grift"
    10  	"github.com/wawandco/oxpecker/plugins"
    11  )
    12  
    13  var (
    14  	// We want grift task to be invoked from any place.
    15  	// this is because of production/compiled usage of the tasks.
    16  	_ plugins.RootFinder = (*Command)(nil)
    17  )
    18  
    19  // Grift command is a root command to run tasks
    20  // usage is ox task [name]. If no name is passed this will
    21  // list the tasks
    22  type Command struct{}
    23  
    24  func (c Command) Name() string {
    25  	return "task"
    26  }
    27  
    28  func (c Command) ParentName() string {
    29  	return ""
    30  }
    31  
    32  func (c Command) HelpText() string {
    33  	return "Runs grifts tasks previously imported in the CLI"
    34  }
    35  
    36  func (c *Command) Run(ctx context.Context, root string, args []string) error {
    37  	if len(args) < 2 {
    38  		c.list()
    39  		return nil
    40  	}
    41  
    42  	task := args[1]
    43  	gc := grift.NewContext(task)
    44  	if len(args) > 2 {
    45  		gc.Args = args[2:]
    46  	}
    47  
    48  	return grift.Run(task, gc)
    49  }
    50  
    51  func (c Command) list() {
    52  	list := grift.List()
    53  	fmt.Printf("There are %v grift tasks available on this app:\n", len(list))
    54  
    55  	w := new(tabwriter.Writer)
    56  	w.Init(os.Stdout, 4, 8, 0, '\t', 0)
    57  
    58  	fmt.Fprintf(w, "\n%s\t%s\t", "task-name", "Full Command")
    59  	fmt.Fprintf(w, "\n%s\t%s\t", "---------", "------------")
    60  	for _, v := range list {
    61  		fmt.Fprintf(w, "\n%v\tox task %s\t", v, v)
    62  	}
    63  	w.Flush()
    64  
    65  	fmt.Printf("\n\nrun one of those with: \nox task [task-name]\n")
    66  }
    67  
    68  func (c Command) FindRoot() string {
    69  	wd, err := os.Getwd()
    70  	if err != nil {
    71  		return ""
    72  	}
    73  
    74  	return wd
    75  }