github.com/wawandco/oxpecker-plugins@v0.1.1/tools/pop/fixer.go (about)

     1  package pop
     2  
     3  import (
     4  	"context"
     5  	"errors"
     6  	"fmt"
     7  	"io/ioutil"
     8  	"os"
     9  
    10  	"github.com/wawandco/oxpecker-plugins/lifecycle/fix"
    11  	"github.com/wawandco/oxpecker/plugins"
    12  )
    13  
    14  // Err..
    15  var (
    16  	_ plugins.Plugin = (*Fixer)(nil)
    17  	_ fix.Fixer      = (*Fixer)(nil)
    18  
    19  	ErrDatabaseNotExist = errors.New(" database.yml does not exist")
    20  )
    21  
    22  // Fixer type ...
    23  type Fixer struct{}
    24  
    25  func (f Fixer) Name() string {
    26  	return "fix database"
    27  }
    28  
    29  // Fix moves the file "database.yml" to
    30  // "/config/database.yml". If the file
    31  // already exists it ignores the oparation
    32  func (f Fixer) Fix(ctx context.Context, root string, args []string) error {
    33  	//search for file
    34  	_, err := f.fileExists(".")
    35  	if err != nil {
    36  		return err
    37  	}
    38  	err = os.MkdirAll("config/", 0755)
    39  	if err != nil {
    40  		return err
    41  	}
    42  	_, err = f.fileExists("config/")
    43  	if err == ErrDatabaseNotExist {
    44  		err = f.moveFile()
    45  		if err != nil {
    46  			return err
    47  		}
    48  	}
    49  
    50  	return nil
    51  }
    52  
    53  // moveFile moves the database.yml file to
    54  // a config/ directory
    55  
    56  func (f Fixer) moveFile() error {
    57  
    58  	err := os.Rename("database.yml", "config/database.yml")
    59  	if err != nil {
    60  		return err
    61  	}
    62  
    63  	return nil
    64  }
    65  
    66  // fileExists search in the s directory for
    67  // the "database.yml" file
    68  func (f Fixer) fileExists(s string) (bool, error) {
    69  	files, err := ioutil.ReadDir(s)
    70  	if err != nil {
    71  		return false, err
    72  	}
    73  
    74  	for _, f := range files {
    75  		if f.Name() == "database.yml" {
    76  			fmt.Println(f.Name() + " found")
    77  			return true, nil
    78  		}
    79  	}
    80  
    81  	return false, ErrDatabaseNotExist
    82  }