github.com/mg98/scriptup@v0.1.0/pkg/scriptup/new.go (about)

     1  package scriptup
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"github.com/mg98/scriptup/pkg/scriptup/migration"
     7  	"os"
     8  	"regexp"
     9  	"time"
    10  )
    11  
    12  // templateContent is the initial content in a new migration file.
    13  var templateContent = `### migrate up ###
    14  
    15  ### migrate down ###
    16  `
    17  
    18  // currentTime returns the current time as it would be used inside the migration's identifier.
    19  // This is abstracted into a variable to let it be overridden in testing.
    20  var currentTime = time.Now().UTC
    21  
    22  // NewMigrationFile creates a new migration file.
    23  func NewMigrationFile(cfg *Config, name string) error {
    24  	if name == "" {
    25  		return errors.New("no migration name")
    26  	}
    27  	if !regexp.MustCompile(fmt.Sprintf("^%s$", migration.NamePattern)).MatchString(name) {
    28  		return errors.New("name contains illegal characters")
    29  	}
    30  	ts := currentTime().Format(migration.DateLayout)
    31  	return os.WriteFile(
    32  		fmt.Sprintf("%s/%s_%s.sh", cfg.Directory, ts, name),
    33  		[]byte(templateContent),
    34  		0644,
    35  	)
    36  }