Skip to content
Snippets Groups Projects
build.go 1.88 KiB
Newer Older
steeve.chailloux's avatar
steeve.chailloux committed
package cmd

	"github.com/rs/zerolog"

	"orus.io/orus-io/beaver/lib/logging"
Florent Aide's avatar
Florent Aide committed
	"orus.io/orus-io/beaver/runner"
Florent Aide's avatar
Florent Aide committed

steeve.chailloux's avatar
steeve.chailloux committed
type BuildCmd struct {
	Args struct {
steeve.chailloux's avatar
steeve.chailloux committed
		DryRun bool   `short:"d" long:"dry-run" description:"if set only prints commands but do not run them"`
		Keep   bool   `short:"k" long:"keep" description:"Keep the temporary files"`
		Output string `short:"o" long:"output" description:"output directory, use \"stdout\" to print to stdout"`
Florent Aide's avatar
Florent Aide committed
	PositionalArgs struct {
Florent Aide's avatar
Florent Aide committed
		DirName string `required:"yes" positional-arg-name:"directory"`
steeve.chailloux's avatar
steeve.chailloux committed
	} `positional-args:"yes"`
	log zerolog.Logger `no-flag:"t"`
steeve.chailloux's avatar
steeve.chailloux committed
}

// NewBuildCmd ...
func NewBuildCmd(loggingOptions *logging.Options) *BuildCmd {
	cmd := BuildCmd{log: loggingOptions.Logger()}
steeve.chailloux's avatar
steeve.chailloux committed
	return &cmd
}

// Execute ...
func (cmd *BuildCmd) Execute([]string) error {
Florent Aide's avatar
Florent Aide committed
	cmd.log.Debug().Str("directory", cmd.PositionalArgs.DirName).Msg("starting beaver")
Florent Aide's avatar
Florent Aide committed
	config := runner.NewCmdConfig(cmd.log, ".", cmd.PositionalArgs.DirName, cmd.Args.DryRun, cmd.Args.Output)
steeve.chailloux's avatar
steeve.chailloux committed
	path, err := os.Getwd()
	if err != nil {
		cmd.log.Fatal().Err(err).Msg("cannot get current working directory")
steeve.chailloux's avatar
steeve.chailloux committed
	}

	tmpDir, err := os.MkdirTemp(path, ".beaver-")
	if err != nil {
		return fmt.Errorf("failed to create temp dir: %w", err)
	}
steeve.chailloux's avatar
steeve.chailloux committed
	if !cmd.Args.Keep {
		defer func() {
			if err := os.RemoveAll(tmpDir); err != nil {
				cmd.log.Err(err).Str("tempdir", tmpDir).Msg("failed to remove temp dir")

	if err := config.Initialize(tmpDir); err != nil {
		return fmt.Errorf("failed to prepare config: %w", err)
Florent Aide's avatar
Florent Aide committed
	}
	r := runner.NewRunner(config)
	return r.Build(tmpDir)
steeve.chailloux's avatar
steeve.chailloux committed
}

func init() {
	buildCmd := NewBuildCmd(LoggingOptions)
steeve.chailloux's avatar
steeve.chailloux committed
	_, err := parser.AddCommand("build", "Build new environment", "", buildCmd)
	if err != nil {
		Logger.Fatal().Msg(err.Error())
	}

	g, err := parser.AddGroup("Logging", "Logging options", LoggingOptions)
	if err != nil {
		panic(err)
	}
	g.Namespace = "log"
steeve.chailloux's avatar
steeve.chailloux committed
}