Skip to content
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 an attr.Convert helper. #120

Merged
merged 4 commits into from
Sep 14, 2021
Merged

Add an attr.Convert helper. #120

merged 4 commits into from
Sep 14, 2021

Commits on Sep 14, 2021

  1. Add an attr.Convert helper.

    This function converts an `attr.Value` to use a new `attr.Type`, so long
    as they share a compatible `tftypes.Type` representation. This allows
    code that doesn't know the type of an `attr.Value` to still use it,
    provided they know the kind of data it holds.
    
    For example, a validation helper that works on strings--MaxStringLength,
    say--could look something like this:
    
    ```
    // assume req.Config is an attr.Value
    strAttr, err := attr.Convert(ctx, req.Config, types.StringType)
    if err != nil {
      panic(err)
    }
    var str types.String
    diags := tfsdk.ValueAs(ctx, strAttr, &str)
    if diags.HasError() {
      panic("oops")
    }
    // do something with `str`, which is now strongly typed
    ```
    
    Then no matter what `attr.Type` provider devs use in their schema, this
    validator would still work, then. Without the conversion step, it
    wouldn't work, as `tfsdk.ValueAs` implementation needs to know the
    `attr.Type` of the `attr.Value`, and reusable validators _can't_ know
    that. So the point of this helper is to get an `attr.Value` into a known
    `attr.Type` format.
    paddycarver committed Sep 14, 2021
    Configuration menu
    Copy the full SHA
    a07447c View commit details
    Browse the repository at this point in the history
  2. Add tests, move to tfsdk.

    Import cycle in tests if we don't.
    paddycarver committed Sep 14, 2021
    Configuration menu
    Copy the full SHA
    3a5e64f View commit details
    Browse the repository at this point in the history
  3. Fix up tests, add String to attr.Type.

    Being able to return good error messages depends on human-friendly
    representations of types existing.
    paddycarver committed Sep 14, 2021
    Configuration menu
    Copy the full SHA
    887bf00 View commit details
    Browse the repository at this point in the history
  4. Add changelog entry.

    paddycarver committed Sep 14, 2021
    Configuration menu
    Copy the full SHA
    f623439 View commit details
    Browse the repository at this point in the history