Skip to content

Commit

Permalink
Execute 1build from specified configuration file (#199)
Browse files Browse the repository at this point in the history
  • Loading branch information
gopinath-langote authored Aug 16, 2020
1 parent 4ef9066 commit b89d622
Show file tree
Hide file tree
Showing 20 changed files with 367 additions and 105 deletions.
44 changes: 35 additions & 9 deletions cmd/config/io.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,42 +4,68 @@ import (
"errors"
"io/ioutil"
"os"
"path/filepath"

"github.com/spf13/viper"
"gopkg.in/yaml.v3"
)

// ReadFile returns OneBuildConfiguration file content as string.
func ReadFile() (string, error) {
if _, err := os.Stat(OneBuildConfigFileName); os.IsNotExist(err) {
return "", errors.New("no '" + OneBuildConfigFileName + "' file found in current directory")
oneBuildConfigFile := getConfigFile()
if _, err := os.Stat(oneBuildConfigFile); os.IsNotExist(err) {
return "", errors.New("no '" + oneBuildConfigFile + "' file found")
}
yamlFile, err := ioutil.ReadFile(OneBuildConfigFileName)
yamlFile, err := ioutil.ReadFile(oneBuildConfigFile)
if err != nil {
return "", errors.New("error in reading '" + OneBuildConfigFileName + "' configuration file")
return "", errors.New("error in reading '" + oneBuildConfigFile + "' configuration file")
}
return string(yamlFile), nil
}

// IsConfigFilePresent return whether the config file present or not
func IsConfigFilePresent() bool {
if _, err := os.Stat(OneBuildConfigFileName); err == nil {
oneBuildConfigFile := getConfigFile()
if _, err := os.Stat(oneBuildConfigFile); err == nil {
return true
} else if os.IsNotExist(err) {
return false
} else {
return true
}
return false
}

// WriteConfigFile writes config to the file
// If there is an error, it will be of type *Error.
func WriteConfigFile(configuration OneBuildConfiguration) error {
oneBuildConfigFile := getConfigFile()
yamlData, _ := yaml.Marshal(&configuration)
content := string(yamlData)
return ioutil.WriteFile(OneBuildConfigFileName, []byte(content), 0777)
return ioutil.WriteFile(oneBuildConfigFile, []byte(content), 0750)
}

// DeleteConfigFile deletes the config file
func DeleteConfigFile() error {
return os.Remove(OneBuildConfigFileName)
oneBuildConfigFile := getConfigFile()
return os.Remove(oneBuildConfigFile)
}

// GetAbsoluteDirPathOfConfigFile gets the base directory from the configuration file location
func GetAbsoluteDirPathOfConfigFile() (string, error) {
oneBuildConfigFile := getConfigFile()
abs, err := filepath.Abs(oneBuildConfigFile)
if err != nil {
return "", errors.New("error in resolving file path for '" + oneBuildConfigFile + "' configuration file.")
}
baseDirFromAbs := filepath.Dir(abs)
return baseDirFromAbs, nil
}

// getConfigFile returns the 1build configuration file from root file flag or global file variable
func getConfigFile() string {
fileFlag := viper.GetString("file")
if fileFlag == "" {
return OneBuildConfigFileName
}

return fileFlag
}
8 changes: 4 additions & 4 deletions cmd/delete.go → cmd/del/delete.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cmd
package del

import (
"bufio"
Expand All @@ -13,7 +13,8 @@ import (

var shouldDelete bool

var deleteCmd = &cobra.Command{
// Cmd cobra command for delete one build configuration
var Cmd = &cobra.Command{
Use: "delete",
Short: "Deletes project configuration",
Long: `Deletes project configuration
Expand Down Expand Up @@ -49,6 +50,5 @@ For example:
}

func init() {
rootCmd.AddCommand(deleteCmd)
deleteCmd.Flags().BoolVarP(&shouldDelete, "force", "f", false, "Forcibly delete configuration file")
Cmd.Flags().BoolVar(&shouldDelete, "force", false, "Forcibly del configuration file")
}
12 changes: 7 additions & 5 deletions cmd/exec/exec.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,28 +67,28 @@ func executeAndStopIfFailed(command *models.CommandContext, executeStart time.Ti

}

func buildExecutionPlan(onebuildConfig config.OneBuildConfiguration, commands ...string) models.OneBuildExecutionPlan {
func buildExecutionPlan(config config.OneBuildConfiguration, commands ...string) models.OneBuildExecutionPlan {

before := onebuildConfig.Before
before := config.Before
var executionPlan models.OneBuildExecutionPlan
if before != "" {
executionPlan.Before = &models.CommandContext{
Name: "before", Command: before, CommandSession: bashCommand(sh.NewSession(), before)}
}

for _, name := range commands {
executionCommand := onebuildConfig.GetCommand(name)
executionCommand := config.GetCommand(name)
if executionCommand == "" {
utils.CPrintln("\nError building execution plan. Command \""+name+"\" not found.",
utils.Style{Color: utils.RED, Bold: true})
onebuildConfig.Print()
config.Print()
utils.ExitWithCode("127")
}
executionPlan.Commands = append(executionPlan.Commands, &models.CommandContext{
Name: name, Command: executionCommand, CommandSession: bashCommand(sh.NewSession(), executionCommand)})
}

after := onebuildConfig.After
after := config.After
if after != "" {
executionPlan.After = &models.CommandContext{
Name: "after", Command: after, CommandSession: bashCommand(sh.NewSession(), after)}
Expand All @@ -98,6 +98,8 @@ func buildExecutionPlan(onebuildConfig config.OneBuildConfiguration, commands ..
}

func bashCommand(s *sh.Session, command string) *sh.Session {
configFileAbsoluteDir, _ := config.GetAbsoluteDirPathOfConfigFile()
s.SetDir(configFileAbsoluteDir)
return s.Command("bash", "-c", command)
}

Expand Down
15 changes: 7 additions & 8 deletions cmd/init.go → cmd/initialize/init.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cmd
package initialize

import (
"fmt"
Expand All @@ -7,7 +7,8 @@ import (
"github.com/spf13/cobra"
)

var initCmd = &cobra.Command{
// Cmd cobra command for initializing one build configuration
var Cmd = &cobra.Command{
Use: "init",
Short: "Create default project configuration",
Long: `Create default project configuration
Expand All @@ -16,8 +17,8 @@ var initCmd = &cobra.Command{
For example:
1build init --name project
1build init --name "My favorite project"`,
1build initialize --name project
1build initialize --name "My favorite project"`,
PreRun: func(cmd *cobra.Command, args []string) {
if config.IsConfigFilePresent() {
fmt.Println("'" + config.OneBuildConfigFileName + "' configuration file already exists.")
Expand All @@ -43,8 +44,6 @@ For example:
}

func init() {
rootCmd.AddCommand(initCmd)

initCmd.Flags().StringP("name", "n", "", "Project name")
_ = initCmd.MarkFlagRequired("name")
Cmd.Flags().StringP("name", "n", "", "Project name")
_ = Cmd.MarkFlagRequired("name")
}
9 changes: 3 additions & 6 deletions cmd/list.go → cmd/list/list.go
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
package cmd
package list

import (
"fmt"
"github.com/gopinath-langote/1build/cmd/config"
"github.com/spf13/cobra"
)

var listCmd = &cobra.Command{
// Cmd cobra command for listing one build configuration
var Cmd = &cobra.Command{
Use: "list",
Short: "Show all available commands from the current project configuration",
Long: "Show all available commands from the current project configuration",
Expand All @@ -19,7 +20,3 @@ var listCmd = &cobra.Command{
oneBuildConfig.Print()
},
}

func init() {
rootCmd.AddCommand(listCmd)
}
30 changes: 22 additions & 8 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,35 @@ package cmd

import (
"fmt"
"github.com/gopinath-langote/1build/cmd/del"
"github.com/gopinath-langote/1build/cmd/initialize"
"github.com/gopinath-langote/1build/cmd/list"
"github.com/gopinath-langote/1build/cmd/set"
"github.com/gopinath-langote/1build/cmd/unset"

parse "github.com/gopinath-langote/1build/cmd/config"
configuration "github.com/gopinath-langote/1build/cmd/config"
"github.com/gopinath-langote/1build/cmd/exec"
"github.com/gopinath-langote/1build/cmd/utils"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)

var rootCmd = &cobra.Command{
// Cmd cobra for root level
var Cmd = &cobra.Command{
Use: "1build",
Version: "1.4.0",
Short: "Frictionless way of managing project-specific commands",
Args: cobra.MinimumNArgs(0),
PreRun: func(cmd *cobra.Command, args []string) {
_, err := parse.LoadOneBuildConfiguration()
_, err := configuration.LoadOneBuildConfiguration()
if err != nil {
fmt.Println(err)
utils.ExitError()
}
},
Run: func(cmd *cobra.Command, args []string) {
if len(args) < 1 {
listCmd.Run(cmd, args)
list.Cmd.Run(cmd, args)
} else {
exec.ExecutePlan(args...)
}
Expand All @@ -33,15 +39,23 @@ var rootCmd = &cobra.Command{

// Execute entry-point for cobra app
func Execute() {
if err := rootCmd.Execute(); err != nil {
if err := Cmd.Execute(); err != nil {
fmt.Println(err)
utils.ExitError()
}
}

func init() {
rootCmd.SetHelpCommand(&cobra.Command{Use: "no-help", Hidden: true})
rootCmd.PersistentFlags().BoolP("quiet", "q", false,
Cmd.SetHelpCommand(&cobra.Command{Use: "no-help", Hidden: true})
Cmd.PersistentFlags().BoolP("quiet", "q", false,
"Hide output log of command & only show SUCCESS/FAILURE result")
_ = viper.BindPFlags(rootCmd.PersistentFlags())
Cmd.PersistentFlags().
StringP("file", "f", configuration.OneBuildConfigFileName, "The file path for 1build configuration file.")
_ = viper.BindPFlags(Cmd.PersistentFlags())

Cmd.AddCommand(list.Cmd)
Cmd.AddCommand(del.Cmd)
Cmd.AddCommand(initialize.Cmd)
Cmd.AddCommand(set.Cmd)
Cmd.AddCommand(unset.Cmd)
}
14 changes: 6 additions & 8 deletions cmd/set.go → cmd/set/set.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package cmd
package set

import (
"fmt"
Expand All @@ -10,7 +10,8 @@ import (
"github.com/spf13/cobra"
)

var setCmd = &cobra.Command{
// Cmd cobra command for setting one build configuration command
var Cmd = &cobra.Command{
Use: "set",
Short: "Set new or update the existing command in the current project configuration",
Long: `Set new or update the existing command in the current project configuration
Expand Down Expand Up @@ -86,7 +87,7 @@ func setCommand(configuration config.OneBuildConfiguration, name string, value s
command := map[string]string{}
command[name] = value

index := indexOfCommandIfPresent(configuration, name)
index := IndexOfCommandIfPresent(configuration, name)
if index == -1 {
strings := append(configuration.Commands, command)
configuration.Commands = strings
Expand All @@ -96,7 +97,8 @@ func setCommand(configuration config.OneBuildConfiguration, name string, value s
return configuration
}

func indexOfCommandIfPresent(configuration config.OneBuildConfiguration, commandName string) int {
// IndexOfCommandIfPresent returns index in configuration for command if exists
func IndexOfCommandIfPresent(configuration config.OneBuildConfiguration, commandName string) int {
return utils.SliceIndex(len(configuration.Commands), func(i int) bool {
i2 := configuration.Commands[i]
for k := range i2 {
Expand All @@ -107,7 +109,3 @@ func indexOfCommandIfPresent(configuration config.OneBuildConfiguration, command
return false
})
}

func init() {
rootCmd.AddCommand(setCmd)
}
11 changes: 5 additions & 6 deletions cmd/unset.go → cmd/unset/unset.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
package cmd
package unset

import (
"fmt"
"github.com/gopinath-langote/1build/cmd/set"
"regexp"
"strings"

Expand All @@ -11,7 +12,8 @@ import (
"github.com/spf13/cobra"
)

var unsetCmd = &cobra.Command{
// Cmd cobra command for unsetting one build configuration command
var Cmd = &cobra.Command{
Use: "unset",
Short: "Remove one or more existing command(s) in the current project configuration",
Long: `Remove one or more existing command(s) in the current project configuration
Expand Down Expand Up @@ -88,7 +90,7 @@ func findIndex(configuration config.OneBuildConfiguration, name string) int {
case config.BeforeCommand, config.AfterCommand:
return callbackExistence(configuration, name)
default:
return indexOfCommandIfPresent(configuration, name)
return set.IndexOfCommandIfPresent(configuration, name)
}
}

Expand All @@ -115,6 +117,3 @@ func removeCommand(configuration config.OneBuildConfiguration, name string, inde
return configuration
}

func init() {
rootCmd.AddCommand(unsetCmd)
}
6 changes: 5 additions & 1 deletion testing/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,11 @@ func TestAll(t *testing.T) {
if tt.Setup != nil {
_ = tt.Setup(testResourceDirectory)
}
cmd := exec.Command(binaryPath, tt.CmdArgs...)
var args []string
if tt.CmdArgs != nil {
args = tt.CmdArgs(testResourceDirectory)
}
cmd := exec.Command(binaryPath, args...)
cmd.Dir = testResourceDirectory
out, _ := cmd.Output()
_ = tt.Assertion(testResourceDirectory, string(out), t)
Expand Down
Loading

0 comments on commit b89d622

Please sign in to comment.