feat: FlagSet: add MustSetAnnotation method #458
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.
The SetAnnotation method returns an error if the given flag does not exist. While handling the error should normally be the recommendation, in many cases the list of flags is static, and adding error handling for each annotation can either introduce unwanted boilerplating, or may not be possible in cases where there's no error return.
Unfortunately, also makes this method prone to copy/paste mistakes where either the flag doesn't exist, or an annotation is already set, potentially overwriting another flag's annotation (which is a bug I recently discovered in one of our projects (see 1)). Such bugs can be hard to discover if they have no immediate impact.
This patch introduces a
MustSetAnnotationthat can be used as a replacement forSetAnnotation. UnlikeSetAnnotation, it produces a panic instead of returning an error, and uses stricter validation; not allowing an annotation to be set if the flag already has the annotation set.