Skip to content

Commit

Permalink
feat(proxy): validate sampler info (#48)
Browse files Browse the repository at this point in the history
  • Loading branch information
plastikfan committed Dec 7, 2023
1 parent b16ee29 commit 010f64e
Show file tree
Hide file tree
Showing 18 changed files with 571 additions and 162 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
coverage
coverage.out
ginkgo.report

dist/
.task/

src/i18n/out/en-US/active.en-GB.json
Expand Down
Binary file removed dist/darwin/pixa
Binary file not shown.
23 changes: 19 additions & 4 deletions src/app/command/bootstrap.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import (
"github.com/snivilised/extendio/xfs/utils"
"github.com/snivilised/pixa/src/app/proxy"
"github.com/snivilised/pixa/src/i18n"
"github.com/snivilised/pixa/src/internal/helpers"
)

type LocaleDetector interface {
Expand All @@ -41,7 +42,7 @@ func validatePositionalArgs(cmd *cobra.Command, args []string) error {
return err
}

directory := proxy.ResolvePath(args[0])
directory := helpers.ResolvePath(args[0])

if !utils.Exists(directory) {
return xi18n.NewPathNotFoundError("shrink directory", directory)
Expand All @@ -63,7 +64,8 @@ type ConfigInfo struct {
type Bootstrap struct {
Container *assistant.CobraContainer
optionsInfo ConfigureOptionsInfo
profiles proxy.ConfiguredProfiles
ProfilesCFG proxy.ProfilesConfig
SamplerCFG proxy.SamplerConfig
}

type ConfigureOptionsInfo struct {
Expand Down Expand Up @@ -123,14 +125,14 @@ func (b *Bootstrap) Root(options ...ConfigureOptionFn) *cobra.Command {
fmt.Printf(" ===> 🌷🌷🌷 Root Command...\n")

inputs := b.getRootInputs()
inputs.ParamSet.Native.Directory = proxy.ResolvePath(args[0])
inputs.ParamSet.Native.Directory = helpers.ResolvePath(args[0])

if inputs.WorkerPoolFam.Native.CPU {
inputs.WorkerPoolFam.Native.NoWorkers = 0
}

profile := inputs.ProfileFam.Native.Profile
if err := b.profiles.Validate(profile); err != nil {
if err := b.ProfilesCFG.Validate(profile); err != nil {
return err
}

Expand Down Expand Up @@ -209,3 +211,16 @@ func handleLangSetting(config configuration.ViperConfig) {
os.Exit(1)
}
}

func (b *Bootstrap) viper() {
// Ideally, the ProfileParameterSet would perform a check against
// the config, but extendio is not aware of config, so it can't
// check. Instead, we can check here.
//
b.ProfilesCFG = b.optionsInfo.Config.Viper.GetStringMapStringSlice("profiles")
err := b.optionsInfo.Config.Viper.UnmarshalKey("sampler", &b.SamplerCFG)

if err != nil {
panic(err)
}
}
88 changes: 74 additions & 14 deletions src/app/command/root-cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,80 @@ func (b *Bootstrap) buildRootCommand(container *assistant.CobraContainer) {
),
Default: xi18n.DefaultLanguage.Get().String(),
AlternativeFlagSet: rootCommand.PersistentFlags(),
}, &paramSet.Native.Language, func(value string, _ *pflag.Flag) error {
_, err := language.Parse(value)
return err
})
},
&paramSet.Native.Language,
func(value string, _ *pflag.Flag) error {
_, err := language.Parse(value)
return err
})

// --sample (pending: sampling-family)
//
paramSet.BindBool(&assistant.FlagInfo{
Name: "sample",
Usage: i18n.LeadsWith(
"sample",
xi18n.Text(i18n.RootCmdSampleUsageTemplData{}),
),
Default: false,
AlternativeFlagSet: rootCommand.PersistentFlags(),
},
&paramSet.Native.IsSampling,
)

const (
defFSItems = uint(3)
minFSItems = uint(1)
maxFSItems = uint(128)
)

// --no-files (pending: sampling-family)
//
paramSet.BindValidatedUintWithin(
&assistant.FlagInfo{
Name: "no-files",
Usage: i18n.LeadsWith(
"no-files",
xi18n.Text(i18n.RootCmdNoFilesUsageTemplData{}),
),
Default: defFSItems,
AlternativeFlagSet: rootCommand.PersistentFlags(),
},
&paramSet.Native.NoFiles,
minFSItems,
maxFSItems,
)

// --no-folders (pending: sampling-family)
//
paramSet.BindValidatedUintWithin(
&assistant.FlagInfo{
Name: "no-folders",
Usage: i18n.LeadsWith(
"no-folders",
xi18n.Text(i18n.RootCmdNoFoldersUsageTemplData{}),
),
Default: defFSItems,
AlternativeFlagSet: rootCommand.PersistentFlags(),
},
&paramSet.Native.NoFolders,
minFSItems,
maxFSItems,
)

// --last (pending: sampling-family)
//
paramSet.BindBool(&assistant.FlagInfo{
Name: "last",
Usage: i18n.LeadsWith(
"last",
xi18n.Text(i18n.RootCmdLastUsageTemplData{}),
),
Default: false,
AlternativeFlagSet: rootCommand.PersistentFlags(),
},
&paramSet.Native.Last,
)

// family: preview [--dry-run(D)]
//
Expand Down Expand Up @@ -81,16 +151,6 @@ func (b *Bootstrap) buildRootCommand(container *assistant.CobraContainer) {
container.MustRegisterParamSet(WorkerPoolFamName, workerPoolFam)
container.MustRegisterParamSet(FoldersFamName, foldersFam)
container.MustRegisterParamSet(ProfileFamName, profileFam)

// This needs to be implemented in extendio, so we can't bind
// here with a validated binder, we just perform a check here
// after the bind as a temporary measure. Actually, this
// needs to be implemented inside cross field validation.

// Ideally, the ProfileParameterSet would perform a check against
// the config, but extendio is not aware of config, so it can't
// check. Instead, we can put this check into
b.profiles = b.optionsInfo.Config.Viper.GetStringMapStringSlice("profiles")
}

func (b *Bootstrap) getRootInputs() *proxy.RootCommandInputs {
Expand Down
49 changes: 38 additions & 11 deletions src/app/command/shrink-cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (

"github.com/snivilised/pixa/src/app/proxy"
"github.com/snivilised/pixa/src/i18n"
"github.com/snivilised/pixa/src/internal/helpers"
)

// We define all the options here, even the ones inherited from the root
Expand Down Expand Up @@ -99,8 +100,9 @@ func (b *Bootstrap) buildShrinkCommand(container *assistant.CobraContainer) *cob
}); xvErr == nil {
options := []string{}
present := make(cobrass.SpecifiedFlagsCollection)
flagSet := cmd.Flags()

cmd.Flags().Visit(func(f *pflag.Flag) {
flagSet.Visit(func(f *pflag.Flag) {
options = append(options, fmt.Sprintf("--%v=%v", f.Name, f.Value))

if isThirdPartyKnown(f.Name, shrinkPS.Native.ThirdPartySet.KnownBy) {
Expand All @@ -113,28 +115,53 @@ func (b *Bootstrap) buildShrinkCommand(container *assistant.CobraContainer) *cob
AppEmoji, ApplicationName, options, strings.Join(args, "/"),
)

if cmd.Flags().Changed("gaussian-blur") {
if flagSet.Changed("gaussian-blur") {
fmt.Printf("💠 Blur defined with value: '%v'\n", cmd.Flag("gaussian-blur").Value)
}

if cmd.Flags().Changed("sampling-factor") {
if flagSet.Changed("sampling-factor") {
fmt.Printf("💠 Blur defined with value: '%v'\n", cmd.Flag("sampling-factor").Value)
}

inputs := b.getShrinkInputs()
inputs.RootInputs.ParamSet.Native.Directory = proxy.ResolvePath(args[0])
inputs.RootInputs.ParamSet.Native.Directory = helpers.ResolvePath(args[0])

// validate the profile
//
profile := inputs.RootInputs.ProfileFam.Native.Profile
if err := b.profiles.Validate(profile); err != nil {
if err := b.ProfilesCFG.Validate(profile); err != nil {
return err
}

// validate the scheme
//
if err := b.SamplerCFG.Validate(
inputs.ParamSet.Native.Scheme,
&b.ProfilesCFG,
); err != nil {
return err
}

// Apply fallbacks, ie user didn't specify flag on command line
// so fallback to one defined in config. This is supposed to
// work transparently with Viper, but this doesn't work with
// custom locations; ie no-files is defined under sampler, but
// viper would expect to see it at the root. Even so, still found
// that viper would fail to pick up this value, so implementing
// the fall back manually here.
//
if inputs.RootInputs.ParamSet.Native.IsSampling {
if !flagSet.Changed("no-files") && b.SamplerCFG.NoFiles > 0 {
inputs.RootInputs.ParamSet.Native.NoFiles = b.SamplerCFG.NoFiles
}
}

appErr = proxy.EnterShrink(
inputs,
b.optionsInfo.Program,
b.optionsInfo.Config.Viper,
&b.ProfilesCFG,
&b.SamplerCFG,
)
} else {
return xvErr
Expand Down Expand Up @@ -196,13 +223,11 @@ func (b *Bootstrap) buildShrinkCommand(container *assistant.CobraContainer) *cob

// -- scheme(S)
//

const (
defaultScheme = ""
)

samplers := b.optionsInfo.Config.Viper.Get("samplers")
_ = samplers
sampler := b.optionsInfo.Config.Viper.Get("sampler")

// can we validate that it is present in the config?
paramSet.BindValidatedString(
Expand All @@ -212,9 +237,9 @@ func (b *Bootstrap) buildShrinkCommand(container *assistant.CobraContainer) *cob
),
&paramSet.Native.Scheme,
func(s string, f *pflag.Flag) error {
return lo.TernaryF(samplers != nil,
return lo.TernaryF(sampler != nil,
func() error { return nil },
func() error { return fmt.Errorf("samplers not found (%v)", s) },
func() error { return fmt.Errorf("sampler not found (%v)", s) },
)
},
)
Expand Down Expand Up @@ -334,7 +359,9 @@ func (b *Bootstrap) buildShrinkCommand(container *assistant.CobraContainer) *cob
"quality": "q",
}

// 📌A note about cobra args validation: cmd.ValidArgs lets you define
b.viper()

// 📌 A note about cobra args validation: cmd.ValidArgs lets you define
// a list of all allowable tokens for positional args. Just define
// ValidArgs, eg:
// shrinkCommand.ValidArgs = []string{"foo", "bar", "baz"}
Expand Down
55 changes: 45 additions & 10 deletions src/app/proxy/enter-shrink.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,14 +10,12 @@ import (
"github.com/samber/lo"
"github.com/snivilised/cobrass"
"github.com/snivilised/cobrass/src/assistant/configuration"
"github.com/snivilised/cobrass/src/clif"
"github.com/snivilised/extendio/xfs/nav"
)

type ShrinkEntry struct {
EntryBase
Inputs *ShrinkCommandInputs
jobs []string
}

func FilenameWithoutExtension(name string) string {
Expand Down Expand Up @@ -51,6 +49,30 @@ func (e *ShrinkEntry) LookAheadOptionsFn(o *nav.TraverseOptions) {
return nil
},
}

switch {
case e.Inputs.FilesFam.Native.FilesGlob != "":
pattern := e.Inputs.FilesFam.Native.FilesGlob
o.Store.FilterDefs = &nav.FilterDefinitions{
Node: nav.FilterDef{
Type: nav.FilterTypeGlobEn,
Description: fmt.Sprintf("--files-gb(G): '%v'", pattern),
Pattern: pattern,
Scope: nav.ScopeFileEn,
},
}

case e.Inputs.FilesFam.Native.FilesRexEx != "":
pattern := e.Inputs.FilesFam.Native.FilesRexEx
o.Store.FilterDefs = &nav.FilterDefinitions{
Node: nav.FilterDef{
Type: nav.FilterTypeRegexEn,
Description: fmt.Sprintf("--files-rx(X): '%v'", pattern),
Pattern: pattern,
Scope: nav.ScopeFileEn,
},
}
}
}

func (e *ShrinkEntry) PrincipalOptionsFn(o *nav.TraverseOptions) {
Expand All @@ -73,7 +95,7 @@ func (e *ShrinkEntry) PrincipalOptionsFn(o *nav.TraverseOptions) {
runner := e.Registry.Get()
defer e.Registry.Put(runner)

return runner.OnNewItem(item, clif.Expand(positional, e.ThirdPartyCL)...)
return runner.OnNewShrinkItem(item, positional, e.ThirdPartyCL)
},
}
}
Expand All @@ -90,6 +112,17 @@ func (e *ShrinkEntry) ConfigureOptions(o *nav.TraverseOptions) {
o.Store.Subscription = nav.SubscribeFiles

e.EntryBase.ConfigureOptions(o)

if e.Registry == nil {
e.Registry = NewRunnerRegistry(&SharedRunnerInfo{
Type: RunnerTypeSamplerEn, // TODO: to come from an arg !!!
Options: e.Options,
program: e.Program,
profilesCFG: e.ProfilesCFG,
samplerCFG: e.SamplerCFG,
Inputs: e.Inputs,
})
}
}

func clearResumeFromWith(with nav.CreateNewRunnerWith) nav.CreateNewRunnerWith {
Expand Down Expand Up @@ -139,12 +172,10 @@ func (e *ShrinkEntry) resumeFn(item *nav.TraverseItem) error {
runner := e.Registry.Get()
defer e.Registry.Put(runner)

return runner.OnNewItem(item, clif.Expand(positional, e.ThirdPartyCL)...)
return runner.OnNewShrinkItem(item, positional, e.ThirdPartyCL)
}

func (e *ShrinkEntry) run(config configuration.ViperConfig) error {
_ = config

func (e *ShrinkEntry) run(_ configuration.ViperConfig) error {
e.ThirdPartyCL = cobrass.Evaluate(
e.Inputs.ParamSet.Native.ThirdPartySet.Present,
e.Inputs.ParamSet.Native.ThirdPartySet.KnownBy,
Expand Down Expand Up @@ -182,14 +213,18 @@ func EnterShrink(
inputs *ShrinkCommandInputs,
program Executor,
config configuration.ViperConfig,
profilesCFG *ProfilesConfig,
samplerCFG *SamplerConfig,
) error {
fmt.Printf("---> 🔊🔊 Directory: '%v'\n", inputs.RootInputs.ParamSet.Native.Directory)

entry := &ShrinkEntry{
EntryBase: EntryBase{
Inputs: inputs.RootInputs,
Program: program,
Config: config,
Inputs: inputs.RootInputs,
Program: program,
Config: config,
ProfilesCFG: profilesCFG,
SamplerCFG: samplerCFG,
},
Inputs: inputs,
}
Expand Down
Loading

0 comments on commit 010f64e

Please sign in to comment.