-
Notifications
You must be signed in to change notification settings - Fork 49
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[RFC] many: add types.Option
generic and use in customizations
#860
Draft
mvo5
wants to merge
5
commits into
osbuild:main
Choose a base branch
from
mvo5:go-optional-less-ptr-internal
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
fc3af96
internal: add new `types.Option` generic for primitive types
mvo5 932e095
blueprint: use new `internal/types` to avoid pointers for unset
mvo5 dd3212c
many: move Blueprint.TLSVerify to types.Optional[bool]
mvo5 74823a6
customizations: move Timezone to Option[string]
mvo5 07741d4
blueprint: convert UserCustomization to types.Option
mvo5 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
Copyright 2021 Taiki Kawakami (a.k.a. moznion) https://moznion.net | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,117 @@ | ||
package types | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"fmt" | ||
) | ||
|
||
// Option is a more constrained subset of the code in | ||
// https://github.com/moznion/go-optional | ||
// | ||
// It is not using an external go-optional lib directly because none | ||
// has toml unmarshal support and also because there is no support for | ||
// complex types in UnmarshalTOML (it only gives a single | ||
// reflect.Value of type any) so our optional "lib" must come with | ||
// limitations for this. | ||
// | ||
// Unfortunately there is no way I could find to import the code and | ||
// limit the supported types. So this is a copy of the subset. | ||
// Fortunatly the code is small, targeted and easy to follow so it | ||
// should not be too bad. | ||
|
||
type OptionTomlTypes interface { | ||
~int | ~bool | ~string | ||
} | ||
|
||
// Option is a subset of github.com/moznion/go-optional for use with toml | ||
|
||
// Option is a data type that must be Some (i.e. having a value) or None (i.e. doesn't have a value). | ||
// This type implements database/sql/driver.Valuer and database/sql.Scanner. | ||
type Option[T OptionTomlTypes] []T | ||
|
||
const ( | ||
value = iota | ||
) | ||
|
||
// Some is a function to make an Option type value with the actual value. | ||
func Some[T OptionTomlTypes](v T) Option[T] { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Fwiw, we could call this differently, e.g. |
||
return Option[T]{ | ||
value: v, | ||
} | ||
} | ||
|
||
// None is a function to make an Option type value that doesn't have a value. | ||
func None[T OptionTomlTypes]() Option[T] { | ||
return nil | ||
} | ||
|
||
// IsNone returns True if the Option *doesn't* have a value | ||
func (o Option[T]) IsNone() bool { | ||
return o == nil | ||
} | ||
|
||
// IsSome returns whether the Option has a value or not. | ||
func (o Option[T]) IsSome() bool { | ||
return o != nil | ||
} | ||
|
||
// Unwrap returns the value regardless of Some/None status. | ||
// If the Option value is Some, this method returns the actual value. | ||
// On the other hand, if the Option value is None, this method returns the *default* value according to the type. | ||
func (o Option[T]) Unwrap() T { | ||
if o.IsNone() { | ||
var defaultValue T | ||
return defaultValue | ||
} | ||
return o[value] | ||
} | ||
|
||
// TakeOr returns the actual value if the Option has a value. | ||
// On the other hand, this returns fallbackValue. | ||
func (o Option[T]) TakeOr(fallbackValue T) T { | ||
if o.IsNone() { | ||
return fallbackValue | ||
} | ||
return o[value] | ||
} | ||
|
||
var jsonNull = []byte("null") | ||
|
||
func (o Option[T]) MarshalJSON() ([]byte, error) { | ||
if o.IsNone() { | ||
return jsonNull, nil | ||
} | ||
|
||
marshal, err := json.Marshal(o.Unwrap()) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return marshal, nil | ||
} | ||
|
||
func (o *Option[T]) UnmarshalJSON(data []byte) error { | ||
if len(data) <= 0 || bytes.Equal(data, jsonNull) { | ||
*o = None[T]() | ||
return nil | ||
} | ||
|
||
var v T | ||
err := json.Unmarshal(data, &v) | ||
if err != nil { | ||
return err | ||
} | ||
*o = Some(v) | ||
|
||
return nil | ||
} | ||
|
||
// not part of github.com/moznion/go-optional | ||
func (o *Option[T]) UnmarshalTOML(data any) error { | ||
b, ok := data.(T) | ||
if !ok { | ||
return fmt.Errorf("cannot use %[1]v (%[1]T) as bool", data) | ||
} | ||
*o = Some(b) | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,80 @@ | ||
package types_test | ||
|
||
import ( | ||
"testing" | ||
|
||
"github.com/BurntSushi/toml" | ||
"github.com/stretchr/testify/assert" | ||
|
||
"github.com/osbuild/images/internal/types" | ||
) | ||
|
||
type s1 struct { | ||
Name string `toml:"name"` | ||
Sub s2 `toml:"sub"` | ||
} | ||
|
||
type s2 struct { | ||
ValBool types.Option[bool] `toml:"val-bool"` | ||
ValString types.Option[string] `toml:"val-string"` | ||
ValString2 types.Option[string] `toml:"val-string2"` | ||
} | ||
|
||
func TestTomlParseOption(t *testing.T) { | ||
testTomlStr := ` | ||
name = "some-name" | ||
[sub] | ||
val-bool = true | ||
val-string = "opt-string" | ||
` | ||
|
||
var bp s1 | ||
err := toml.Unmarshal([]byte(testTomlStr), &bp) | ||
assert.NoError(t, err) | ||
assert.Equal(t, bp.Name, "some-name") | ||
assert.Equal(t, types.Some(true), bp.Sub.ValBool) | ||
assert.Equal(t, types.Some("opt-string"), bp.Sub.ValString) | ||
assert.EqualValues(t, types.None[string](), bp.Sub.ValString2) | ||
} | ||
|
||
func TestTomlParseOptionBad(t *testing.T) { | ||
testTomlStr := ` | ||
[sub] | ||
val-bool = 1234 | ||
` | ||
|
||
var bp s1 | ||
err := toml.Unmarshal([]byte(testTomlStr), &bp) | ||
assert.ErrorContains(t, err, "cannot use 1234 (int64) as bool") | ||
} | ||
|
||
// taken from https://github.com/moznion/go-optional | ||
func TestOption_IsNone(t *testing.T) { | ||
assert.True(t, types.None[int]().IsNone()) | ||
assert.False(t, types.Some[int](123).IsNone()) | ||
|
||
var nilValue types.Option[int] = nil | ||
assert.True(t, nilValue.IsNone()) | ||
} | ||
|
||
func TestOption_IsSome(t *testing.T) { | ||
assert.False(t, types.None[int]().IsSome()) | ||
assert.True(t, types.Some[int](123).IsSome()) | ||
|
||
var nilValue types.Option[int] = nil | ||
assert.False(t, nilValue.IsSome()) | ||
} | ||
|
||
func TestOption_Unwrap(t *testing.T) { | ||
assert.Equal(t, "foo", types.Some[string]("foo").Unwrap()) | ||
assert.Equal(t, "", types.None[string]().Unwrap()) | ||
assert.Equal(t, false, types.None[bool]().Unwrap()) | ||
} | ||
|
||
func TestOption_TakeOr(t *testing.T) { | ||
v := types.Some[int](123).TakeOr(666) | ||
assert.Equal(t, 123, v) | ||
|
||
v = types.None[int]().TakeOr(666) | ||
assert.Equal(t, 666, v) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Fwiw, we could call this
Optional
too which I actually slightly prefer but thenOption
is what rust uses and lots of people are familar with this terminology now.