github.com/gobuffalo/buffalo-cli/v2@v2.0.0-alpha.15.0.20200919213536-a7350c8e6799/cli/internal/cligen/cligen.go (about)

     1  package cligen
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"html/template"
     7  	"os"
     8  	"path"
     9  	"path/filepath"
    10  	"strings"
    11  
    12  	"github.com/gobuffalo/here"
    13  )
    14  
    15  var (
    16  	// ErrCLIMainExists is returned if the CLI main exists.
    17  	ErrCLIMainExists = errors.New("cmd/buffalo/main.go already exists")
    18  )
    19  
    20  type Generator struct {
    21  	Plugins map[string]string
    22  }
    23  
    24  func (g *Generator) Generate(ctx context.Context, root string, args []string) error {
    25  	info, err := here.Dir(root)
    26  	if err != nil {
    27  		return err
    28  	}
    29  
    30  	x := filepath.Join(root, "cmd", "buffalo")
    31  	fp := filepath.Join(x, "main.go")
    32  
    33  	if err := os.MkdirAll(filepath.Dir(fp), 0755); err != nil {
    34  		return err
    35  	}
    36  
    37  	if _, err := os.Stat(fp); err == nil {
    38  		return ErrCLIMainExists
    39  	}
    40  
    41  	f, err := os.Create(fp)
    42  	if err != nil {
    43  		return err
    44  	}
    45  
    46  	body := strings.TrimSpace(tmplMain)
    47  	tmpl, err := template.New(fp).Parse(body)
    48  	if err != nil {
    49  		return err
    50  	}
    51  
    52  	if g.Plugins == nil {
    53  		g.Plugins = map[string]string{}
    54  	}
    55  
    56  	err = tmpl.Execute(f, struct {
    57  		Name       string
    58  		ImportPath string
    59  		Plugs      map[string]string
    60  	}{
    61  		ImportPath: info.Module.Path,
    62  		Name:       path.Base(info.Module.Path),
    63  		Plugs:      g.Plugins,
    64  	})
    65  
    66  	if err != nil {
    67  		return err
    68  	}
    69  
    70  	if err := f.Close(); err != nil {
    71  		return err
    72  	}
    73  
    74  	return nil
    75  }
    76  
    77  const tmplMain = `
    78  package main
    79  
    80  import (
    81  	"context"
    82  	"fmt"
    83  	"log"
    84  	"os"
    85  
    86  	"github.com/gobuffalo/buffalo-cli/v2/cli"
    87  )
    88  
    89  func main() {
    90  	fmt.Print("~~~~ Using {{.Name}}/cmd/buffalo ~~~\n\n")
    91  
    92  	ctx := context.Background()
    93  	pwd, err := os.Getwd()
    94  	if err != nil {
    95  		log.Fatal(err)
    96  	}
    97  
    98  	buffalo, err := cli.New()
    99  	if err != nil {
   100  		log.Fatal(err)
   101  	}
   102  
   103  	// append your plugins here
   104  	// buffalo.Plugins = append(buffalo.Plugins, ...)
   105  
   106  	err = buffalo.Main(ctx, pwd, os.Args[1:])
   107  	if err != nil {
   108  		log.Fatal(err)
   109  	}
   110  }
   111  `