github.com/JarrahG/buffalocli@v0.0.0-20230801092127-b85bfd5d395a/internal/genny/fix/movemain.go (about)

     1  package fix
     2  
     3  import (
     4  	"fmt"
     5  	"io"
     6  
     7  	"github.com/gobuffalo/genny/v2"
     8  	"github.com/gobuffalo/refresh/refresh"
     9  	"gopkg.in/yaml.v2"
    10  )
    11  
    12  // MoveMain will move the main.go from the root folder into
    13  // cmd/app/main.go
    14  func MoveMain(opts *Options) genny.RunFn {
    15  	return func(r *genny.Runner) error {
    16  		// If there is a main in the cmd/app folder, we don't need to do anything
    17  		_, err := r.FindFile("cmd/app/main.go")
    18  		if err == nil {
    19  			return nil
    20  		}
    21  
    22  		fmt.Println("~~~ Moving main.go ~~~")
    23  		// If there is a main in the root folder, we need to move it
    24  		f, err := r.FindFile("main.go")
    25  		if err != nil {
    26  			// There is no file to move to move\
    27  			r.Logger.Info("No main.go found")
    28  			return nil
    29  		}
    30  
    31  		nf := genny.NewFileS("cmd/app/main.go", f.String())
    32  		err = r.Disk.Delete("main.go")
    33  		if err != nil {
    34  			return fmt.Errorf("could not delete main.go: %w", err)
    35  		}
    36  
    37  		return r.File(nf)
    38  	}
    39  }
    40  
    41  // Refresh will update the buffalo.dev.yml to build
    42  // the main at ./cmd/app instead of the root folder.
    43  func Refresh(opts *Options) genny.RunFn {
    44  	return func(r *genny.Runner) error {
    45  		fmt.Println("~~~ Checking for .buffalo.dev.yml ~~~")
    46  		f, err := r.FindFile(".buffalo.dev.yml")
    47  		if err != nil {
    48  			return err
    49  		}
    50  
    51  		data, err := io.ReadAll(f)
    52  		if err != nil {
    53  			return err
    54  		}
    55  
    56  		c := refresh.Configuration{}
    57  		err = yaml.Unmarshal(data, &c)
    58  		if err != nil {
    59  			return err
    60  		}
    61  
    62  		if c.BuildTargetPath != "" {
    63  			return nil
    64  		}
    65  
    66  		c.BuildTargetPath = "./cmd/app"
    67  		data, err = yaml.Marshal(&c)
    68  		if err != nil {
    69  			return err
    70  		}
    71  
    72  		_, err = f.Write(data)
    73  		if err != nil {
    74  			return err
    75  		}
    76  
    77  		return r.File(f)
    78  	}
    79  }