Skip to content
This repository has been archived by the owner on Jul 12, 2022. It is now read-only.

Change build formulas behavior #332

Merged
merged 3 commits into from
Jul 31, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ func buildCommands() *cobra.Command {
tutorialFindSetter := rtutorial.NewFindSetter(ritchieHomeDir, tutorialFinder, tutorialSetter)

formBuildMake := builder.NewBuildMake()
formBuildBat := builder.NewBuildBat()
formBuildBat := builder.NewBuildBat(fileManager)
formBuildDocker := builder.NewBuildDocker()
formulaLocalBuilder := builder.NewBuildLocal(ritchieHomeDir, dirManager, fileManager, treeGen)

Expand Down
8 changes: 4 additions & 4 deletions pkg/cmd/build_formula.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package cmd
import (
"errors"
"fmt"
"path"
"path/filepath"
"time"

"github.com/kaduartur/go-cli-spinner/pkg/spinner"
Expand All @@ -19,7 +19,7 @@ import (
const (
newWorkspace = "Type new formula workspace?"
dirPattern = "%s/%s"
treeDir = "tree"
docsDir = "docs"
srcDir = "src"
)

Expand Down Expand Up @@ -74,7 +74,7 @@ func (b buildFormulaCmd) runFunc() CommandRunnerFunc {
return err
}

defaultWorkspace := path.Join(b.userHomeDir, formula.DefaultWorkspaceDir)
defaultWorkspace := filepath.Join(b.userHomeDir, formula.DefaultWorkspaceDir)
if b.directory.Exists(defaultWorkspace) {
workspaces[formula.DefaultWorkspaceName] = defaultWorkspace
}
Expand Down Expand Up @@ -142,7 +142,7 @@ func (b buildFormulaCmd) readFormulas(dir string) (string, error) {
return "", err
}

dirs = sliceutil.Remove(dirs, treeDir)
dirs = sliceutil.Remove(dirs, docsDir)

if isFormula(dirs) {
return dir, nil
Expand Down
6 changes: 3 additions & 3 deletions pkg/cmd/create_formula.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path"
"path/filepath"
"strings"
"time"

Expand Down Expand Up @@ -102,7 +103,7 @@ func (c createFormulaCmd) runPrompt() CommandRunnerFunc {
return err
}

defaultWorkspace := path.Join(c.homeDir, formula.DefaultWorkspaceDir)
defaultWorkspace := filepath.Join(c.homeDir, formula.DefaultWorkspaceDir)
workspaces[formula.DefaultWorkspaceName] = defaultWorkspace

wspace, err := FormulaWorkspaceInput(workspaces, c.inList, c.inText)
Expand Down Expand Up @@ -159,8 +160,6 @@ func (c createFormulaCmd) create(cf formula.Create, workspacePath, formulaPath s
return
}

createSuccess(s, cf.Lang)

if err := c.formula.Build(workspacePath, formulaPath); err != nil {
err := prompt.NewError(err.Error())
s.Error(err)
Expand All @@ -172,6 +171,7 @@ func (c createFormulaCmd) create(cf formula.Create, workspacePath, formulaPath s
s.Error(err)
return
}
createSuccess(s, cf.Lang)
buildSuccess(formulaPath, cf.FormulaCmd, tutorialHolder.Current)
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/cmd/formula_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ func TestFormulaCommand_Add(t *testing.T) {
},
{
name: "success docker",
args: []string{"mock", "test", "--local"},
args: []string{"mock", "test", "--docker"},
},
{
name: "success stdin",
Expand Down
8 changes: 4 additions & 4 deletions pkg/cmd/formulas.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import (
const (
subCommand = " SUBCOMMAND"
Group = "group"
localFlag = "local"
dockerFlag = "docker"
rootCmdName = "root"
)

Expand Down Expand Up @@ -108,12 +108,12 @@ func (f FormulaCommand) execFormulaFunc(repo, path string) func(cmd *cobra.Comma
inputType = api.Stdin
}

local, err := cmd.Flags().GetBool(localFlag)
docker, err := cmd.Flags().GetBool(dockerFlag)
if err != nil {
return err
}

if err := f.formula.Run(d, inputType, local); err != nil {
if err := f.formula.Run(d, inputType, docker); err != nil {
return err
}

Expand All @@ -123,5 +123,5 @@ func (f FormulaCommand) execFormulaFunc(repo, path string) func(cmd *cobra.Comma

func addFlags(cmd *cobra.Command) {
formulaFlags := cmd.Flags()
formulaFlags.BoolP(localFlag, "l", false, "Use to run formulas locally")
formulaFlags.BoolP(dockerFlag, "d", false, "Use to run formulas inside docker")
}
4 changes: 2 additions & 2 deletions pkg/credential/settings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ func TestNewDefaultCredentials(t *testing.T) {

func TestProviderPath(t *testing.T) {
provider := credSettings.ProviderPath()
slicedPath := strings.Split(provider, "/")
slicedPath := strings.Split(provider, string(os.PathSeparator))
providersJson := slicedPath[len(slicedPath)-1]

if providersJson != "providers.json" {
Expand All @@ -107,7 +107,7 @@ func TestProviderPath(t *testing.T) {

func TestCredentialsPath(t *testing.T){
credentials := credSettings.CredentialsPath()
slicedPath := strings.Split(credentials, "/")
slicedPath := strings.Split(credentials, string(os.PathSeparator))
fmt.Println(slicedPath)
providersDir := slicedPath[len(slicedPath)-1]

Expand Down
31 changes: 25 additions & 6 deletions pkg/formula/builder/bat.go
Original file line number Diff line number Diff line change
@@ -1,33 +1,52 @@
package builder

import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"

"github.com/ZupIT/ritchie-cli/pkg/formula"
"github.com/ZupIT/ritchie-cli/pkg/stream"
)

const buildFile = "build.bat"
const (
buildFile = "build.bat"
msgBuildErr = "failed building formula with build.bat, verify your repository"
errMsgFmt = `%s
More about error: %s`
)

var ErrBuildFormulaBuildBat = errors.New("failed building formula with build.bat, verify your repository")
var ErrBuildFormulaBuildBat = errors.New(msgBuildErr)

type BatManager struct{}
type BatManager struct {
file stream.FileExister
}

func NewBuildBat() formula.BatBuilder {
return BatManager{}
func NewBuildBat(file stream.FileExister) formula.BatBuilder {
return BatManager{file: file}
}

func (ba BatManager) Build(formulaPath string) error {
if err := os.Chdir(formulaPath); err != nil {
return err
}

if !ba.file.Exists(buildFile) {
return ErrBuildOnWindows
}

var stderr bytes.Buffer
cmd := exec.Command(buildFile)
cmd.Stderr = os.Stderr
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return ErrBuildFormulaBuildBat
}

if stderr.String() != "" {
return fmt.Errorf(errMsgFmt, msgBuildErr, stderr.String())
}

return nil
}
2 changes: 1 addition & 1 deletion pkg/formula/builder/docker.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ func (do DockerManager) Build(formulaPath, dockerImg string) error {
return err
}

args := []string{"run", "-u", "0:0", "-v", volume, "--entrypoint", "/bin/sh", dockerImg, "-c", containerCmd}
args := []string{"run", "--rm", "-u", "0:0", "-v", volume, "--entrypoint", "/bin/sh", dockerImg, "-c", containerCmd}

var stderr bytes.Buffer
cmd := exec.Command("docker", args...)
Expand Down
7 changes: 6 additions & 1 deletion pkg/formula/builder/local.go
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,6 @@ func (m LocalManager) buildFormulaBin(workspacePath, formulaPath, dest string) e

var stderr bytes.Buffer
cmd.Stderr = &stderr

if err := cmd.Run(); err != nil {
if stderr.Bytes() != nil {
errMsg := fmt.Sprintf("Build error: \n%s \n%s", stderr.String(), err)
Expand All @@ -98,6 +97,12 @@ func (m LocalManager) buildFormulaBin(workspacePath, formulaPath, dest string) e
return err
}

if so == osutil.Windows {
if stderr.String() != "" {
return fmt.Errorf("%s \nMore about error: %s", ErrBuildFormulaBuildBat, stderr.String())
}
}

return nil
}

Expand Down
4 changes: 2 additions & 2 deletions pkg/formula/formula.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,11 +75,11 @@ type (
)

type PreRunner interface {
PreRun(def Definition, local bool) (Setup, error)
PreRun(def Definition, docker bool) (Setup, error)
}

type Runner interface {
Run(def Definition, inputType api.TermInputType, local bool) error
Run(def Definition, inputType api.TermInputType, docker bool) error
}

type PostRunner interface {
Expand Down
18 changes: 1 addition & 17 deletions pkg/formula/runner/post_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package runner

import (
"fmt"
"os/exec"

"github.com/ZupIT/ritchie-cli/pkg/file/fileutil"
"github.com/ZupIT/ritchie-cli/pkg/formula"
Expand All @@ -23,10 +22,6 @@ func (po PostRunnerManager) PostRun(p formula.Setup, docker bool) error {
if err := po.file.Remove(envFile); err != nil {
return err
}

if err := removeContainer(p.ContainerId); err != nil {
return err
}
}

defer po.removeWorkDir(p.TmpDir)
Expand All @@ -47,15 +42,4 @@ func (po PostRunnerManager) removeWorkDir(tmpDir string) {
if err := po.dir.Remove(tmpDir); err != nil {
fmt.Sprintln("Error in remove dir")
}
}

func removeContainer(imgName string) error {
args := []string{"rm", imgName}
cmd := exec.Command(dockerCmd, args...)

if err := cmd.Run(); err != nil {
return err
}

return nil
}
}
38 changes: 23 additions & 15 deletions pkg/formula/runner/pre_run.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ import (
"os/exec"
"path/filepath"
"runtime"
"strings"
"time"

"github.com/google/uuid"
"github.com/kaduartur/go-cli-spinner/pkg/spinner"

"github.com/ZupIT/ritchie-cli/pkg/formula"
Expand All @@ -27,7 +27,7 @@ type PreRunManager struct {
make formula.MakeBuilder
docker formula.DockerBuilder
bat formula.BatBuilder
dir stream.DirCreateListCopier
dir stream.DirCreateListCopyRemover
file stream.FileReadExister
}

Expand All @@ -36,7 +36,7 @@ func NewPreRun(
make formula.MakeBuilder,
docker formula.DockerBuilder,
bat formula.BatBuilder,
dir stream.DirCreateListCopier,
dir stream.DirCreateListCopyRemover,
file stream.FileReadExister,
) PreRunManager {
return PreRunManager{
Expand All @@ -49,7 +49,7 @@ func NewPreRun(
}
}

func (pr PreRunManager) PreRun(def formula.Definition, local bool) (formula.Setup, error) {
func (pr PreRunManager) PreRun(def formula.Definition, docker bool) (formula.Setup, error) {
pwd, _ := os.Getwd()
formulaPath := def.FormulaPath(pr.ritchieHome)

Expand All @@ -62,8 +62,14 @@ func (pr PreRunManager) PreRun(def formula.Definition, local bool) (formula.Setu
if !pr.file.Exists(binFilePath) {
s := spinner.StartNew("Building formula...")
time.Sleep(2 * time.Second)
if err := pr.buildFormula(formulaPath, config.DockerIB, local); err != nil {
if err := pr.buildFormula(formulaPath, config.DockerIB, docker); err != nil {
s.Stop()

// Remove /bin dir to force formula rebuild in next execution
if err := pr.dir.Remove(def.BinPath(formulaPath)); err != nil {
return formula.Setup{}, err
}

return formula.Setup{}, err
}
s.Success(prompt.Green("Formula was successfully built!"))
Expand All @@ -88,8 +94,8 @@ func (pr PreRunManager) PreRun(def formula.Definition, local bool) (formula.Setu
}

dockerFile := filepath.Join(tmpDir, "Dockerfile")
if !local && validateDocker() && pr.file.Exists(dockerFile) {
s.ContainerId, err = buildRunImg()
if docker && validateDocker() && pr.file.Exists(dockerFile) {
s.ContainerId, err = buildRunImg(def)
if err != nil {
return formula.Setup{}, err
}
Expand All @@ -98,8 +104,8 @@ func (pr PreRunManager) PreRun(def formula.Definition, local bool) (formula.Setu
return s, nil
}

func (pr PreRunManager) buildFormula(formulaPath, dockerIB string, localFlag bool) error {
if !localFlag && dockerIB != "" && validateDocker() { // Build formula inside docker
func (pr PreRunManager) buildFormula(formulaPath, dockerIB string, dockerFlag bool) error {
if dockerFlag && dockerIB != "" && validateDocker() { // Build formula inside docker
if err := pr.docker.Build(formulaPath, dockerIB); err != nil {
fmt.Println("\n" + err.Error())
} else {
Expand Down Expand Up @@ -152,13 +158,15 @@ func (pr PreRunManager) createWorkDir(home, formulaPath string, def formula.Defi
return tDir, nil
}

func buildRunImg() (string, error) {
func buildRunImg(def formula.Definition) (string, error) {
s := spinner.StartNew("Building docker image to run formula...")
containerId, err := uuid.NewRandom()
if err != nil {
return "", err
formName := strings.ReplaceAll(def.Path, string(os.PathSeparator), "-")
containerId := fmt.Sprintf("rit-repo-%s-formula%s", def.RepoName, formName)
if len(containerId) > 200 {
containerId = containerId[:200]
}
args := []string{"build", "-t", containerId.String(), "."}

args := []string{"build", "-t", containerId, "."}
cmd := exec.Command(dockerCmd, args...) // Run command "docker build -t (randomId) ."
cmd.Stderr = os.Stderr

Expand All @@ -168,7 +176,7 @@ func buildRunImg() (string, error) {
}

s.Success(prompt.Green("Docker image successfully built!"))
return containerId.String(), err
return containerId, nil
}

// validate checks if able to run inside docker
Expand Down
Loading