github.com/supabase/cli@v1.168.1/internal/migration/new/new.go (about)

     1  package new
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/go-errors/errors"
    10  	"github.com/spf13/afero"
    11  	"github.com/supabase/cli/internal/utils"
    12  )
    13  
    14  func Run(migrationName string, stdin afero.File, fsys afero.Fs) error {
    15  	path := GetMigrationPath(utils.GetCurrentTimestamp(), migrationName)
    16  	if err := utils.MkdirIfNotExistFS(fsys, filepath.Dir(path)); err != nil {
    17  		return err
    18  	}
    19  	f, err := fsys.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
    20  	if err != nil {
    21  		return errors.Errorf("failed to open migration file: %w", err)
    22  	}
    23  	defer func() {
    24  		fmt.Println("Created new migration at " + utils.Bold(path))
    25  		// File descriptor will always be closed when process quits
    26  		_ = f.Close()
    27  	}()
    28  	return CopyStdinIfExists(stdin, f)
    29  }
    30  
    31  func GetMigrationPath(timestamp, name string) string {
    32  	fullName := fmt.Sprintf("%s_%s.sql", timestamp, name)
    33  	return filepath.Join(utils.MigrationsDir, fullName)
    34  }
    35  
    36  func CopyStdinIfExists(stdin afero.File, dst io.Writer) error {
    37  	if fi, err := stdin.Stat(); err != nil {
    38  		return errors.Errorf("failed to initialise stdin: %w", err)
    39  	} else if (fi.Mode() & os.ModeCharDevice) == 0 {
    40  		// Ref: https://stackoverflow.com/a/26567513
    41  		if _, err := io.Copy(dst, stdin); err != nil {
    42  			return errors.Errorf("failed to copy from stdin: %w", err)
    43  		}
    44  	}
    45  	return nil
    46  }