github.com/wawandco/oxplugins@v0.7.11/tools/pop/migration/generator.go (about)

     1  package migration
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  	"time"
    10  
    11  	"github.com/gobuffalo/flect"
    12  	"github.com/pkg/errors"
    13  	"github.com/spf13/pflag"
    14  	"github.com/wawandco/oxplugins/tools/pop/migration/creator"
    15  )
    16  
    17  // Generator allows to identify model as a plugin
    18  type Generator struct {
    19  	migrationType string
    20  }
    21  
    22  // Name returns the name of the generator plugin
    23  func (g Generator) Name() string {
    24  	return "migration"
    25  }
    26  
    27  // Generate generates an empty [name].plush.html file
    28  func (g Generator) Generate(ctx context.Context, root string, args []string) error {
    29  	example := "please use `ox generate migration [name] [columns?] --type=[sql|fizz]`"
    30  	if len(args) < 3 {
    31  		return errors.Errorf("no name specified, %s", example)
    32  	}
    33  
    34  	g.parseFlag(args)
    35  
    36  	dirPath := filepath.Join(root, "migrations")
    37  	if !g.exists(dirPath) {
    38  		if err := os.MkdirAll(dirPath, 0755); err != nil {
    39  			return err
    40  		}
    41  	}
    42  
    43  	creator, err := creator.CreateMigrationFor(strings.ToLower(g.migrationType))
    44  	if err != nil {
    45  		return err
    46  	}
    47  
    48  	name := flect.Underscore(flect.Pluralize(strings.ToLower(args[2])))
    49  	columns := g.parseColumns(args[2:])
    50  
    51  	if err = creator.Create(dirPath, columns); err != nil {
    52  		return errors.Wrap(err, "failed creating migrations")
    53  	}
    54  
    55  	timestamp := time.Now().UTC().Format("20060102150405")
    56  	fileName := fmt.Sprintf("%s_%s", timestamp, name)
    57  	fmt.Printf("[info] Migrations generated in: \n-- migrations/%s.up.%s\n-- migrations/%s.down.%s\n", fileName, creator.Name(), fileName, creator.Name())
    58  
    59  	return nil
    60  }
    61  
    62  func (g Generator) exists(path string) bool {
    63  	_, err := os.Stat(path)
    64  
    65  	return !os.IsNotExist(err)
    66  }
    67  
    68  func (g *Generator) parseFlag(args []string) {
    69  	flags := pflag.NewFlagSet("type", pflag.ContinueOnError)
    70  	flags.StringVarP(&g.migrationType, "type", "t", "fizz", "the type of the migration")
    71  	flags.Parse(args) //nolint:errcheck,we don't care hence the flag
    72  }
    73  
    74  func (g *Generator) parseColumns(args []string) []string {
    75  	if len(args) == 1 {
    76  		return args
    77  	}
    78  
    79  	var columns []string
    80  	for _, arg := range args {
    81  		if !strings.HasPrefix(arg, "-") {
    82  			columns = append(columns, arg)
    83  		}
    84  	}
    85  
    86  	return columns
    87  }