-
Notifications
You must be signed in to change notification settings - Fork 304
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
Add support for func
-types to fx.As()
#1249
base: master
Are you sure you want to change the base?
Conversation
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.
Thanks for the PR! I have a couple comments on the implementation.
At a high level, I can't think of any particular reason why this shouldn't be allowed, but can you maybe provide some insight into why this is desired over, say, just providing a struct with a call-able method defined on it and using fx.As(new(someInterface))
? Is it just cleaner in some scenarios?
annotated.go
Outdated
if !((at.types[i].typ.Kind() == reflect.Interface && t.Implements(at.types[i].typ)) || | ||
t.ConvertibleTo(at.types[i].typ)) { | ||
return nil, | ||
nil, | ||
fmt.Errorf("invalid fx.As: %v does not implement or is not convertible to %v", t, at.types[i]) |
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.
Should we make these two separate checks? This will keep the code cleaner and give better error messages.
if at.types[i].typ.Kind() == reflect.Interface {
if !t.Implements(at.types[i].typ) {
return nil, nil, fmt.Errorf("invalid fx.As: %v does not implement %v", t, at.types[i])
}
} else if !t.ConvertibleTo(at.types[i].typ) {
return nil, nil, fmt.Errorf("invalid fx.As: %v cannot be converted to %v", t, at.types[i])
}
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.
Thx, I split this condition
annotated.go
Outdated
if newOutResult.Field(i).Kind() == reflect.Func { | ||
newOutResult.Field(i).Set(getResult(i, results).Convert(newOutResult.Field(i).Type())) | ||
} else { | ||
newOutResult.Field(i).Set(getResult(i, results)) | ||
} |
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.
nit: should we flip these conditions to make the control flow more/appear consistent with the check above?
if newOutResult.Field(i).Kind() == reflect.Interface {
newOutResult.Field(i).Set(getResult(i, results))
} else {
newOutResult.Field(i).Set(getResult(i, results).Convert(newOutResult.Field(i).Type()))
}
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.
fixed
@@ -1300,7 +1317,11 @@ func (at *asAnnotation) results(ann *annotated) ( | |||
|
|||
newOutResult := reflect.New(resType).Elem() | |||
for i := 1; i < resType.NumField(); i++ { |
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.
Is there any reason we would need to check Value.CanConvert
first since technically Value.Convert
can panic even if Type.ConvertibleTo
returns true? I can't think of any reason why a func value wouldn't be convertible if its type is though.
annotated_test.go
Outdated
@@ -477,6 +480,32 @@ func TestAnnotatedAs(t *testing.T) { | |||
assert.Equal(t, s.String(), "another stringer") | |||
}, | |||
}, | |||
{ | |||
desc: "value type convertible to target type", |
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.
nit: consider downscoping the names of these cases since convertible types are locked down to just functions right now
desc: "value type convertible to target type", | |
desc: "function value convertible to target type", |
annotated_test.go
Outdated
}, | ||
}, | ||
{ | ||
desc: "anonymous value type convertible to target type", |
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.
should we add a test case for a function vaoue that is not convertible to the target type?
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.
Thx, I added new test case.
annotated.go
Outdated
@@ -1145,6 +1146,19 @@ var _ Annotation = (*asAnnotation)(nil) | |||
// constructor does NOT provide both bytes.Buffer and io.Writer type; it just | |||
// provides io.Writer type. | |||
// | |||
// Example for function-types: |
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.
Let's update line 1129 as well:
- // constructor) to be provided as another interface.
+ // constructor) to be provided as another type.
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.
Thx, appropriate changes have been made.
WalkthroughThe changes enhance the Changes
Sequence Diagram(s)sequenceDiagram
participant Caller as fx.Provide
participant Annotation as As Annotation
participant Checker as Type Checker
participant Results as Result Handler
Caller->>Annotation: Call with function/value
Annotation->>Checker: Check if value is pointer/interface or convertible
Checker-->>Annotation: Return conversion status or error
Annotation->>Results: Update return values accordingly
Results-->>Caller: Provide converted result / error message
Poem
Tip ⚡💬 Agentic Chat (Pro Plan, General Availability)
✨ Finishing Touches
🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
gRPC-server implementation:
list handler:
I need to do this to register the handler:
What would I like to do:
|
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.
Actionable comments posted: 0
🧹 Nitpick comments (1)
annotated_test.go (1)
1875-1877
: Minor formatting issueThere's a formatting issue in the test file. The indentation for this interface doesn't match the Go standard formatting.
func assertApp( t *testing.T, app interface { - Start(context.Context) error - Stop(context.Context) error - }, + Start(context.Context) error + Stop(context.Context) error + }, started *bool, stopped *bool, invoked *bool, ) {🧰 Tools
🪛 golangci-lint (1.64.8)
1875-1875: File is not properly formatted
(gofumpt)
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
annotated.go
(6 hunks)annotated_test.go
(7 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
annotated_test.go (2)
provide.go (1)
Provide
(64-69)annotated.go (2)
Annotate
(1933-1945)As
(1282-1284)
🪛 golangci-lint (1.64.8)
annotated.go
1241-1241: File is not properly formatted
(gofumpt)
1255-1255: File is not properly formatted
(gofumpt)
annotated_test.go
1875-1875: File is not properly formatted
(gofumpt)
🔇 Additional comments (10)
annotated.go (4)
1217-1258
: Well-documented enhancement to support convertible typesThe documentation has been properly updated to include examples for function values and custom convertible types. This clearly explains the new capability of the
As
annotation to handle not just interfaces but also convertible types, making the API more flexible.🧰 Tools
🪛 golangci-lint (1.64.8)
1241-1241: File is not properly formatted
(gofumpt)
1255-1255: File is not properly formatted
(gofumpt)
1325-1326
: Clear error message improvementUpdated error message to indicate that the argument must be a pointer to an interface or convertible type, which properly explains the expected input format for the enhanced functionality.
1379-1385
: Good separation of error checking logicYou've split the condition to separately check for interface implementation and type conversion, which provides more specific error messages. This makes debugging easier for consumers of the API.
1418-1423
: Implemented proper conversion handlingThe implementation correctly handles both interface assignment and type conversion based on the kind of the target type. The additional check for
CanConvert
before attempting conversion is a good defensive programming practice to avoid potential panics.annotated_test.go (6)
447-450
: Good addition of test typesThese new type definitions are well-structured for testing the enhanced functionality of the
fx.As()
annotation with convertible types. The function types (myProvideFunc
andmyInvokeFunc
) along with the string type will allow comprehensive testing of the conversion capabilities.
486-497
: Comprehensive test for function type conversionThis test case properly validates that a function type can be converted to another compatible function type through the
fx.As()
annotation. This confirms the core enhancement being made in this PR.
499-521
: Good coverage with additional conversion testsThese test cases cover both anonymous function values and primitive type conversions, providing good test coverage for the convertible types enhancement. The anonymous function test is particularly valuable since it represents a common use case.
887-890
: Useful negative test typesThe addition of
myIntType
provides a foundation for testing invalid type conversions, which helps ensure proper error handling in the implementation.
904-914
: Strong negative testingThese test cases verify that appropriate errors are generated when incompatible types are provided to
fx.As()
. This is essential for ensuring a robust implementation that fails gracefully when misused.
959-959
: Updated error message for clarityThe error message now properly describes that the argument must be a pointer to an interface or convertible type, making it consistent with the implementation changes.
Summary by CodeRabbit
New Features
Tests