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

Commit

Permalink
fix(transform): fix nil returned by TransformString for ComposeTranfo…
Browse files Browse the repository at this point in the history
…rmers (#330)

TranformString should not return nil on zero value, otherwise nil will be passed to next Tranformer if there are more than 1 Transformer in ComposeTransformers.

return zero value of string instead coz String Tranformer is guaranteed to return string
  • Loading branch information
Roytangrb authored Jan 21, 2021
1 parent e64d9b6 commit a21fb70
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 4 deletions.
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)
}
}

0 comments on commit a21fb70

Please sign in to comment.