github.com/gopinath-langote/1build@v1.7.0/cmd/config/io.go (about)

     1  package config
     2  
     3  import (
     4  	"errors"
     5  	"io/ioutil"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/spf13/viper"
    10  	"gopkg.in/yaml.v3"
    11  )
    12  
    13  // ReadFile returns OneBuildConfiguration file content as string.
    14  func ReadFile() (string, error) {
    15  	oneBuildConfigFile := getConfigFile()
    16  	if _, err := os.Stat(oneBuildConfigFile); os.IsNotExist(err) {
    17  		return "", errors.New("no '" + oneBuildConfigFile + "' file found")
    18  	}
    19  	yamlFile, err := ioutil.ReadFile(oneBuildConfigFile)
    20  	if err != nil {
    21  		return "", errors.New("error in reading '" + oneBuildConfigFile + "' configuration file")
    22  	}
    23  	return string(yamlFile), nil
    24  }
    25  
    26  // IsConfigFilePresent return whether the config file present or not
    27  func IsConfigFilePresent() bool {
    28  	oneBuildConfigFile := getConfigFile()
    29  	if _, err := os.Stat(oneBuildConfigFile); err == nil {
    30  		return true
    31  	} else if os.IsNotExist(err) {
    32  		return false
    33  	}
    34  	return false
    35  }
    36  
    37  // WriteConfigFile writes config to the file
    38  // If there is an error, it will be of type *Error.
    39  func WriteConfigFile(configuration OneBuildConfiguration) error {
    40  	oneBuildConfigFile := getConfigFile()
    41  	yamlData, _ := yaml.Marshal(&configuration)
    42  	content := string(yamlData)
    43  	return ioutil.WriteFile(oneBuildConfigFile, []byte(content), 0750)
    44  }
    45  
    46  // DeleteConfigFile deletes the config file
    47  func DeleteConfigFile() error {
    48  	oneBuildConfigFile := getConfigFile()
    49  	return os.Remove(oneBuildConfigFile)
    50  }
    51  
    52  // GetAbsoluteDirPathOfConfigFile gets the base directory from the configuration file location
    53  func GetAbsoluteDirPathOfConfigFile() (string, error) {
    54  	oneBuildConfigFile := getConfigFile()
    55  	abs, err := filepath.Abs(oneBuildConfigFile)
    56  	if err != nil {
    57  		return "", errors.New("error in resolving file path for '" + oneBuildConfigFile + "' configuration file.")
    58  	}
    59  	baseDirFromAbs := filepath.Dir(abs)
    60  	return baseDirFromAbs, nil
    61  }
    62  
    63  // getConfigFile returns the 1build configuration file from root file flag or global file variable
    64  func getConfigFile() string {
    65  	fileFlag := viper.GetString("file")
    66  	if fileFlag == "" {
    67  		return OneBuildConfigFileName
    68  	}
    69  
    70  	return fileFlag
    71  }