Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

fix(transform): fix nil returned by TransformString #330

Merged
merged 1 commit into from
Jan 21, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 7 additions & 4 deletions transform.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,18 +18,21 @@ func TransformString(f func(s string) string) Transformer {
return func(ans interface{}) interface{} {
// if the answer value passed in is the zero value of the appropriate type
if isZero(reflect.ValueOf(ans)) {
// skip this `Transformer` by returning a nil value.
// skip this `Transformer` by returning a zero value of string.
// The original answer will be not affected,
// see survey.go#L125.
return nil
// A zero value of string should be returned to be handled by
// next Transformer in a composed Tranformer,
// see tranform.go#L75
return ""
}

// "ans" is never nil here, so we don't have to check that
// see survey.go#L97 for more.
// see survey.go#L338 for more.
// Make sure that the the answer's value was a typeof string.
s, ok := ans.(string)
if !ok {
return nil
return ""
}

return f(s)
Expand Down
6 changes: 6 additions & 0 deletions transform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,10 @@ func TestComposeTransformers(t *testing.T) {
// the result should be lowercase.
t.Errorf("TestComposeTransformers transformer failed to transform the answer to title->lowercase, expected '%s' but got '%s'.", expected, got)
}

var emptyAns string
if expected, got := "", transformer(emptyAns); expected != got {
// TransformString transformers should be skipped and return zero value string
t.Errorf("TestComposeTransformers transformer failed to skip transforming on optional empty input, expected '%s' but got '%s'.", expected, got)
}
}