Skip to content

Commit

Permalink
refactor: refactors global arguments (#43)
Browse files Browse the repository at this point in the history
  • Loading branch information
jmgilman authored Sep 14, 2024
1 parent 80b759e commit a0dae67
Show file tree
Hide file tree
Showing 14 changed files with 65 additions and 43 deletions.
4 changes: 2 additions & 2 deletions forge/cli/cmd/cmds/dump.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@ type DumpCmd struct {
Pretty bool `help:"Pretty print JSON output."`
}

func (c *DumpCmd) Run(logger *slog.Logger) error {
project, err := loadProject(c.Project, logger)
func (c *DumpCmd) Run(logger *slog.Logger, global GlobalArgs) error {
project, err := loadProject(global, c.Project, logger)
if err != nil {
return fmt.Errorf("could not load project: %w", err)
}
Expand Down
10 changes: 3 additions & 7 deletions forge/cli/cmd/cmds/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,21 +10,19 @@ import (

type RunCmd struct {
Artifact string `short:"a" help:"Dump all produced artifacts to the given path."`
CI bool `help:"Run the target in CI mode."`
Local bool `short:"l" help:"Forces the target to run locally (ignores satellite)."`
Path string `arg:"" help:"The path to the target to execute (i.e., ./dir1+test)."`
Platform []string `short:"p" help:"Run the target with the given platform."`
Pretty bool `help:"Pretty print JSON output."`
TargetArgs []string `arg:"" help:"Arguments to pass to the target." default:""`
}

func (c *RunCmd) Run(logger *slog.Logger) error {
func (c *RunCmd) Run(logger *slog.Logger, global GlobalArgs) error {
ref, err := earthfile.ParseEarthfileRef(c.Path)
if err != nil {
return err
}

project, err := loadProject(ref.Path, logger)
project, err := loadProject(global, ref.Path, logger)
if err != nil {
return err
}
Expand All @@ -36,11 +34,9 @@ func (c *RunCmd) Run(logger *slog.Logger) error {
)
result, err := project.RunTarget(
ref.Target,
c.CI,
c.Local,
localExec,
secrets.NewDefaultSecretStore(),
generateOpts(c)...,
generateOpts(c, &global)...,
)
if err != nil {
return err
Expand Down
14 changes: 9 additions & 5 deletions forge/cli/cmd/cmds/scan.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,20 @@ import (
type ScanCmd struct {
Absolute bool `short:"a" help:"Output absolute paths."`
Blueprint bool `help:"Return the blueprint for each project."`
CI bool `help:"Run in CI mode."`
Earthfile bool `help:"Return the Earthfile targets for each project."`
Filter []string `short:"f" help:"Filter Earthfile targets by regular expression or blueprint results by path."`
Pretty bool `help:"Pretty print JSON output."`
RootPath string `arg:"" help:"Root path to scan for Earthfiles and their respective targets."`
}

func (c *ScanCmd) Run(logger *slog.Logger) error {
func (c *ScanCmd) Run(logger *slog.Logger, global GlobalArgs) error {
walker := walker.NewDefaultFSWalker(logger)
loader := project.NewDefaultProjectLoader(project.GetDefaultRuntimes(logger), logger)
loader := project.NewDefaultProjectLoader(
false,
false,
project.GetDefaultRuntimes(logger),
logger,
)

var rootPath string
if c.Absolute {
Expand Down Expand Up @@ -94,7 +98,7 @@ func (c *ScanCmd) Run(logger *slog.Logger) error {
}
}

if c.CI {
if global.CI {
enumerated := make(map[string][]string)
for filter, targetMap := range result {
enumerated[filter] = enumerate(targetMap)
Expand All @@ -113,7 +117,7 @@ func (c *ScanCmd) Run(logger *slog.Logger) error {
}
}

if c.CI {
if global.CI {
enumerated := enumerate(result)
sort.Strings(enumerated)
printJson(enumerated, c.Pretty)
Expand Down
8 changes: 4 additions & 4 deletions forge/cli/cmd/cmds/secret.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,12 +35,12 @@ type SecretCmd struct {
Set *Set `cmd:"" help:"Set a secret."`
}

func (c *Get) Run(logger *slog.Logger) error {
func (c *Get) Run(logger *slog.Logger, global GlobalArgs) error {
var path, provider string
var maps map[string]string

if c.Project != "" {
project, err := loadProject(c.Project, logger)
project, err := loadProject(global, c.Project, logger)
if err != nil {
return fmt.Errorf("could not load project: %w", err)
}
Expand Down Expand Up @@ -125,11 +125,11 @@ func (c *Get) Run(logger *slog.Logger) error {
return nil
}

func (c *Set) Run(logger *slog.Logger) error {
func (c *Set) Run(logger *slog.Logger, global GlobalArgs) error {
var path, provider string

if c.Project != "" {
project, err := loadProject(c.Project, logger)
project, err := loadProject(global, c.Project, logger)
if err != nil {
return fmt.Errorf("could not load project: %w", err)
}
Expand Down
7 changes: 3 additions & 4 deletions forge/cli/cmd/cmds/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
)

type TagCmd struct {
CI bool `help:"Run in CI mode."`
Pretty bool `short:"p" help:"Pretty print JSON output."`
Project string `arg:"" help:"The project to generate tags for."`
Trim bool `short:"t" help:"Trim the project path from the git tag."`
Expand All @@ -19,14 +18,14 @@ type TagOutput struct {
Git string `json:"git"`
}

func (c *TagCmd) Run(logger *slog.Logger) error {
project, err := loadProject(c.Project, logger)
func (c *TagCmd) Run(logger *slog.Logger, global GlobalArgs) error {
project, err := loadProject(global, c.Project, logger)
if err != nil {
return err
}

var output TagOutput
tagger := p.NewTagger(&project, c.CI, c.Trim, logger)
tagger := p.NewTagger(&project, global.CI, c.Trim, logger)

if project.Blueprint.Global.CI.Tagging.Strategy != "" {
tag, err := tagger.GenerateTag()
Expand Down
19 changes: 15 additions & 4 deletions forge/cli/cmd/cmds/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,12 @@ import (
"github.com/input-output-hk/catalyst-forge/forge/cli/pkg/project"
)

type GlobalArgs struct {
CI bool `help:"Run in CI mode."`
Local bool `short:"l" help:"Forces all runs to happen locally (ignores any remote satellites)."`
Verbose int `short:"v" type:"counter" help:"Enable verbose logging."`
}

// enumerate enumerates the Earthfile+Target pairs from the target map.
func enumerate(data map[string][]string) []string {
var result []string
Expand All @@ -23,15 +29,15 @@ func enumerate(data map[string][]string) []string {

// generateOpts generates the options for the Earthly executor based on command
// flags.
func generateOpts(flags *RunCmd) []earthly.EarthlyExecutorOption {
func generateOpts(flags *RunCmd, global *GlobalArgs) []earthly.EarthlyExecutorOption {
var opts []earthly.EarthlyExecutorOption

if flags != nil {
if flags.Artifact != "" {
opts = append(opts, earthly.WithArtifact(flags.Artifact))
}

if flags.CI {
if global.CI {
opts = append(opts, earthly.WithCI())
}

Expand All @@ -49,8 +55,13 @@ func generateOpts(flags *RunCmd) []earthly.EarthlyExecutorOption {
}

// loadProject loads the project from the given root path.
func loadProject(rootPath string, logger *slog.Logger) (project.Project, error) {
loader := project.NewDefaultProjectLoader(project.GetDefaultRuntimes(logger), logger)
func loadProject(global GlobalArgs, rootPath string, logger *slog.Logger) (project.Project, error) {
loader := project.NewDefaultProjectLoader(
global.CI,
global.Local,
project.GetDefaultRuntimes(logger),
logger,
)
return loader.Load(rootPath)
}

Expand Down
4 changes: 2 additions & 2 deletions forge/cli/cmd/cmds/validate.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ type ValidateCmd struct {
Project string `arg:"" help:"Path to the project."`
}

func (c *ValidateCmd) Run(logger *slog.Logger) error {
_, err := loadProject(c.Project, logger)
func (c *ValidateCmd) Run(logger *slog.Logger, global GlobalArgs) error {
_, err := loadProject(global, c.Project, logger)
if err != nil {
return err
}
Expand Down
6 changes: 3 additions & 3 deletions forge/cli/cmd/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,15 @@ import (
var version = "dev"

var cli struct {
cmds.GlobalArgs

Dump cmds.DumpCmd `cmd:"" help:"Dumps a project's blueprint to JSON."`
Run cmds.RunCmd `cmd:"" help:"Run an Earthly target."`
Scan cmds.ScanCmd `cmd:"" help:"Scan for Earthfiles."`
Secret cmds.SecretCmd `cmd:"" help:"Manage secrets."`
Tag cmds.TagCmd `cmd:"" help:"Generate a tag for a project."`
Validate cmds.ValidateCmd `cmd:"" help:"Validates a project."`
Version VersionCmd `cmd:"" help:"Print the version."`
Verbose int `short:"v" type:"counter" help:"Enable verbose logging."`
}

type VersionCmd struct{}
Expand Down Expand Up @@ -58,8 +59,7 @@ func Run() int {
handler.SetLevel(log.DebugLevel)
}

logger := slog.New(handler)
ctx.Bind(logger)
ctx.Bind(slog.New(handler), cli.GlobalArgs)

err := ctx.Run()
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion forge/cli/cmd/testdata/run/4.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
exec git init .
exec forge run --ci --platform test --platform test1 ./dir1+test
exec forge --ci run --platform test --platform test1 ./dir1+test
cmp stdout golden.txt

-- golden.txt --
Expand Down
2 changes: 1 addition & 1 deletion forge/cli/cmd/testdata/run/5.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
exec git init .
exec forge run --ci ./dir1+test
exec forge --ci run ./dir1+test
cmp stdout golden.txt

-- golden.txt --
Expand Down
4 changes: 2 additions & 2 deletions forge/cli/cmd/testdata/scan/2.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ exec git init .
exec forge scan --earthfile .
cmp stdout golden_1.txt

exec forge scan --ci --earthfile .
exec forge --ci scan --earthfile .
cmp stdout golden_1_ci.txt

exec forge scan --absolute --earthfile .
cmpenv stdout golden_2.txt

exec forge scan --absolute --ci --earthfile .
exec forge --ci scan --absolute --earthfile .
cmpenv stdout golden_2_ci.txt

-- golden_1.txt --
Expand Down
2 changes: 1 addition & 1 deletion forge/cli/cmd/testdata/scan/3.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ exec git init .
exec forge scan --earthfile .
cmp stdout golden.txt

exec forge scan --ci --earthfile .
exec forge --ci scan --earthfile .
cmp stdout golden_ci.txt

-- golden.txt --
Expand Down
12 changes: 11 additions & 1 deletion forge/cli/pkg/project/loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,9 @@ type ProjectLoader interface {
// DefaultProjectLoader is the default implementation of the ProjectLoader.
type DefaultProjectLoader struct {
blueprintLoader loader.BlueprintLoader
ci bool
fs afero.Fs
local bool
logger *slog.Logger
repoLoader git.RepoLoader
runtimes []RuntimeData
Expand Down Expand Up @@ -114,7 +116,9 @@ func (p *DefaultProjectLoader) Load(projectPath string) (Project, error) {

return Project{
Blueprint: bp,
CI: p.ci,
Earthfile: ef,
Local: p.local,
Name: bp.Project.Name,
Path: projectPath,
Repo: repo,
Expand All @@ -125,7 +129,11 @@ func (p *DefaultProjectLoader) Load(projectPath string) (Project, error) {
}

// NewDefaultProjectLoader creates a new DefaultProjectLoader.
func NewDefaultProjectLoader(runtimes []RuntimeData, logger *slog.Logger) DefaultProjectLoader {
func NewDefaultProjectLoader(
ci, local bool,
runtimes []RuntimeData,
logger *slog.Logger,
) DefaultProjectLoader {
if logger == nil {
logger = slog.New(slog.NewTextHandler(io.Discard, nil))
}
Expand All @@ -134,7 +142,9 @@ func NewDefaultProjectLoader(runtimes []RuntimeData, logger *slog.Logger) Defaul
rl := git.NewDefaultRepoLoader()
return DefaultProjectLoader{
blueprintLoader: &bl,
ci: ci,
fs: afero.NewOsFs(),
local: local,
logger: logger,
repoLoader: &rl,
runtimes: runtimes,
Expand Down
14 changes: 8 additions & 6 deletions forge/cli/pkg/project/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ type TagInfo struct {
// Project represents a project
type Project struct {
Blueprint schema.Blueprint
CI bool
Earthfile *earthfile.Earthfile
Local bool
Name string
Path string
Repo *gg.Repository
Expand Down Expand Up @@ -73,10 +75,9 @@ func (p *Project) Raw() blueprint.RawBlueprint {
return p.rawBlueprint
}

// RunTarget runs the given Earthly target.
func (p *Project) RunTarget(
target string,
ci bool,
local bool,
exec executor.Executor,
store secrets.SecretStore,
opts ...earthly.EarthlyExecutorOption,
Expand All @@ -87,11 +88,12 @@ func (p *Project) RunTarget(
exec,
store,
p.logger,
append(p.generateOpts(target, ci, local), opts...)...,
append(p.generateOpts(target), opts...)...,
).Run()
}

func (p *Project) generateOpts(target string, ci, local bool) []earthly.EarthlyExecutorOption {
// generateOpts generates the options for the Earthly executor.
func (p *Project) generateOpts(target string) []earthly.EarthlyExecutorOption {
var opts []earthly.EarthlyExecutorOption

if _, ok := p.Blueprint.Project.CI.Targets[target]; ok {
Expand All @@ -107,7 +109,7 @@ func (p *Project) generateOpts(target string, ci, local bool) []earthly.EarthlyE
}

// We only run multiple platforms in CI mode to avoid issues with local builds.
if targetConfig.Platforms != nil && ci {
if targetConfig.Platforms != nil && p.CI {
opts = append(opts, earthly.WithPlatforms(targetConfig.Platforms...))
}

Expand All @@ -124,7 +126,7 @@ func (p *Project) generateOpts(target string, ci, local bool) []earthly.EarthlyE
}
}

if p.Blueprint.Global.CI.Providers.Earthly.Satellite != nil && !local {
if p.Blueprint.Global.CI.Providers.Earthly.Satellite != nil && !p.Local {
opts = append(opts, earthly.WithSatellite(*p.Blueprint.Global.CI.Providers.Earthly.Satellite))
}

Expand Down

0 comments on commit a0dae67

Please sign in to comment.