Add extra Options to Make

This commit is contained in:
Dan Jones 2025-03-14 21:46:30 -05:00
commit db2f12522d
3 changed files with 42 additions and 4 deletions

14
make.go
View file

@ -5,12 +5,21 @@ import "fmt"
// Make generates a random filename. The behavior can be controlled by specifying Options
// In general, the final filename will be [prefix]_[generated_string]_[original_filename]_[suffix].[extension].
// If the name generator returns an error (generally, it shouldn't), that will be returned instead.
func Make(conf Config) (string, error) {
func Make(conf Config, opts ...Option) (string, error) {
for _, opt := range opts {
opt(&conf)
}
name, err := conf.generator(&conf)
if err != nil {
return "", err
}
seperateConf(&conf)
return fmt.Sprintf("%s%s%s%s%s", conf.prefix, name, conf.original, conf.suffix, conf.extension), nil
}
func seperateConf(conf *Config) {
if conf.prefix != "" {
conf.prefix += conf.separator
}
@ -19,8 +28,5 @@ func Make(conf Config) (string, error) {
}
if conf.suffix != "" {
conf.suffix = conf.separator + conf.suffix
}
return fmt.Sprintf("%s%s%s%s%s", conf.prefix, name, conf.original, conf.suffix, conf.extension), nil
}

View file

@ -11,3 +11,20 @@ func ExampleMake_basic() {
out, _ := nomino.Make(nomino.NewConfig())
fmt.Println(out)
}
func ExampleMake_withExtraOptions() {
gen := nomino.Incremental()
conf := nomino.NewConfig(
nomino.WithGenerator(gen),
nomino.WithPrefix("pre"),
)
st, _ := nomino.Make(conf, nomino.WithOriginal("foobar"))
fmt.Println(st)
st, _ = nomino.Make(conf, nomino.WithOriginal("baz"))
fmt.Println(st)
// Output:
// pre_0_foobar.txt
// pre_1_baz.txt
}

View file

@ -66,3 +66,18 @@ func TestMakeDoesntChangeConf(t *testing.T) {
assert.Equal(t, "foo.txt", st)
assert.NoError(t, err)
}
func TestMakeOptsDoesntChangeConf(t *testing.T) {
gen := Incremental()
conf := NewConfig(WithGenerator(gen), WithPrefix("pre"))
st, err := Make(conf, WithOriginal("foobar"))
assert.Equal(t, "", conf.original)
assert.Equal(t, "pre_0_foobar.txt", st)
assert.NoError(t, err)
st, err = Make(conf, WithOriginal("baz"))
assert.Equal(t, "", conf.original)
assert.Equal(t, "pre_1_baz.txt", st)
assert.NoError(t, err)
}