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 6, 2023
1 parent b16ee29 commit 6854ea4
Show file tree
Hide file tree
Showing 12 changed files with 440 additions and 106 deletions.
25 changes: 22 additions & 3 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
profiles proxy.ProfilesConfig
sampler proxy.SamplerConfig
}

type ConfigureOptionsInfo struct {
Expand Down Expand Up @@ -123,7 +125,7 @@ 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
Expand Down Expand Up @@ -209,3 +211,20 @@ func handleLangSetting(config configuration.ViperConfig) {
os.Exit(1)
}
}

func (b *Bootstrap) viper() {

Check failure on line 215 in src/app/command/bootstrap.go

View workflow job for this annotation

GitHub Actions / lint

block should not start with a whitespace (wsl)
// 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.
//

nf := b.optionsInfo.Config.Viper.Get("no-files")
_ = nf

b.profiles = b.optionsInfo.Config.Viper.GetStringMapStringSlice("profiles")
err := b.optionsInfo.Config.Viper.UnmarshalKey("sampler", &b.sampler)

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
45 changes: 35 additions & 10 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,16 +115,16 @@ 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
//
Expand All @@ -131,6 +133,29 @@ func (b *Bootstrap) buildShrinkCommand(container *assistant.CobraContainer) *cob
return err
}

// validate the scheme
//
if err := b.sampler.Validate(
inputs.ParamSet.Native.Scheme,
&b.profiles,
); 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 does 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 still fail to pick up this value, so implementing
// the fall back manually here.
//
if inputs.RootInputs.ParamSet.Native.IsSampling {
if !flagSet.Changed("no-files") {
inputs.RootInputs.ParamSet.Native.NoFiles = b.sampler.Files
}
}

appErr = proxy.EnterShrink(
inputs,
b.optionsInfo.Program,
Expand Down Expand Up @@ -196,13 +221,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 +235,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 +357,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
31 changes: 28 additions & 3 deletions src/app/proxy/enter-shrink.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ import (
type ShrinkEntry struct {
EntryBase
Inputs *ShrinkCommandInputs
jobs []string
}

func FilenameWithoutExtension(name string) string {
Expand Down Expand Up @@ -51,6 +50,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 Down Expand Up @@ -142,8 +165,10 @@ func (e *ShrinkEntry) resumeFn(item *nav.TraverseItem) error {
return runner.OnNewItem(item, clif.Expand(positional, e.ThirdPartyCL)...)
}

func (e *ShrinkEntry) run(config configuration.ViperConfig) error {
_ = config
func (e *ShrinkEntry) run(_ configuration.ViperConfig) error {
if err := e.viper(); err != nil {
return err
}

e.ThirdPartyCL = cobrass.Evaluate(
e.Inputs.ParamSet.Native.ThirdPartySet.Present,
Expand Down
Loading

0 comments on commit 6854ea4

Please sign in to comment.