From 4709024e7f1cfaf4167862bb475809ac88486163 Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Thu, 12 Mar 2020 12:03:51 -0400 Subject: [PATCH 1/7] Adds acceptance test runs triggered by labels --- .github/workflows/acceptance-tests.yml | 53 ++++++++++++++++++++++++++ 1 file changed, 53 insertions(+) create mode 100644 .github/workflows/acceptance-tests.yml diff --git a/.github/workflows/acceptance-tests.yml b/.github/workflows/acceptance-tests.yml new file mode 100644 index 0000000000..c955600df6 --- /dev/null +++ b/.github/workflows/acceptance-tests.yml @@ -0,0 +1,53 @@ +name: Acceptance Tests + +on: + pull_request: + types: [labeled] + +jobs: + acceptance-tests: + runs-on: ubuntu-latest + steps: + + - name: Parse Context From Environment + run: | + echo ::set-env name=HEAD_SHA::$( + jq -rc '.pull_request.head.sha' $GITHUB_EVENT_PATH + ) + echo ::set-env name=LABEL_NAME::$( + jq -rc .label.name $GITHUB_EVENT_PATH + ) + + - name: Parse Arguments From Label Name + run: | + echo ::set-env name=RUN_FILTER::$( + echo $LABEL_NAME | cut -d/ -f 2 + ) + + - name: Match Expected Label Prefix + run: echo ${LABEL_NAME} | egrep -q "^acceptance-test/" + + - name: Checkout + uses: actions/checkout@v2.0.0 + with: + ref: ${{ env.HEAD_SHA }} + + - name: Generate Test Fixtures + run: | + openssl req -x509 -newkey rsa:4096 -days 1 -nodes \ + -subj "/C=US/ST=CA/L=San Francisco/O=HashiCorp, Inc./CN=localhost" \ + -keyout github/test-fixtures/key.pem -out github/test-fixtures/cert.pem + + - name: Acceptance Tests + uses: terraformtesting/acceptance-tests@v1.2.0 + with: + RUN_FILTER: ${{ env.RUN_FILTER }} + GITHUB_ORGANIZATION: terraformtesting + GITHUB_TEST_USER: github-terraform-test-user + GITHUB_TEST_USER_NAME: "Test User" + GITHUB_TEST_USER_EMAIL: 60107403+github-terraform-test-user@users.noreply.github.com + GITHUB_TEST_USER_TOKEN: ${{ secrets.GITHUB_TEST_USER_TOKEN }} + GITHUB_TEST_COLLABORATOR: github-terraform-test-collaborator + GITHUB_TEST_COLLABORATOR_TOKEN: ${{ secrets.GITHUB_TEST_COLLABORATOR_TOKEN }} + GITHUB_TEMPLATE_REPOSITORY: terraform-template-module + GITHUB_TEMPLATE_REPOSITORY_RELEASE_ID: 23826477 From c82a23a1846123b27a4d70bcd41e4d691634df48 Mon Sep 17 00:00:00 2001 From: Ben F Date: Fri, 28 Feb 2020 11:43:00 +0000 Subject: [PATCH 2/7] Updated to go-github v29.0.3 --- github/config.go | 19 +- github/resource_github_team.go | 24 +- github/resource_github_team_repository.go | 15 +- .../resource_github_team_repository_test.go | 7 +- github/resource_github_team_test.go | 5 +- go.mod | 3 +- go.sum | 5 +- .../doublestar}/.gitignore | 10 + .../github.com/bmatcuk/doublestar/.travis.yml | 15 + vendor/github.com/bmatcuk/doublestar/LICENSE | 22 + .../github.com/bmatcuk/doublestar/README.md | 109 ++++ .../bmatcuk/doublestar/doublestar.go | 476 ++++++++++++++++++ vendor/github.com/bmatcuk/doublestar/go.mod | 3 + .../google/go-github/v29/github/actions.go | 12 + .../go-github/v29/github/actions_secrets.go | 132 +++++ .../go-github/v29/github/actions_workflows.go | 88 ++++ .../go-github/v29/github/activity_events.go | 32 +- .../v29/github/activity_notifications.go | 8 +- .../go-github/v29/github/activity_star.go | 8 +- .../go-github/v29/github/activity_watching.go | 8 +- .../go-github/v29/github/admin_users.go | 4 +- .../google/go-github/v29/github/apps.go | 12 +- .../go-github/v29/github/apps_installation.go | 22 +- .../go-github/v29/github/apps_marketplace.go | 16 +- .../go-github/v29/github/authorizations.go | 8 +- .../google/go-github/v29/github/checks.go | 32 +- .../go-github/v29/github/event_types.go | 6 + .../google/go-github/v29/github/gists.go | 20 +- .../go-github/v29/github/gists_comments.go | 4 +- .../google/go-github/v29/github/git_refs.go | 8 +- .../go-github/v29/github/github-accessors.go | 120 +++++ .../google/go-github/v29/github/github.go | 52 +- .../google/go-github/v29/github/issues.go | 22 +- .../go-github/v29/github/issues_assignees.go | 4 +- .../go-github/v29/github/issues_comments.go | 4 +- .../go-github/v29/github/issues_events.go | 8 +- .../go-github/v29/github/issues_labels.go | 12 +- .../go-github/v29/github/issues_milestones.go | 4 +- .../go-github/v29/github/issues_timeline.go | 4 +- .../google/go-github/v29/github/migrations.go | 8 +- .../v29/github/migrations_source_import.go | 24 - .../go-github/v29/github/migrations_user.go | 8 +- .../google/go-github/v29/github/misc.go | 12 +- .../google/go-github/v29/github/orgs.go | 12 +- .../google/go-github/v29/github/orgs_hooks.go | 4 +- .../go-github/v29/github/orgs_members.go | 22 +- .../v29/github/orgs_outside_collaborators.go | 4 +- .../go-github/v29/github/orgs_projects.go | 8 +- .../v29/github/orgs_users_blocking.go | 4 +- .../google/go-github/v29/github/projects.go | 44 +- .../google/go-github/v29/github/pulls.go | 22 +- .../go-github/v29/github/pulls_comments.go | 4 +- .../go-github/v29/github/pulls_reviewers.go | 4 +- .../go-github/v29/github/pulls_reviews.go | 11 +- .../google/go-github/v29/github/reactions.go | 24 +- .../google/go-github/v29/github/repos.go | 181 ++++--- .../v29/github/repos_collaborators.go | 8 +- .../go-github/v29/github/repos_comments.go | 8 +- .../go-github/v29/github/repos_commits.go | 10 +- .../go-github/v29/github/repos_contents.go | 34 +- .../go-github/v29/github/repos_deployments.go | 8 +- .../go-github/v29/github/repos_forks.go | 8 +- .../go-github/v29/github/repos_hooks.go | 4 +- .../go-github/v29/github/repos_invitations.go | 4 +- .../google/go-github/v29/github/repos_keys.go | 4 +- .../go-github/v29/github/repos_pages.go | 19 +- .../v29/github/repos_prereceive_hooks.go | 4 +- .../go-github/v29/github/repos_projects.go | 8 +- .../go-github/v29/github/repos_releases.go | 45 +- .../go-github/v29/github/repos_statuses.go | 8 +- .../go-github/v29/github/repos_traffic.go | 8 +- .../google/go-github/v29/github/search.go | 34 +- .../google/go-github/v29/github/teams.go | 354 ++++++++++--- .../go-github/v29/github/teams_members.go | 12 +- .../google/go-github/v29/github/users.go | 12 +- .../v29/github/users_administration.go | 4 +- .../go-github/v29/github/users_blocking.go | 4 +- .../go-github/v29/github/users_emails.go | 4 +- .../go-github/v29/github/users_followers.go | 8 +- .../go-github/v29/github/users_gpg_keys.go | 4 +- .../google/go-github/v29/github/users_keys.go | 4 +- .../go-github/v29/github/users_projects.go | 8 +- .../hashicorp/go-getter/.travis.yml | 24 - .../github.com/hashicorp/go-getter/README.md | 8 +- .../github.com/hashicorp/go-getter/client.go | 2 +- .../github.com/hashicorp/go-getter/get_git.go | 28 +- .../hashicorp/go-getter/get_http.go | 24 +- .../github.com/hashicorp/hcl/v2/appveyor.yml | 13 + .../hcl/v2/ext/customdecode/README.md | 209 ++++++++ .../hcl/v2/ext/customdecode/customdecode.go | 56 +++ .../v2/ext/customdecode/expression_type.go | 146 ++++++ .../hashicorp/hcl/v2/ext/tryfunc/README.md | 44 ++ .../hashicorp/hcl/v2/ext/tryfunc/tryfunc.go | 150 ++++++ .../hcl/v2/ext/typeexpr/type_type.go | 118 +++++ .../hashicorp/hcl/v2/gohcl/decode.go | 26 +- .../hashicorp/hcl/v2/hclsyntax/parser.go | 11 +- .../hcl/v2/hclwrite/ast_expression.go | 23 + .../hashicorp/hcl/v2/hclwrite/generate.go | 8 +- vendor/github.com/hashicorp/logutils/LICENSE | 354 ------------- .../github.com/hashicorp/logutils/README.md | 36 -- vendor/github.com/hashicorp/logutils/go.mod | 1 - vendor/github.com/hashicorp/logutils/level.go | 81 --- .../terraform-config-inspect/tfconfig/load.go | 4 +- .../tfconfig/load_legacy.go | 10 +- .../tfconfig/module.go | 6 +- .../tfconfig/provider_ref.go | 76 +++ .../helper/logging/logging.go | 31 +- .../helper/resource/testing_import_state.go | 5 +- .../internal/addrs/input_variable.go | 2 +- .../internal/addrs/module_instance.go | 2 +- .../internal/addrs/resource.go | 3 +- .../internal/command/format/diff.go | 66 ++- .../internal/command/format/state.go | 2 +- .../internal/configs/compat_shim.go | 92 +++- .../internal/configs/configload/copy_dir.go | 10 - .../internal/configs/module_merge.go | 5 +- .../internal/configs/named_values.go | 212 +++++++- .../internal/configs/parser_config.go | 35 +- .../internal/configs/parser_config_dir.go | 6 +- .../internal/configs/provisioner.go | 58 ++- .../internal/configs/resource.go | 26 +- .../terraform-plugin-sdk/internal/dag/walk.go | 2 +- .../internal/lang/funcs/collection.go | 9 +- .../internal/lang/funcs/string.go | 90 +++- .../internal/modsdir/manifest.go | 9 + .../internal/providers/addressed_types.go | 4 +- .../internal/states/instance_object.go | 17 +- .../internal/states/instance_object_src.go | 5 +- .../internal/states/module.go | 65 ++- .../internal/states/resource.go | 7 + .../internal/states/state_deepcopy.go | 18 +- .../internal/states/statefile/version4.go | 28 +- .../internal/tfdiags/contextual.go | 4 +- .../internal/version/version.go | 2 +- .../terraform-plugin-sdk/plugin/client.go | 7 +- .../terraform-plugin-sdk/terraform/context.go | 38 +- .../terraform/context_input.go | 96 +--- .../terraform/eval_apply.go | 64 ++- .../terraform/eval_provider.go | 2 +- .../terraform/eval_read_data.go | 31 +- .../terraform/eval_refresh.go | 1 + .../terraform/evaltree_provider.go | 2 +- .../terraform/evaluate.go | 101 ++-- .../terraform/evaluate_valid.go | 2 +- .../terraform/graph_builder_apply.go | 24 +- .../terraform/graph_builder_refresh.go | 1 + .../terraform/module_dependencies.go | 5 +- .../terraform/node_data_refresh.go | 1 - .../terraform/node_provider_eval.go | 2 +- .../terraform/node_resource_apply_instance.go | 45 +- .../terraform/node_resource_destroy.go | 27 + .../node_resource_destroy_deposed.go | 2 +- .../terraform/node_resource_plan_destroy.go | 2 +- .../terraform/node_resource_plan_instance.go | 5 +- .../terraform/node_resource_refresh.go | 18 + .../terraform/node_root_variable.go | 20 + .../terraform/provisioner_mock.go | 1 - .../terraform/transform_attach_schema.go | 4 +- .../terraform/transform_destroy_edge.go | 85 +++- .../terraform/transform_import_state.go | 2 +- .../hashicorp/terraform/addrs/provider.go | 49 ++ .../terraform/configs/experiments.go | 156 ++++++ .../configs/provider_requirements.go | 82 +++ .../hashicorp/terraform/experiments/doc.go | 9 + .../hashicorp/terraform/experiments/errors.go | 26 + .../terraform/experiments/experiment.go | 93 ++++ .../hashicorp/terraform/experiments/set.go | 46 ++ .../terraform/experiments/testing.go | 33 ++ .../terraform/helper/logging/indent.go | 23 + .../terraform/helper/logging/level.go | 159 ++++++ .../terraform/tfdiags/consolidate_warnings.go | 146 ++++++ website/docs/index.html.markdown | 3 + 172 files changed, 4630 insertions(+), 1443 deletions(-) rename vendor/github.com/{hashicorp/logutils => bmatcuk/doublestar}/.gitignore (81%) create mode 100644 vendor/github.com/bmatcuk/doublestar/.travis.yml create mode 100644 vendor/github.com/bmatcuk/doublestar/LICENSE create mode 100644 vendor/github.com/bmatcuk/doublestar/README.md create mode 100644 vendor/github.com/bmatcuk/doublestar/doublestar.go create mode 100644 vendor/github.com/bmatcuk/doublestar/go.mod create mode 100644 vendor/github.com/google/go-github/v29/github/actions.go create mode 100644 vendor/github.com/google/go-github/v29/github/actions_secrets.go create mode 100644 vendor/github.com/google/go-github/v29/github/actions_workflows.go delete mode 100644 vendor/github.com/hashicorp/go-getter/.travis.yml create mode 100644 vendor/github.com/hashicorp/hcl/v2/appveyor.yml create mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md create mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go create mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go create mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md create mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go create mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go delete mode 100644 vendor/github.com/hashicorp/logutils/LICENSE delete mode 100644 vendor/github.com/hashicorp/logutils/README.md delete mode 100644 vendor/github.com/hashicorp/logutils/go.mod delete mode 100644 vendor/github.com/hashicorp/logutils/level.go create mode 100644 vendor/github.com/hashicorp/terraform/addrs/provider.go create mode 100644 vendor/github.com/hashicorp/terraform/configs/experiments.go create mode 100644 vendor/github.com/hashicorp/terraform/configs/provider_requirements.go create mode 100644 vendor/github.com/hashicorp/terraform/experiments/doc.go create mode 100644 vendor/github.com/hashicorp/terraform/experiments/errors.go create mode 100644 vendor/github.com/hashicorp/terraform/experiments/experiment.go create mode 100644 vendor/github.com/hashicorp/terraform/experiments/set.go create mode 100644 vendor/github.com/hashicorp/terraform/experiments/testing.go create mode 100644 vendor/github.com/hashicorp/terraform/helper/logging/indent.go create mode 100644 vendor/github.com/hashicorp/terraform/helper/logging/level.go create mode 100644 vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go diff --git a/github/config.go b/github/config.go index 6563f459b4..7edb3eec33 100644 --- a/github/config.go +++ b/github/config.go @@ -23,6 +23,7 @@ type Config struct { type Organization struct { name string + id int64 client *github.Client StopContext context.Context } @@ -48,12 +49,6 @@ func (c *Config) Client() (interface{}, error) { return nil, fmt.Errorf("If `individual` is false, `organization` is required.") } - if c.Individual { - org.name = "" - } else { - org.name = c.Organization - } - // Either run as anonymous, or run with a Token if c.Token != "" && c.Anonymous { return nil, fmt.Errorf("If `anonymous` is true, `token` cannot be set.") @@ -89,6 +84,18 @@ func (c *Config) Client() (interface{}, error) { org.client.BaseURL = u } + if c.Individual { + org.name = "" + } else { + org.name = c.Organization + + remoteOrg, _, err := org.client.Organizations.Get(ctx, org.name) + if err != nil { + return nil, err + } + org.id = remoteOrg.GetID() + } + return &org, nil } diff --git a/github/resource_github_team.go b/github/resource_github_team.go index 65f4e098b4..4b2b20ab2c 100644 --- a/github/resource_github_team.go +++ b/github/resource_github_team.go @@ -98,7 +98,13 @@ func resourceGithubTeamCreate(d *schema.ResourceData, meta interface{}) error { } func resourceGithubTeamRead(d *schema.ResourceData, meta interface{}) error { + err := checkOrganization(meta) + if err != nil { + return err + } + client := meta.(*Organization).client + orgId := meta.(*Organization).id id, err := strconv.ParseInt(d.Id(), 10, 64) if err != nil { @@ -110,7 +116,7 @@ func resourceGithubTeamRead(d *schema.ResourceData, meta interface{}) error { } log.Printf("[DEBUG] Reading team: %s", d.Id()) - team, resp, err := client.Teams.GetTeam(ctx, id) + team, resp, err := client.Teams.GetTeamByID(ctx, orgId, id) if err != nil { if ghErr, ok := err.(*github.ErrorResponse); ok { if ghErr.Response.StatusCode == http.StatusNotModified { @@ -142,7 +148,13 @@ func resourceGithubTeamRead(d *schema.ResourceData, meta interface{}) error { } func resourceGithubTeamUpdate(d *schema.ResourceData, meta interface{}) error { + err := checkOrganization(meta) + if err != nil { + return err + } + client := meta.(*Organization).client + orgId := meta.(*Organization).id editedTeam := github.NewTeam{ Name: d.Get("name").(string), @@ -161,7 +173,7 @@ func resourceGithubTeamUpdate(d *schema.ResourceData, meta interface{}) error { ctx := context.WithValue(context.Background(), ctxId, d.Id()) log.Printf("[DEBUG] Updating team: %s", d.Id()) - team, _, err := client.Teams.EditTeam(ctx, teamId, editedTeam, false) + team, _, err := client.Teams.EditTeamByID(ctx, orgId, teamId, editedTeam, false) if err != nil { return err } @@ -182,7 +194,13 @@ func resourceGithubTeamUpdate(d *schema.ResourceData, meta interface{}) error { } func resourceGithubTeamDelete(d *schema.ResourceData, meta interface{}) error { + err := checkOrganization(meta) + if err != nil { + return err + } + client := meta.(*Organization).client + orgId := meta.(*Organization).id id, err := strconv.ParseInt(d.Id(), 10, 64) if err != nil { @@ -191,6 +209,6 @@ func resourceGithubTeamDelete(d *schema.ResourceData, meta interface{}) error { ctx := context.WithValue(context.Background(), ctxId, d.Id()) log.Printf("[DEBUG] Deleting team: %s", d.Id()) - _, err = client.Teams.DeleteTeam(ctx, id) + _, err = client.Teams.DeleteTeamByID(ctx, orgId, id) return err } diff --git a/github/resource_github_team_repository.go b/github/resource_github_team_repository.go index aca3ea4dc4..38234196a6 100644 --- a/github/resource_github_team_repository.go +++ b/github/resource_github_team_repository.go @@ -53,6 +53,7 @@ func resourceGithubTeamRepositoryCreate(d *schema.ResourceData, meta interface{} } client := meta.(*Organization).client + orgId := meta.(*Organization).id teamIdString := d.Get("team_id").(string) teamId, err := strconv.ParseInt(teamIdString, 10, 64) @@ -66,7 +67,8 @@ func resourceGithubTeamRepositoryCreate(d *schema.ResourceData, meta interface{} log.Printf("[DEBUG] Creating team repository association: %s:%s (%s/%s)", teamIdString, permission, orgName, repoName) - _, err = client.Teams.AddTeamRepo(ctx, + _, err = client.Teams.AddTeamRepoByID(ctx, + orgId, teamId, orgName, repoName, @@ -91,6 +93,7 @@ func resourceGithubTeamRepositoryRead(d *schema.ResourceData, meta interface{}) } client := meta.(*Organization).client + orgId := meta.(*Organization).id teamIdString, repoName, err := parseTwoPartID(d.Id(), "team_id", "repository") if err != nil { @@ -108,7 +111,7 @@ func resourceGithubTeamRepositoryRead(d *schema.ResourceData, meta interface{}) } log.Printf("[DEBUG] Reading team repository association: %s (%s/%s)", teamIdString, orgName, repoName) - repo, resp, repoErr := client.Teams.IsTeamRepo(ctx, teamId, orgName, repoName) + repo, resp, repoErr := client.Teams.IsTeamRepoByID(ctx, orgId, teamId, orgName, repoName) if repoErr != nil { if ghErr, ok := repoErr.(*github.ErrorResponse); ok { if ghErr.Response.StatusCode == http.StatusNotModified { @@ -145,6 +148,7 @@ func resourceGithubTeamRepositoryUpdate(d *schema.ResourceData, meta interface{} } client := meta.(*Organization).client + orgId := meta.(*Organization).id teamIdString := d.Get("team_id").(string) teamId, err := strconv.ParseInt(teamIdString, 10, 64) @@ -159,7 +163,8 @@ func resourceGithubTeamRepositoryUpdate(d *schema.ResourceData, meta interface{} log.Printf("[DEBUG] Updating team repository association: %s:%s (%s/%s)", teamIdString, permission, orgName, repoName) // the go-github library's AddTeamRepo method uses the add/update endpoint from Github API - _, err = client.Teams.AddTeamRepo(ctx, + _, err = client.Teams.AddTeamRepoByID(ctx, + orgId, teamId, orgName, repoName, @@ -183,6 +188,7 @@ func resourceGithubTeamRepositoryDelete(d *schema.ResourceData, meta interface{} } client := meta.(*Organization).client + orgId := meta.(*Organization).id teamIdString := d.Get("team_id").(string) @@ -196,7 +202,6 @@ func resourceGithubTeamRepositoryDelete(d *schema.ResourceData, meta interface{} log.Printf("[DEBUG] Deleting team repository association: %s (%s/%s)", teamIdString, orgName, repoName) - _, err = client.Teams.RemoveTeamRepo(ctx, - teamId, orgName, repoName) + _, err = client.Teams.RemoveTeamRepoByID(ctx, orgId, teamId, orgName, repoName) return err } diff --git a/github/resource_github_team_repository_test.go b/github/resource_github_team_repository_test.go index 22a468a520..6492bd498c 100644 --- a/github/resource_github_team_repository_test.go +++ b/github/resource_github_team_repository_test.go @@ -122,7 +122,8 @@ func testAccCheckGithubTeamRepositoryExists(n string, repository *github.Reposit return unconvertibleIdErr(teamIdString, err) } - repo, _, err := conn.Teams.IsTeamRepo(context.TODO(), + repo, _, err := conn.Teams.IsTeamRepoByID(context.TODO(), + repository.GetID(), teamId, testAccProvider.Meta().(*Organization).name, repoName) @@ -137,6 +138,7 @@ func testAccCheckGithubTeamRepositoryExists(n string, repository *github.Reposit func testAccCheckGithubTeamRepositoryDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*Organization).client + orgId := testAccProvider.Meta().(*Organization).id for _, rs := range s.RootModule().Resources { if rs.Type != "github_team_repository" { @@ -152,7 +154,8 @@ func testAccCheckGithubTeamRepositoryDestroy(s *terraform.State) error { return unconvertibleIdErr(teamIdString, err) } - repo, resp, err := conn.Teams.IsTeamRepo(context.TODO(), + repo, resp, err := conn.Teams.IsTeamRepoByID(context.TODO(), + orgId, teamId, testAccProvider.Meta().(*Organization).name, repoName) diff --git a/github/resource_github_team_test.go b/github/resource_github_team_test.go index 7575a29676..cf7c71fcb0 100644 --- a/github/resource_github_team_test.go +++ b/github/resource_github_team_test.go @@ -146,7 +146,7 @@ func testAccCheckGithubTeamExists(n string, team *github.Team) resource.TestChec return unconvertibleIdErr(rs.Primary.ID, err) } - githubTeam, _, err := conn.Teams.GetTeam(context.TODO(), id) + githubTeam, _, err := conn.Teams.GetTeamByID(context.TODO(), team.Organization.GetID(), id) if err != nil { return err } @@ -179,6 +179,7 @@ func testAccCheckGithubTeamAttributes(team *github.Team, name, description strin func testAccCheckGithubTeamDestroy(s *terraform.State) error { conn := testAccProvider.Meta().(*Organization).client + orgId := testAccProvider.Meta().(*Organization).id for _, rs := range s.RootModule().Resources { if rs.Type != "github_team" { @@ -190,7 +191,7 @@ func testAccCheckGithubTeamDestroy(s *terraform.State) error { return unconvertibleIdErr(rs.Primary.ID, err) } - team, resp, err := conn.Teams.GetTeam(context.TODO(), id) + team, resp, err := conn.Teams.GetTeamByID(context.TODO(), orgId, id) if err == nil { teamId := strconv.FormatInt(*team.ID, 10) if team != nil && teamId == rs.Primary.ID { diff --git a/go.mod b/go.mod index 10eada1c69..046acce866 100644 --- a/go.mod +++ b/go.mod @@ -1,9 +1,10 @@ module github.com/terraform-providers/terraform-provider-github require ( - github.com/google/go-github/v29 v29.0.2 + github.com/google/go-github/v29 v29.0.3 github.com/hashicorp/terraform-plugin-sdk v1.7.0 github.com/kylelemons/godebug v1.1.0 + github.com/terraform-providers/terraform-provider-tls v1.2.0 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d ) diff --git a/go.sum b/go.sum index 5465f7d564..9ee96b6341 100644 --- a/go.sum +++ b/go.sum @@ -57,8 +57,8 @@ github.com/google/go-cmp v0.2.0/go.mod h1:oXzfMopK8JAjlY9xF4vHSVASa0yLyX7SntLO5a github.com/google/go-cmp v0.3.0/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/google/go-cmp v0.3.1 h1:Xye71clBPdm5HgqGwUkwhbynsUJZhDbS20FvLhQ2izg= github.com/google/go-cmp v0.3.1/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= -github.com/google/go-github/v29 v29.0.2 h1:opYN6Wc7DOz7Ku3Oh4l7prmkOMwEcQxpFtxdU8N8Pts= -github.com/google/go-github/v29 v29.0.2/go.mod h1:CHKiKKPHJ0REzfwc14QMklvtHwCveD0PxlMjLlzAM5E= +github.com/google/go-github/v29 v29.0.3 h1:IktKCTwU//aFHnpA+2SLIi7Oo9uhAzgsdZNbcAqhgdc= +github.com/google/go-github/v29 v29.0.3/go.mod h1:CHKiKKPHJ0REzfwc14QMklvtHwCveD0PxlMjLlzAM5E= github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk= github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck= github.com/google/martian v2.1.0+incompatible h1:/CP5g8u/VJHijgedC/Legn3BAbAaWPgecwXBIDzw5no= @@ -174,6 +174,7 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/terraform-providers/terraform-provider-tls v1.2.0/go.mod h1:Mxe/v5u31LDW4m32O1z6Ursdh95dpc9Puq6otkYg7tU= github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok= github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= diff --git a/vendor/github.com/hashicorp/logutils/.gitignore b/vendor/github.com/bmatcuk/doublestar/.gitignore similarity index 81% rename from vendor/github.com/hashicorp/logutils/.gitignore rename to vendor/github.com/bmatcuk/doublestar/.gitignore index 00268614f0..af212ecc28 100644 --- a/vendor/github.com/hashicorp/logutils/.gitignore +++ b/vendor/github.com/bmatcuk/doublestar/.gitignore @@ -1,3 +1,8 @@ +# vi +*~ +*.swp +*.swo + # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a @@ -20,3 +25,8 @@ _cgo_export.* _testmain.go *.exe +*.test +*.prof + +# test directory +test/ diff --git a/vendor/github.com/bmatcuk/doublestar/.travis.yml b/vendor/github.com/bmatcuk/doublestar/.travis.yml new file mode 100644 index 0000000000..ec4fee8896 --- /dev/null +++ b/vendor/github.com/bmatcuk/doublestar/.travis.yml @@ -0,0 +1,15 @@ +language: go + +go: + - 1.11 + - 1.12 + +before_install: + - go get -t -v ./... + +script: + - go test -race -coverprofile=coverage.txt -covermode=atomic + +after_success: + - bash <(curl -s https://codecov.io/bash) + diff --git a/vendor/github.com/bmatcuk/doublestar/LICENSE b/vendor/github.com/bmatcuk/doublestar/LICENSE new file mode 100644 index 0000000000..309c9d1d11 --- /dev/null +++ b/vendor/github.com/bmatcuk/doublestar/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2014 Bob Matcuk + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/vendor/github.com/bmatcuk/doublestar/README.md b/vendor/github.com/bmatcuk/doublestar/README.md new file mode 100644 index 0000000000..8e365c5e3f --- /dev/null +++ b/vendor/github.com/bmatcuk/doublestar/README.md @@ -0,0 +1,109 @@ +![Release](https://img.shields.io/github/release/bmatcuk/doublestar.svg?branch=master) +[![Build Status](https://travis-ci.org/bmatcuk/doublestar.svg?branch=master)](https://travis-ci.org/bmatcuk/doublestar) +[![codecov.io](https://img.shields.io/codecov/c/github/bmatcuk/doublestar.svg?branch=master)](https://codecov.io/github/bmatcuk/doublestar?branch=master) + +# doublestar + +**doublestar** is a [golang](http://golang.org/) implementation of path pattern +matching and globbing with support for "doublestar" (aka globstar: `**`) +patterns. + +doublestar patterns match files and directories recursively. For example, if +you had the following directory structure: + +``` +grandparent +`-- parent + |-- child1 + `-- child2 +``` + +You could find the children with patterns such as: `**/child*`, +`grandparent/**/child?`, `**/parent/*`, or even just `**` by itself (which will +return all files and directories recursively). + +Bash's globstar is doublestar's inspiration and, as such, works similarly. +Note that the doublestar must appear as a path component by itself. A pattern +such as `/path**` is invalid and will be treated the same as `/path*`, but +`/path*/**` should achieve the desired result. Additionally, `/path/**` will +match all directories and files under the path directory, but `/path/**/` will +only match directories. + +## Installation + +**doublestar** can be installed via `go get`: + +```bash +go get github.com/bmatcuk/doublestar +``` + +To use it in your code, you must import it: + +```go +import "github.com/bmatcuk/doublestar" +``` + +## Functions + +### Match +```go +func Match(pattern, name string) (bool, error) +``` + +Match returns true if `name` matches the file name `pattern` +([see below](#patterns)). `name` and `pattern` are split on forward slash (`/`) +characters and may be relative or absolute. + +Note: `Match()` is meant to be a drop-in replacement for `path.Match()`. As +such, it always uses `/` as the path separator. If you are writing code that +will run on systems where `/` is not the path separator (such as Windows), you +want to use `PathMatch()` (below) instead. + + +### PathMatch +```go +func PathMatch(pattern, name string) (bool, error) +``` + +PathMatch returns true if `name` matches the file name `pattern` +([see below](#patterns)). The difference between Match and PathMatch is that +PathMatch will automatically use your system's path separator to split `name` +and `pattern`. + +`PathMatch()` is meant to be a drop-in replacement for `filepath.Match()`. + +### Glob +```go +func Glob(pattern string) ([]string, error) +``` + +Glob finds all files and directories in the filesystem that match `pattern` +([see below](#patterns)). `pattern` may be relative (to the current working +directory), or absolute. + +`Glob()` is meant to be a drop-in replacement for `filepath.Glob()`. + +## Patterns + +**doublestar** supports the following special terms in the patterns: + +Special Terms | Meaning +------------- | ------- +`*` | matches any sequence of non-path-separators +`**` | matches any sequence of characters, including path separators +`?` | matches any single non-path-separator character +`[class]` | matches any single non-path-separator character against a class of characters ([see below](#character-classes)) +`{alt1,...}` | matches a sequence of characters if one of the comma-separated alternatives matches + +Any character with a special meaning can be escaped with a backslash (`\`). + +### Character Classes + +Character classes support the following: + +Class | Meaning +---------- | ------- +`[abc]` | matches any single character within the set +`[a-z]` | matches any single character in the range +`[^class]` | matches any single character which does *not* match the class + diff --git a/vendor/github.com/bmatcuk/doublestar/doublestar.go b/vendor/github.com/bmatcuk/doublestar/doublestar.go new file mode 100644 index 0000000000..0044dfa831 --- /dev/null +++ b/vendor/github.com/bmatcuk/doublestar/doublestar.go @@ -0,0 +1,476 @@ +package doublestar + +import ( + "fmt" + "os" + "path" + "path/filepath" + "strings" + "unicode/utf8" +) + +// ErrBadPattern indicates a pattern was malformed. +var ErrBadPattern = path.ErrBadPattern + +// Split a path on the given separator, respecting escaping. +func splitPathOnSeparator(path string, separator rune) (ret []string) { + idx := 0 + if separator == '\\' { + // if the separator is '\\', then we can just split... + ret = strings.Split(path, string(separator)) + idx = len(ret) + } else { + // otherwise, we need to be careful of situations where the separator was escaped + cnt := strings.Count(path, string(separator)) + if cnt == 0 { + return []string{path} + } + + ret = make([]string, cnt+1) + pathlen := len(path) + separatorLen := utf8.RuneLen(separator) + emptyEnd := false + for start := 0; start < pathlen; { + end := indexRuneWithEscaping(path[start:], separator) + if end == -1 { + emptyEnd = false + end = pathlen + } else { + emptyEnd = true + end += start + } + ret[idx] = path[start:end] + start = end + separatorLen + idx++ + } + + // If the last rune is a path separator, we need to append an empty string to + // represent the last, empty path component. By default, the strings from + // make([]string, ...) will be empty, so we just need to icrement the count + if emptyEnd { + idx++ + } + } + + return ret[:idx] +} + +// Find the first index of a rune in a string, +// ignoring any times the rune is escaped using "\". +func indexRuneWithEscaping(s string, r rune) int { + end := strings.IndexRune(s, r) + if end == -1 { + return -1 + } + if end > 0 && s[end-1] == '\\' { + start := end + utf8.RuneLen(r) + end = indexRuneWithEscaping(s[start:], r) + if end != -1 { + end += start + } + } + return end +} + +// Match returns true if name matches the shell file name pattern. +// The pattern syntax is: +// +// pattern: +// { term } +// term: +// '*' matches any sequence of non-path-separators +// '**' matches any sequence of characters, including +// path separators. +// '?' matches any single non-path-separator character +// '[' [ '^' ] { character-range } ']' +// character class (must be non-empty) +// '{' { term } [ ',' { term } ... ] '}' +// c matches character c (c != '*', '?', '\\', '[') +// '\\' c matches character c +// +// character-range: +// c matches character c (c != '\\', '-', ']') +// '\\' c matches character c +// lo '-' hi matches character c for lo <= c <= hi +// +// Match requires pattern to match all of name, not just a substring. +// The path-separator defaults to the '/' character. The only possible +// returned error is ErrBadPattern, when pattern is malformed. +// +// Note: this is meant as a drop-in replacement for path.Match() which +// always uses '/' as the path separator. If you want to support systems +// which use a different path separator (such as Windows), what you want +// is the PathMatch() function below. +// +func Match(pattern, name string) (bool, error) { + return matchWithSeparator(pattern, name, '/') +} + +// PathMatch is like Match except that it uses your system's path separator. +// For most systems, this will be '/'. However, for Windows, it would be '\\'. +// Note that for systems where the path separator is '\\', escaping is +// disabled. +// +// Note: this is meant as a drop-in replacement for filepath.Match(). +// +func PathMatch(pattern, name string) (bool, error) { + return matchWithSeparator(pattern, name, os.PathSeparator) +} + +// Match returns true if name matches the shell file name pattern. +// The pattern syntax is: +// +// pattern: +// { term } +// term: +// '*' matches any sequence of non-path-separators +// '**' matches any sequence of characters, including +// path separators. +// '?' matches any single non-path-separator character +// '[' [ '^' ] { character-range } ']' +// character class (must be non-empty) +// '{' { term } [ ',' { term } ... ] '}' +// c matches character c (c != '*', '?', '\\', '[') +// '\\' c matches character c +// +// character-range: +// c matches character c (c != '\\', '-', ']') +// '\\' c matches character c, unless separator is '\\' +// lo '-' hi matches character c for lo <= c <= hi +// +// Match requires pattern to match all of name, not just a substring. +// The only possible returned error is ErrBadPattern, when pattern +// is malformed. +// +func matchWithSeparator(pattern, name string, separator rune) (bool, error) { + patternComponents := splitPathOnSeparator(pattern, separator) + nameComponents := splitPathOnSeparator(name, separator) + return doMatching(patternComponents, nameComponents) +} + +func doMatching(patternComponents, nameComponents []string) (matched bool, err error) { + // check for some base-cases + patternLen, nameLen := len(patternComponents), len(nameComponents) + if patternLen == 0 && nameLen == 0 { + return true, nil + } + if patternLen == 0 || nameLen == 0 { + return false, nil + } + + patIdx, nameIdx := 0, 0 + for patIdx < patternLen && nameIdx < nameLen { + if patternComponents[patIdx] == "**" { + // if our last pattern component is a doublestar, we're done - + // doublestar will match any remaining name components, if any. + if patIdx++; patIdx >= patternLen { + return true, nil + } + + // otherwise, try matching remaining components + for ; nameIdx < nameLen; nameIdx++ { + if m, _ := doMatching(patternComponents[patIdx:], nameComponents[nameIdx:]); m { + return true, nil + } + } + return false, nil + } + + // try matching components + matched, err = matchComponent(patternComponents[patIdx], nameComponents[nameIdx]) + if !matched || err != nil { + return + } + + patIdx++ + nameIdx++ + } + return patIdx >= patternLen && nameIdx >= nameLen, nil +} + +// Glob returns the names of all files matching pattern or nil +// if there is no matching file. The syntax of pattern is the same +// as in Match. The pattern may describe hierarchical names such as +// /usr/*/bin/ed (assuming the Separator is '/'). +// +// Glob ignores file system errors such as I/O errors reading directories. +// The only possible returned error is ErrBadPattern, when pattern +// is malformed. +// +// Your system path separator is automatically used. This means on +// systems where the separator is '\\' (Windows), escaping will be +// disabled. +// +// Note: this is meant as a drop-in replacement for filepath.Glob(). +// +func Glob(pattern string) (matches []string, err error) { + patternComponents := splitPathOnSeparator(filepath.ToSlash(pattern), '/') + if len(patternComponents) == 0 { + return nil, nil + } + + // On Windows systems, this will return the drive name ('C:') for filesystem + // paths, or \\\ for UNC paths. On other systems, it will + // return an empty string. Since absolute paths on non-Windows systems start + // with a slash, patternComponent[0] == volumeName will return true for both + // absolute Windows paths and absolute non-Windows paths, but we need a + // separate check for UNC paths. + volumeName := filepath.VolumeName(pattern) + isWindowsUNC := strings.HasPrefix(pattern, `\\`) + if isWindowsUNC || patternComponents[0] == volumeName { + startComponentIndex := 1 + if isWindowsUNC { + startComponentIndex = 4 + } + return doGlob(fmt.Sprintf("%s%s", volumeName, string(os.PathSeparator)), patternComponents[startComponentIndex:], matches) + } + + // otherwise, it's a relative pattern + return doGlob(".", patternComponents, matches) +} + +// Perform a glob +func doGlob(basedir string, components, matches []string) (m []string, e error) { + m = matches + e = nil + + // figure out how many components we don't need to glob because they're + // just names without patterns - we'll use os.Lstat below to check if that + // path actually exists + patLen := len(components) + patIdx := 0 + for ; patIdx < patLen; patIdx++ { + if strings.IndexAny(components[patIdx], "*?[{\\") >= 0 { + break + } + } + if patIdx > 0 { + basedir = filepath.Join(basedir, filepath.Join(components[0:patIdx]...)) + } + + // Lstat will return an error if the file/directory doesn't exist + fi, err := os.Lstat(basedir) + if err != nil { + return + } + + // if there are no more components, we've found a match + if patIdx >= patLen { + m = append(m, basedir) + return + } + + // otherwise, we need to check each item in the directory... + // first, if basedir is a symlink, follow it... + if (fi.Mode() & os.ModeSymlink) != 0 { + fi, err = os.Stat(basedir) + if err != nil { + return + } + } + + // confirm it's a directory... + if !fi.IsDir() { + return + } + + // read directory + dir, err := os.Open(basedir) + if err != nil { + return + } + defer dir.Close() + + files, _ := dir.Readdir(-1) + lastComponent := (patIdx + 1) >= patLen + if components[patIdx] == "**" { + // if the current component is a doublestar, we'll try depth-first + for _, file := range files { + // if symlink, we may want to follow + if (file.Mode() & os.ModeSymlink) != 0 { + file, err = os.Stat(filepath.Join(basedir, file.Name())) + if err != nil { + continue + } + } + + if file.IsDir() { + // recurse into directories + if lastComponent { + m = append(m, filepath.Join(basedir, file.Name())) + } + m, e = doGlob(filepath.Join(basedir, file.Name()), components[patIdx:], m) + } else if lastComponent { + // if the pattern's last component is a doublestar, we match filenames, too + m = append(m, filepath.Join(basedir, file.Name())) + } + } + if lastComponent { + return // we're done + } + patIdx++ + lastComponent = (patIdx + 1) >= patLen + } + + // check items in current directory and recurse + var match bool + for _, file := range files { + match, e = matchComponent(components[patIdx], file.Name()) + if e != nil { + return + } + if match { + if lastComponent { + m = append(m, filepath.Join(basedir, file.Name())) + } else { + m, e = doGlob(filepath.Join(basedir, file.Name()), components[patIdx+1:], m) + } + } + } + return +} + +// Attempt to match a single pattern component with a path component +func matchComponent(pattern, name string) (bool, error) { + // check some base cases + patternLen, nameLen := len(pattern), len(name) + if patternLen == 0 && nameLen == 0 { + return true, nil + } + if patternLen == 0 { + return false, nil + } + if nameLen == 0 && pattern != "*" { + return false, nil + } + + // check for matches one rune at a time + patIdx, nameIdx := 0, 0 + for patIdx < patternLen && nameIdx < nameLen { + patRune, patAdj := utf8.DecodeRuneInString(pattern[patIdx:]) + nameRune, nameAdj := utf8.DecodeRuneInString(name[nameIdx:]) + if patRune == '\\' { + // handle escaped runes + patIdx += patAdj + patRune, patAdj = utf8.DecodeRuneInString(pattern[patIdx:]) + if patRune == utf8.RuneError { + return false, ErrBadPattern + } else if patRune == nameRune { + patIdx += patAdj + nameIdx += nameAdj + } else { + return false, nil + } + } else if patRune == '*' { + // handle stars + if patIdx += patAdj; patIdx >= patternLen { + // a star at the end of a pattern will always + // match the rest of the path + return true, nil + } + + // check if we can make any matches + for ; nameIdx < nameLen; nameIdx += nameAdj { + if m, _ := matchComponent(pattern[patIdx:], name[nameIdx:]); m { + return true, nil + } + } + return false, nil + } else if patRune == '[' { + // handle character sets + patIdx += patAdj + endClass := indexRuneWithEscaping(pattern[patIdx:], ']') + if endClass == -1 { + return false, ErrBadPattern + } + endClass += patIdx + classRunes := []rune(pattern[patIdx:endClass]) + classRunesLen := len(classRunes) + if classRunesLen > 0 { + classIdx := 0 + matchClass := false + if classRunes[0] == '^' { + classIdx++ + } + for classIdx < classRunesLen { + low := classRunes[classIdx] + if low == '-' { + return false, ErrBadPattern + } + classIdx++ + if low == '\\' { + if classIdx < classRunesLen { + low = classRunes[classIdx] + classIdx++ + } else { + return false, ErrBadPattern + } + } + high := low + if classIdx < classRunesLen && classRunes[classIdx] == '-' { + // we have a range of runes + if classIdx++; classIdx >= classRunesLen { + return false, ErrBadPattern + } + high = classRunes[classIdx] + if high == '-' { + return false, ErrBadPattern + } + classIdx++ + if high == '\\' { + if classIdx < classRunesLen { + high = classRunes[classIdx] + classIdx++ + } else { + return false, ErrBadPattern + } + } + } + if low <= nameRune && nameRune <= high { + matchClass = true + } + } + if matchClass == (classRunes[0] == '^') { + return false, nil + } + } else { + return false, ErrBadPattern + } + patIdx = endClass + 1 + nameIdx += nameAdj + } else if patRune == '{' { + // handle alternatives such as {alt1,alt2,...} + patIdx += patAdj + endOptions := indexRuneWithEscaping(pattern[patIdx:], '}') + if endOptions == -1 { + return false, ErrBadPattern + } + endOptions += patIdx + options := splitPathOnSeparator(pattern[patIdx:endOptions], ',') + patIdx = endOptions + 1 + for _, o := range options { + m, e := matchComponent(o+pattern[patIdx:], name[nameIdx:]) + if e != nil { + return false, e + } + if m { + return true, nil + } + } + return false, nil + } else if patRune == '?' || patRune == nameRune { + // handle single-rune wildcard + patIdx += patAdj + nameIdx += nameAdj + } else { + return false, nil + } + } + if patIdx >= patternLen && nameIdx >= nameLen { + return true, nil + } + if nameIdx >= nameLen && pattern[patIdx:] == "*" || pattern[patIdx:] == "**" { + return true, nil + } + return false, nil +} diff --git a/vendor/github.com/bmatcuk/doublestar/go.mod b/vendor/github.com/bmatcuk/doublestar/go.mod new file mode 100644 index 0000000000..ce1688f730 --- /dev/null +++ b/vendor/github.com/bmatcuk/doublestar/go.mod @@ -0,0 +1,3 @@ +module github.com/bmatcuk/doublestar + +go 1.12 diff --git a/vendor/github.com/google/go-github/v29/github/actions.go b/vendor/github.com/google/go-github/v29/github/actions.go new file mode 100644 index 0000000000..f9f7f8ee86 --- /dev/null +++ b/vendor/github.com/google/go-github/v29/github/actions.go @@ -0,0 +1,12 @@ +// Copyright 2020 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package github + +// ActionsService handles communication with the actions related +// methods of the GitHub API. +// +// GitHub API docs: https://developer.github.com/v3/actions/ +type ActionsService service diff --git a/vendor/github.com/google/go-github/v29/github/actions_secrets.go b/vendor/github.com/google/go-github/v29/github/actions_secrets.go new file mode 100644 index 0000000000..1640b5a02c --- /dev/null +++ b/vendor/github.com/google/go-github/v29/github/actions_secrets.go @@ -0,0 +1,132 @@ +// Copyright 2020 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package github + +import ( + "context" + "fmt" +) + +// PublicKey represents the public key that should be used to encrypt secrets. +type PublicKey struct { + KeyID *string `json:"key_id"` + Key *string `json:"key"` +} + +// GetPublicKey gets a public key that should be used for secret encryption. +// +// GitHub API docs: https://developer.github.com/v3/actions/secrets/#get-your-public-key +func (s *ActionsService) GetPublicKey(ctx context.Context, owner, repo string) (*PublicKey, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/actions/secrets/public-key", owner, repo) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + pubKey := new(PublicKey) + resp, err := s.client.Do(ctx, req, pubKey) + if err != nil { + return nil, resp, err + } + + return pubKey, resp, nil +} + +// Secret represents a repository action secret. +type Secret struct { + Name string `json:"name"` + CreatedAt Timestamp `json:"created_at"` + UpdatedAt Timestamp `json:"updated_at"` +} + +// Secrets represents one item from the ListSecrets response. +type Secrets struct { + TotalCount int `json:"total_count"` + Secrets []*Secret `json:"secrets"` +} + +// ListSecrets lists all secrets available in a repository +// without revealing their encrypted values. +// +// GitHub API docs: https://developer.github.com/v3/actions/secrets/#list-secrets-for-a-repository +func (s *ActionsService) ListSecrets(ctx context.Context, owner, repo string, opts *ListOptions) (*Secrets, *Response, error) { + u := fmt.Sprintf("repos/%s/%s/actions/secrets", owner, repo) + u, err := addOptions(u, opts) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + secrets := new(Secrets) + resp, err := s.client.Do(ctx, req, &secrets) + if err != nil { + return nil, resp, err + } + + return secrets, resp, nil +} + +// GetSecret gets a single secret without revealing its encrypted value. +// +// GitHub API docs: https://developer.github.com/v3/actions/secrets/#get-a-secret +func (s *ActionsService) GetSecret(ctx context.Context, owner, repo, name string) (*Secret, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/actions/secrets/%v", owner, repo, name) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + secret := new(Secret) + resp, err := s.client.Do(ctx, req, secret) + if err != nil { + return nil, resp, err + } + + return secret, resp, nil +} + +// EncryptedSecret represents a secret that is encrypted using a public key. +// +// The value of EncryptedValue must be your secret, encrypted with +// LibSodium (see documentation here: https://libsodium.gitbook.io/doc/bindings_for_other_languages) +// using the public key retrieved using the GetPublicKey method. +type EncryptedSecret struct { + Name string `json:"-"` + KeyID string `json:"key_id"` + EncryptedValue string `json:"encrypted_value"` +} + +// CreateOrUpdateSecret creates or updates a secret with an encrypted value. +// +// GitHub API docs: https://developer.github.com/v3/actions/secrets/#create-or-update-a-secret-for-a-repository +func (s *ActionsService) CreateOrUpdateSecret(ctx context.Context, owner, repo string, eSecret *EncryptedSecret) (*Response, error) { + u := fmt.Sprintf("repos/%v/%v/actions/secrets/%v", owner, repo, eSecret.Name) + + req, err := s.client.NewRequest("PUT", u, eSecret) + if err != nil { + return nil, err + } + + return s.client.Do(ctx, req, nil) +} + +// DeleteSecret deletes a secret in a repository using the secret name. +// +// GitHub API docs: https://developer.github.com/v3/actions/secrets/#delete-a-secret-from-a-repository +func (s *ActionsService) DeleteSecret(ctx context.Context, owner, repo, name string) (*Response, error) { + u := fmt.Sprintf("repos/%v/%v/actions/secrets/%v", owner, repo, name) + + req, err := s.client.NewRequest("DELETE", u, nil) + if err != nil { + return nil, err + } + + return s.client.Do(ctx, req, nil) +} diff --git a/vendor/github.com/google/go-github/v29/github/actions_workflows.go b/vendor/github.com/google/go-github/v29/github/actions_workflows.go new file mode 100644 index 0000000000..fc4cf4a531 --- /dev/null +++ b/vendor/github.com/google/go-github/v29/github/actions_workflows.go @@ -0,0 +1,88 @@ +// Copyright 2020 The go-github AUTHORS. All rights reserved. +// +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package github + +import ( + "context" + "fmt" +) + +// Workflow represents a repository action workflow. +type Workflow struct { + ID int64 `json:"id"` + NodeID string `json:"node_id"` + Name string `json:"name"` + Path string `json:"path"` + State string `json:"state"` + CreatedAt Timestamp `json:"created_at"` + UpdatedAt Timestamp `json:"updated_at"` + URL string `json:"url"` + HTMLURL string `json:"html_url"` + BadgeURL string `json:"badge_url"` +} + +// Workflows represents a slice of repository action workflows. +type Workflows struct { + TotalCount int `json:"total_count"` + Workflows []*Workflow `json:"workflows"` +} + +// ListWorkflows lists all workflows in a repository. +// +// GitHub API docs: https://developer.github.com/v3/actions/workflows/#list-repository-workflows +func (s *ActionsService) ListWorkflows(ctx context.Context, owner, repo string, opts *ListOptions) (*Workflows, *Response, error) { + u := fmt.Sprintf("repos/%s/%s/actions/workflows", owner, repo) + u, err := addOptions(u, opts) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + workflows := new(Workflows) + resp, err := s.client.Do(ctx, req, &workflows) + if err != nil { + return nil, resp, err + } + + return workflows, resp, nil +} + +// GetWorkflowByID gets a specific workflow by ID. +// +// GitHub API docs: https://developer.github.com/v3/actions/workflows/#get-a-workflow +func (s *ActionsService) GetWorkflowByID(ctx context.Context, owner, repo string, workflowID int64) (*Workflow, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v", owner, repo, workflowID) + + return s.getWorkflow(ctx, u) +} + +// GetWorkflowByFileName gets a specific workflow by file name. +// +// GitHub API docs: https://developer.github.com/v3/actions/workflows/#get-a-workflow +func (s *ActionsService) GetWorkflowByFileName(ctx context.Context, owner, repo, workflowFileName string) (*Workflow, *Response, error) { + u := fmt.Sprintf("repos/%v/%v/actions/workflows/%v", owner, repo, workflowFileName) + + return s.getWorkflow(ctx, u) +} + +func (s *ActionsService) getWorkflow(ctx context.Context, url string) (*Workflow, *Response, error) { + req, err := s.client.NewRequest("GET", url, nil) + if err != nil { + return nil, nil, err + } + + workflow := new(Workflow) + resp, err := s.client.Do(ctx, req, workflow) + if err != nil { + return nil, resp, err + } + + return workflow, resp, nil +} diff --git a/vendor/github.com/google/go-github/v29/github/activity_events.go b/vendor/github.com/google/go-github/v29/github/activity_events.go index 1754b78e9d..115bcc97d3 100644 --- a/vendor/github.com/google/go-github/v29/github/activity_events.go +++ b/vendor/github.com/google/go-github/v29/github/activity_events.go @@ -13,8 +13,8 @@ import ( // ListEvents drinks from the firehose of all public events across GitHub. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events -func (s *ActivityService) ListEvents(ctx context.Context, opt *ListOptions) ([]*Event, *Response, error) { - u, err := addOptions("events", opt) +func (s *ActivityService) ListEvents(ctx context.Context, opts *ListOptions) ([]*Event, *Response, error) { + u, err := addOptions("events", opts) if err != nil { return nil, nil, err } @@ -36,9 +36,9 @@ func (s *ActivityService) ListEvents(ctx context.Context, opt *ListOptions) ([]* // ListRepositoryEvents lists events for a repository. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-repository-events -func (s *ActivityService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { +func (s *ActivityService) ListRepositoryEvents(ctx context.Context, owner, repo string, opts *ListOptions) ([]*Event, *Response, error) { u := fmt.Sprintf("repos/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -60,9 +60,9 @@ func (s *ActivityService) ListRepositoryEvents(ctx context.Context, owner, repo // ListIssueEventsForRepository lists issue events for a repository. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-issue-events-for-a-repository -func (s *ActivityService) ListIssueEventsForRepository(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { +func (s *ActivityService) ListIssueEventsForRepository(ctx context.Context, owner, repo string, opts *ListOptions) ([]*IssueEvent, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -84,9 +84,9 @@ func (s *ActivityService) ListIssueEventsForRepository(ctx context.Context, owne // ListEventsForRepoNetwork lists public events for a network of repositories. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-a-network-of-repositories -func (s *ActivityService) ListEventsForRepoNetwork(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Event, *Response, error) { +func (s *ActivityService) ListEventsForRepoNetwork(ctx context.Context, owner, repo string, opts *ListOptions) ([]*Event, *Response, error) { u := fmt.Sprintf("networks/%v/%v/events", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -108,9 +108,9 @@ func (s *ActivityService) ListEventsForRepoNetwork(ctx context.Context, owner, r // ListEventsForOrganization lists public events for an organization. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-public-events-for-an-organization -func (s *ActivityService) ListEventsForOrganization(ctx context.Context, org string, opt *ListOptions) ([]*Event, *Response, error) { +func (s *ActivityService) ListEventsForOrganization(ctx context.Context, org string, opts *ListOptions) ([]*Event, *Response, error) { u := fmt.Sprintf("orgs/%v/events", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -133,14 +133,14 @@ func (s *ActivityService) ListEventsForOrganization(ctx context.Context, org str // true, only public events will be returned. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-performed-by-a-user -func (s *ActivityService) ListEventsPerformedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { +func (s *ActivityService) ListEventsPerformedByUser(ctx context.Context, user string, publicOnly bool, opts *ListOptions) ([]*Event, *Response, error) { var u string if publicOnly { u = fmt.Sprintf("users/%v/events/public", user) } else { u = fmt.Sprintf("users/%v/events", user) } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -163,14 +163,14 @@ func (s *ActivityService) ListEventsPerformedByUser(ctx context.Context, user st // true, only public events will be returned. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-that-a-user-has-received -func (s *ActivityService) ListEventsReceivedByUser(ctx context.Context, user string, publicOnly bool, opt *ListOptions) ([]*Event, *Response, error) { +func (s *ActivityService) ListEventsReceivedByUser(ctx context.Context, user string, publicOnly bool, opts *ListOptions) ([]*Event, *Response, error) { var u string if publicOnly { u = fmt.Sprintf("users/%v/received_events/public", user) } else { u = fmt.Sprintf("users/%v/received_events", user) } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -193,9 +193,9 @@ func (s *ActivityService) ListEventsReceivedByUser(ctx context.Context, user str // must be authenticated as the user to view this. // // GitHub API docs: https://developer.github.com/v3/activity/events/#list-events-for-an-organization -func (s *ActivityService) ListUserEventsForOrganization(ctx context.Context, org, user string, opt *ListOptions) ([]*Event, *Response, error) { +func (s *ActivityService) ListUserEventsForOrganization(ctx context.Context, org, user string, opts *ListOptions) ([]*Event, *Response, error) { u := fmt.Sprintf("users/%v/events/orgs/%v", user, org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/activity_notifications.go b/vendor/github.com/google/go-github/v29/github/activity_notifications.go index 45c8b2aece..983da6f82f 100644 --- a/vendor/github.com/google/go-github/v29/github/activity_notifications.go +++ b/vendor/github.com/google/go-github/v29/github/activity_notifications.go @@ -50,9 +50,9 @@ type NotificationListOptions struct { // ListNotifications lists all notifications for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications -func (s *ActivityService) ListNotifications(ctx context.Context, opt *NotificationListOptions) ([]*Notification, *Response, error) { +func (s *ActivityService) ListNotifications(ctx context.Context, opts *NotificationListOptions) ([]*Notification, *Response, error) { u := fmt.Sprintf("notifications") - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -75,9 +75,9 @@ func (s *ActivityService) ListNotifications(ctx context.Context, opt *Notificati // for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/activity/notifications/#list-your-notifications-in-a-repository -func (s *ActivityService) ListRepositoryNotifications(ctx context.Context, owner, repo string, opt *NotificationListOptions) ([]*Notification, *Response, error) { +func (s *ActivityService) ListRepositoryNotifications(ctx context.Context, owner, repo string, opts *NotificationListOptions) ([]*Notification, *Response, error) { u := fmt.Sprintf("repos/%v/%v/notifications", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/activity_star.go b/vendor/github.com/google/go-github/v29/github/activity_star.go index 5ae5c10165..1e9850f9e1 100644 --- a/vendor/github.com/google/go-github/v29/github/activity_star.go +++ b/vendor/github.com/google/go-github/v29/github/activity_star.go @@ -26,9 +26,9 @@ type Stargazer struct { // ListStargazers lists people who have starred the specified repo. // // GitHub API docs: https://developer.github.com/v3/activity/starring/#list-stargazers -func (s *ActivityService) ListStargazers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Stargazer, *Response, error) { +func (s *ActivityService) ListStargazers(ctx context.Context, owner, repo string, opts *ListOptions) ([]*Stargazer, *Response, error) { u := fmt.Sprintf("repos/%s/%s/stargazers", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -68,14 +68,14 @@ type ActivityListStarredOptions struct { // will list the starred repositories for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/activity/starring/#list-repositories-being-starred -func (s *ActivityService) ListStarred(ctx context.Context, user string, opt *ActivityListStarredOptions) ([]*StarredRepository, *Response, error) { +func (s *ActivityService) ListStarred(ctx context.Context, user string, opts *ActivityListStarredOptions) ([]*StarredRepository, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/starred", user) } else { u = "user/starred" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/activity_watching.go b/vendor/github.com/google/go-github/v29/github/activity_watching.go index c749ca86e7..608647a6ce 100644 --- a/vendor/github.com/google/go-github/v29/github/activity_watching.go +++ b/vendor/github.com/google/go-github/v29/github/activity_watching.go @@ -28,9 +28,9 @@ type Subscription struct { // ListWatchers lists watchers of a particular repo. // // GitHub API docs: https://developer.github.com/v3/activity/watching/#list-watchers -func (s *ActivityService) ListWatchers(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { +func (s *ActivityService) ListWatchers(ctx context.Context, owner, repo string, opts *ListOptions) ([]*User, *Response, error) { u := fmt.Sprintf("repos/%s/%s/subscribers", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -53,14 +53,14 @@ func (s *ActivityService) ListWatchers(ctx context.Context, owner, repo string, // the empty string will fetch watched repos for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/activity/watching/#list-repositories-being-watched -func (s *ActivityService) ListWatched(ctx context.Context, user string, opt *ListOptions) ([]*Repository, *Response, error) { +func (s *ActivityService) ListWatched(ctx context.Context, user string, opts *ListOptions) ([]*Repository, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/subscriptions", user) } else { u = "user/subscriptions" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/admin_users.go b/vendor/github.com/google/go-github/v29/github/admin_users.go index 742855501e..d756a77e20 100644 --- a/vendor/github.com/google/go-github/v29/github/admin_users.go +++ b/vendor/github.com/google/go-github/v29/github/admin_users.go @@ -96,10 +96,10 @@ type UserAuthorization struct { // CreateUserImpersonation creates an impersonation OAuth token. // // GitHub Enterprise API docs: https://developer.github.com/enterprise/v3/enterprise-admin/users/#create-an-impersonation-oauth-token -func (s *AdminService) CreateUserImpersonation(ctx context.Context, username string, opt *ImpersonateUserOptions) (*UserAuthorization, *Response, error) { +func (s *AdminService) CreateUserImpersonation(ctx context.Context, username string, opts *ImpersonateUserOptions) (*UserAuthorization, *Response, error) { u := fmt.Sprintf("admin/users/%s/authorizations", username) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/apps.go b/vendor/github.com/google/go-github/v29/github/apps.go index 5bd76338dc..75d9177fa9 100644 --- a/vendor/github.com/google/go-github/v29/github/apps.go +++ b/vendor/github.com/google/go-github/v29/github/apps.go @@ -152,8 +152,8 @@ func (s *AppsService) Get(ctx context.Context, appSlug string) (*App, *Response, // ListInstallations lists the installations that the current GitHub App has. // // GitHub API docs: https://developer.github.com/v3/apps/#list-installations -func (s *AppsService) ListInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("app/installations", opt) +func (s *AppsService) ListInstallations(ctx context.Context, opts *ListOptions) ([]*Installation, *Response, error) { + u, err := addOptions("app/installations", opts) if err != nil { return nil, nil, err } @@ -185,8 +185,8 @@ func (s *AppsService) GetInstallation(ctx context.Context, id int64) (*Installat // ListUserInstallations lists installations that are accessible to the authenticated user. // // GitHub API docs: https://developer.github.com/v3/apps/#list-installations-for-user -func (s *AppsService) ListUserInstallations(ctx context.Context, opt *ListOptions) ([]*Installation, *Response, error) { - u, err := addOptions("user/installations", opt) +func (s *AppsService) ListUserInstallations(ctx context.Context, opts *ListOptions) ([]*Installation, *Response, error) { + u, err := addOptions("user/installations", opts) if err != nil { return nil, nil, err } @@ -213,10 +213,10 @@ func (s *AppsService) ListUserInstallations(ctx context.Context, opt *ListOption // CreateInstallationToken creates a new installation token. // // GitHub API docs: https://developer.github.com/v3/apps/#create-a-new-installation-token -func (s *AppsService) CreateInstallationToken(ctx context.Context, id int64, opt *InstallationTokenOptions) (*InstallationToken, *Response, error) { +func (s *AppsService) CreateInstallationToken(ctx context.Context, id int64, opts *InstallationTokenOptions) (*InstallationToken, *Response, error) { u := fmt.Sprintf("app/installations/%v/access_tokens", id) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/apps_installation.go b/vendor/github.com/google/go-github/v29/github/apps_installation.go index 09d4043fe6..59a90c15a9 100644 --- a/vendor/github.com/google/go-github/v29/github/apps_installation.go +++ b/vendor/github.com/google/go-github/v29/github/apps_installation.go @@ -13,8 +13,8 @@ import ( // ListRepos lists the repositories that are accessible to the authenticated installation. // // GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories -func (s *AppsService) ListRepos(ctx context.Context, opt *ListOptions) ([]*Repository, *Response, error) { - u, err := addOptions("installation/repositories", opt) +func (s *AppsService) ListRepos(ctx context.Context, opts *ListOptions) ([]*Repository, *Response, error) { + u, err := addOptions("installation/repositories", opts) if err != nil { return nil, nil, err } @@ -42,9 +42,9 @@ func (s *AppsService) ListRepos(ctx context.Context, opt *ListOptions) ([]*Repos // to the authenticated user for an installation. // // GitHub API docs: https://developer.github.com/v3/apps/installations/#list-repositories-accessible-to-the-user-for-an-installation -func (s *AppsService) ListUserRepos(ctx context.Context, id int64, opt *ListOptions) ([]*Repository, *Response, error) { +func (s *AppsService) ListUserRepos(ctx context.Context, id int64, opts *ListOptions) ([]*Repository, *Response, error) { u := fmt.Sprintf("user/installations/%v/repositories", id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -101,3 +101,17 @@ func (s *AppsService) RemoveRepository(ctx context.Context, instID, repoID int64 return s.client.Do(ctx, req, nil) } + +// RevokeInstallationToken revokes an installation token. +// +// GitHub docs: https://developer.github.com/v3/apps/installations/#revoke-an-installation-token +func (s *AppsService) RevokeInstallationToken(ctx context.Context) (*Response, error) { + u := "installation/token" + req, err := s.client.NewRequest("DELETE", u, nil) + if err != nil { + return nil, err + } + req.Header.Set("Accept", mediaTypeRevokeTokenPreview) + + return s.client.Do(ctx, req, nil) +} diff --git a/vendor/github.com/google/go-github/v29/github/apps_marketplace.go b/vendor/github.com/google/go-github/v29/github/apps_marketplace.go index 863ba934cb..053d451dc6 100644 --- a/vendor/github.com/google/go-github/v29/github/apps_marketplace.go +++ b/vendor/github.com/google/go-github/v29/github/apps_marketplace.go @@ -79,9 +79,9 @@ type MarketplacePlanAccount struct { // ListPlans lists all plans for your Marketplace listing. // // GitHub API docs: https://developer.github.com/v3/apps/marketplace/#list-all-plans-for-your-marketplace-listing -func (s *MarketplaceService) ListPlans(ctx context.Context, opt *ListOptions) ([]*MarketplacePlan, *Response, error) { +func (s *MarketplaceService) ListPlans(ctx context.Context, opts *ListOptions) ([]*MarketplacePlan, *Response, error) { uri := s.marketplaceURI("plans") - u, err := addOptions(uri, opt) + u, err := addOptions(uri, opts) if err != nil { return nil, nil, err } @@ -103,9 +103,9 @@ func (s *MarketplaceService) ListPlans(ctx context.Context, opt *ListOptions) ([ // ListPlanAccountsForPlan lists all GitHub accounts (user or organization) on a specific plan. // // GitHub API docs: https://developer.github.com/v3/apps/marketplace/#list-all-github-accounts-user-or-organization-on-a-specific-plan -func (s *MarketplaceService) ListPlanAccountsForPlan(ctx context.Context, planID int64, opt *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { +func (s *MarketplaceService) ListPlanAccountsForPlan(ctx context.Context, planID int64, opts *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { uri := s.marketplaceURI(fmt.Sprintf("plans/%v/accounts", planID)) - u, err := addOptions(uri, opt) + u, err := addOptions(uri, opts) if err != nil { return nil, nil, err } @@ -127,9 +127,9 @@ func (s *MarketplaceService) ListPlanAccountsForPlan(ctx context.Context, planID // ListPlanAccountsForAccount lists all GitHub accounts (user or organization) associated with an account. // // GitHub API docs: https://developer.github.com/v3/apps/marketplace/#check-if-a-github-account-is-associated-with-any-marketplace-listing -func (s *MarketplaceService) ListPlanAccountsForAccount(ctx context.Context, accountID int64, opt *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { +func (s *MarketplaceService) ListPlanAccountsForAccount(ctx context.Context, accountID int64, opts *ListOptions) ([]*MarketplacePlanAccount, *Response, error) { uri := s.marketplaceURI(fmt.Sprintf("accounts/%v", accountID)) - u, err := addOptions(uri, opt) + u, err := addOptions(uri, opts) if err != nil { return nil, nil, err } @@ -151,13 +151,13 @@ func (s *MarketplaceService) ListPlanAccountsForAccount(ctx context.Context, acc // ListMarketplacePurchasesForUser lists all GitHub marketplace purchases made by a user. // // GitHub API docs: https://developer.github.com/v3/apps/marketplace/#get-a-users-marketplace-purchases -func (s *MarketplaceService) ListMarketplacePurchasesForUser(ctx context.Context, opt *ListOptions) ([]*MarketplacePurchase, *Response, error) { +func (s *MarketplaceService) ListMarketplacePurchasesForUser(ctx context.Context, opts *ListOptions) ([]*MarketplacePurchase, *Response, error) { uri := "user/marketplace_purchases" if s.Stubbed { uri = "user/marketplace_purchases/stubbed" } - u, err := addOptions(uri, opt) + u, err := addOptions(uri, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/authorizations.go b/vendor/github.com/google/go-github/v29/github/authorizations.go index 8ad14328e9..a73c37fd07 100644 --- a/vendor/github.com/google/go-github/v29/github/authorizations.go +++ b/vendor/github.com/google/go-github/v29/github/authorizations.go @@ -137,9 +137,9 @@ func (a AuthorizationUpdateRequest) String() string { // List the authorizations for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-authorizations -func (s *AuthorizationsService) List(ctx context.Context, opt *ListOptions) ([]*Authorization, *Response, error) { +func (s *AuthorizationsService) List(ctx context.Context, opts *ListOptions) ([]*Authorization, *Response, error) { u := "authorizations" - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -343,8 +343,8 @@ func (s *AuthorizationsService) Revoke(ctx context.Context, clientID string, tok // tokens an application has generated for the user. // // GitHub API docs: https://developer.github.com/v3/oauth_authorizations/#list-your-grants -func (s *AuthorizationsService) ListGrants(ctx context.Context, opt *ListOptions) ([]*Grant, *Response, error) { - u, err := addOptions("applications/grants", opt) +func (s *AuthorizationsService) ListGrants(ctx context.Context, opts *ListOptions) ([]*Grant, *Response, error) { + u, err := addOptions("applications/grants", opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/checks.go b/vendor/github.com/google/go-github/v29/github/checks.go index 1acc26e993..55adf14ea1 100644 --- a/vendor/github.com/google/go-github/v29/github/checks.go +++ b/vendor/github.com/google/go-github/v29/github/checks.go @@ -161,9 +161,9 @@ type CheckRunAction struct { // CreateCheckRun creates a check run for repository. // // GitHub API docs: https://developer.github.com/v3/checks/runs/#create-a-check-run -func (s *ChecksService) CreateCheckRun(ctx context.Context, owner, repo string, opt CreateCheckRunOptions) (*CheckRun, *Response, error) { +func (s *ChecksService) CreateCheckRun(ctx context.Context, owner, repo string, opts CreateCheckRunOptions) (*CheckRun, *Response, error) { u := fmt.Sprintf("repos/%v/%v/check-runs", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } @@ -195,9 +195,9 @@ type UpdateCheckRunOptions struct { // UpdateCheckRun updates a check run for a specific commit in a repository. // // GitHub API docs: https://developer.github.com/v3/checks/runs/#update-a-check-run -func (s *ChecksService) UpdateCheckRun(ctx context.Context, owner, repo string, checkRunID int64, opt UpdateCheckRunOptions) (*CheckRun, *Response, error) { +func (s *ChecksService) UpdateCheckRun(ctx context.Context, owner, repo string, checkRunID int64, opts UpdateCheckRunOptions) (*CheckRun, *Response, error) { u := fmt.Sprintf("repos/%v/%v/check-runs/%v", owner, repo, checkRunID) - req, err := s.client.NewRequest("PATCH", u, opt) + req, err := s.client.NewRequest("PATCH", u, opts) if err != nil { return nil, nil, err } @@ -216,9 +216,9 @@ func (s *ChecksService) UpdateCheckRun(ctx context.Context, owner, repo string, // ListCheckRunAnnotations lists the annotations for a check run. // // GitHub API docs: https://developer.github.com/v3/checks/runs/#list-annotations-for-a-check-run -func (s *ChecksService) ListCheckRunAnnotations(ctx context.Context, owner, repo string, checkRunID int64, opt *ListOptions) ([]*CheckRunAnnotation, *Response, error) { +func (s *ChecksService) ListCheckRunAnnotations(ctx context.Context, owner, repo string, checkRunID int64, opts *ListOptions) ([]*CheckRunAnnotation, *Response, error) { u := fmt.Sprintf("repos/%v/%v/check-runs/%v/annotations", owner, repo, checkRunID) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -257,9 +257,9 @@ type ListCheckRunsResults struct { // ListCheckRunsForRef lists check runs for a specific ref. // // GitHub API docs: https://developer.github.com/v3/checks/runs/#list-check-runs-for-a-specific-ref -func (s *ChecksService) ListCheckRunsForRef(ctx context.Context, owner, repo, ref string, opt *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) { +func (s *ChecksService) ListCheckRunsForRef(ctx context.Context, owner, repo, ref string, opts *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits/%v/check-runs", owner, repo, url.QueryEscape(ref)) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -283,9 +283,9 @@ func (s *ChecksService) ListCheckRunsForRef(ctx context.Context, owner, repo, re // ListCheckRunsCheckSuite lists check runs for a check suite. // // GitHub API docs: https://developer.github.com/v3/checks/runs/#list-check-runs-in-a-check-suite -func (s *ChecksService) ListCheckRunsCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64, opt *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) { +func (s *ChecksService) ListCheckRunsCheckSuite(ctx context.Context, owner, repo string, checkSuiteID int64, opts *ListCheckRunsOptions) (*ListCheckRunsResults, *Response, error) { u := fmt.Sprintf("repos/%v/%v/check-suites/%v/check-runs", owner, repo, checkSuiteID) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -323,9 +323,9 @@ type ListCheckSuiteResults struct { // ListCheckSuitesForRef lists check suite for a specific ref. // // GitHub API docs: https://developer.github.com/v3/checks/suites/#list-check-suites-for-a-specific-ref -func (s *ChecksService) ListCheckSuitesForRef(ctx context.Context, owner, repo, ref string, opt *ListCheckSuiteOptions) (*ListCheckSuiteResults, *Response, error) { +func (s *ChecksService) ListCheckSuitesForRef(ctx context.Context, owner, repo, ref string, opts *ListCheckSuiteOptions) (*ListCheckSuiteResults, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits/%v/check-suites", owner, repo, url.QueryEscape(ref)) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -371,9 +371,9 @@ type PreferenceList struct { // SetCheckSuitePreferences changes the default automatic flow when creating check suites. // // GitHub API docs: https://developer.github.com/v3/checks/suites/#set-preferences-for-check-suites-on-a-repository -func (s *ChecksService) SetCheckSuitePreferences(ctx context.Context, owner, repo string, opt CheckSuitePreferenceOptions) (*CheckSuitePreferenceResults, *Response, error) { +func (s *ChecksService) SetCheckSuitePreferences(ctx context.Context, owner, repo string, opts CheckSuitePreferenceOptions) (*CheckSuitePreferenceResults, *Response, error) { u := fmt.Sprintf("repos/%v/%v/check-suites/preferences", owner, repo) - req, err := s.client.NewRequest("PATCH", u, opt) + req, err := s.client.NewRequest("PATCH", u, opts) if err != nil { return nil, nil, err } @@ -398,9 +398,9 @@ type CreateCheckSuiteOptions struct { // CreateCheckSuite manually creates a check suite for a repository. // // GitHub API docs: https://developer.github.com/v3/checks/suites/#create-a-check-suite -func (s *ChecksService) CreateCheckSuite(ctx context.Context, owner, repo string, opt CreateCheckSuiteOptions) (*CheckSuite, *Response, error) { +func (s *ChecksService) CreateCheckSuite(ctx context.Context, owner, repo string, opts CreateCheckSuiteOptions) (*CheckSuite, *Response, error) { u := fmt.Sprintf("repos/%v/%v/check-suites", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/event_types.go b/vendor/github.com/google/go-github/v29/github/event_types.go index df12821c43..4f537c8db9 100644 --- a/vendor/github.com/google/go-github/v29/github/event_types.go +++ b/vendor/github.com/google/go-github/v29/github/event_types.go @@ -599,6 +599,10 @@ type PullRequestEvent struct { // The following field is only present when the webhook is triggered on // a repository belonging to an organization. Organization *Organization `json:"organization,omitempty"` + + // The following fields are only populated when the Action is "synchronize". + Before *string `json:"before,omitempty"` + After *string `json:"after,omitempty"` } // PullRequestReviewEvent is triggered when a review is submitted on a pull @@ -719,6 +723,8 @@ type PushEventRepository struct { HasWiki *bool `json:"has_wiki,omitempty"` HasPages *bool `json:"has_pages,omitempty"` ForksCount *int `json:"forks_count,omitempty"` + Archived *bool `json:"archived,omitempty"` + Disabled *bool `json:"disabled,omitempty"` OpenIssuesCount *int `json:"open_issues_count,omitempty"` DefaultBranch *string `json:"default_branch,omitempty"` MasterBranch *string `json:"master_branch,omitempty"` diff --git a/vendor/github.com/google/go-github/v29/github/gists.go b/vendor/github.com/google/go-github/v29/github/gists.go index 36d9361967..0f32605542 100644 --- a/vendor/github.com/google/go-github/v29/github/gists.go +++ b/vendor/github.com/google/go-github/v29/github/gists.go @@ -97,14 +97,14 @@ type GistListOptions struct { // user. // // GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) List(ctx context.Context, user string, opt *GistListOptions) ([]*Gist, *Response, error) { +func (s *GistsService) List(ctx context.Context, user string, opts *GistListOptions) ([]*Gist, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/gists", user) } else { u = "gists" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -126,8 +126,8 @@ func (s *GistsService) List(ctx context.Context, user string, opt *GistListOptio // ListAll lists all public gists. // // GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListAll(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/public", opt) +func (s *GistsService) ListAll(ctx context.Context, opts *GistListOptions) ([]*Gist, *Response, error) { + u, err := addOptions("gists/public", opts) if err != nil { return nil, nil, err } @@ -149,8 +149,8 @@ func (s *GistsService) ListAll(ctx context.Context, opt *GistListOptions) ([]*Gi // ListStarred lists starred gists of authenticated user. // // GitHub API docs: https://developer.github.com/v3/gists/#list-gists -func (s *GistsService) ListStarred(ctx context.Context, opt *GistListOptions) ([]*Gist, *Response, error) { - u, err := addOptions("gists/starred", opt) +func (s *GistsService) ListStarred(ctx context.Context, opts *GistListOptions) ([]*Gist, *Response, error) { + u, err := addOptions("gists/starred", opts) if err != nil { return nil, nil, err } @@ -248,9 +248,9 @@ func (s *GistsService) Edit(ctx context.Context, id string, gist *Gist) (*Gist, // ListCommits lists commits of a gist. // // GitHub API docs: https://developer.github.com/v3/gists/#list-gist-commits -func (s *GistsService) ListCommits(ctx context.Context, id string, opt *ListOptions) ([]*GistCommit, *Response, error) { +func (s *GistsService) ListCommits(ctx context.Context, id string, opts *ListOptions) ([]*GistCommit, *Response, error) { u := fmt.Sprintf("gists/%v/commits", id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -341,9 +341,9 @@ func (s *GistsService) Fork(ctx context.Context, id string) (*Gist, *Response, e // ListForks lists forks of a gist. // // GitHub API docs: https://developer.github.com/v3/gists/#list-gist-forks -func (s *GistsService) ListForks(ctx context.Context, id string, opt *ListOptions) ([]*GistFork, *Response, error) { +func (s *GistsService) ListForks(ctx context.Context, id string, opts *ListOptions) ([]*GistFork, *Response, error) { u := fmt.Sprintf("gists/%v/forks", id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/gists_comments.go b/vendor/github.com/google/go-github/v29/github/gists_comments.go index d5322e3d85..33913e22fd 100644 --- a/vendor/github.com/google/go-github/v29/github/gists_comments.go +++ b/vendor/github.com/google/go-github/v29/github/gists_comments.go @@ -27,9 +27,9 @@ func (g GistComment) String() string { // ListComments lists all comments for a gist. // // GitHub API docs: https://developer.github.com/v3/gists/comments/#list-comments-on-a-gist -func (s *GistsService) ListComments(ctx context.Context, gistID string, opt *ListOptions) ([]*GistComment, *Response, error) { +func (s *GistsService) ListComments(ctx context.Context, gistID string, opts *ListOptions) ([]*GistComment, *Response, error) { u := fmt.Sprintf("gists/%v/comments", gistID) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/git_refs.go b/vendor/github.com/google/go-github/v29/github/git_refs.go index b51bcbf1de..18494dae33 100644 --- a/vendor/github.com/google/go-github/v29/github/git_refs.go +++ b/vendor/github.com/google/go-github/v29/github/git_refs.go @@ -135,14 +135,14 @@ type ReferenceListOptions struct { // ListRefs lists all refs in a repository. // // GitHub API docs: https://developer.github.com/v3/git/refs/#get-all-references -func (s *GitService) ListRefs(ctx context.Context, owner, repo string, opt *ReferenceListOptions) ([]*Reference, *Response, error) { +func (s *GitService) ListRefs(ctx context.Context, owner, repo string, opts *ReferenceListOptions) ([]*Reference, *Response, error) { var u string - if opt != nil && opt.Type != "" { - u = fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, opt.Type) + if opts != nil && opts.Type != "" { + u = fmt.Sprintf("repos/%v/%v/git/refs/%v", owner, repo, opts.Type) } else { u = fmt.Sprintf("repos/%v/%v/git/refs", owner, repo) } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/github-accessors.go b/vendor/github.com/google/go-github/v29/github/github-accessors.go index 4ff4a3f5a4..212e334b46 100644 --- a/vendor/github.com/google/go-github/v29/github/github-accessors.go +++ b/vendor/github.com/google/go-github/v29/github/github-accessors.go @@ -1940,6 +1940,14 @@ func (c *Contributor) GetLogin() string { return *c.Login } +// GetNodeID returns the NodeID field if it's non-nil, zero value otherwise. +func (c *Contributor) GetNodeID() string { + if c == nil || c.NodeID == nil { + return "" + } + return *c.NodeID +} + // GetOrganizationsURL returns the OrganizationsURL field if it's non-nil, zero value otherwise. func (c *Contributor) GetOrganizationsURL() string { if c == nil || c.OrganizationsURL == nil { @@ -7796,6 +7804,22 @@ func (p *ProjectPermissionLevel) GetUser() *User { return p.User } +// GetAllowDeletions returns the AllowDeletions field. +func (p *Protection) GetAllowDeletions() *AllowDeletions { + if p == nil { + return nil + } + return p.AllowDeletions +} + +// GetAllowForcePushes returns the AllowForcePushes field. +func (p *Protection) GetAllowForcePushes() *AllowForcePushes { + if p == nil { + return nil + } + return p.AllowForcePushes +} + // GetEnforceAdmins returns the EnforceAdmins field. func (p *Protection) GetEnforceAdmins() *AdminEnforcement { if p == nil { @@ -7820,6 +7844,14 @@ func (p *Protection) GetRequiredStatusChecks() *RequiredStatusChecks { return p.RequiredStatusChecks } +// GetRequireLinearHistory returns the RequireLinearHistory field. +func (p *Protection) GetRequireLinearHistory() *RequireLinearHistory { + if p == nil { + return nil + } + return p.RequireLinearHistory +} + // GetRestrictions returns the Restrictions field. func (p *Protection) GetRestrictions() *BranchRestrictions { if p == nil { @@ -7828,6 +7860,22 @@ func (p *Protection) GetRestrictions() *BranchRestrictions { return p.Restrictions } +// GetAllowDeletions returns the AllowDeletions field if it's non-nil, zero value otherwise. +func (p *ProtectionRequest) GetAllowDeletions() bool { + if p == nil || p.AllowDeletions == nil { + return false + } + return *p.AllowDeletions +} + +// GetAllowForcePushes returns the AllowForcePushes field if it's non-nil, zero value otherwise. +func (p *ProtectionRequest) GetAllowForcePushes() bool { + if p == nil || p.AllowForcePushes == nil { + return false + } + return *p.AllowForcePushes +} + // GetRequiredPullRequestReviews returns the RequiredPullRequestReviews field. func (p *ProtectionRequest) GetRequiredPullRequestReviews() *PullRequestReviewsEnforcementRequest { if p == nil { @@ -7844,6 +7892,14 @@ func (p *ProtectionRequest) GetRequiredStatusChecks() *RequiredStatusChecks { return p.RequiredStatusChecks } +// GetRequireLinearHistory returns the RequireLinearHistory field if it's non-nil, zero value otherwise. +func (p *ProtectionRequest) GetRequireLinearHistory() bool { + if p == nil || p.RequireLinearHistory == nil { + return false + } + return *p.RequireLinearHistory +} + // GetRestrictions returns the Restrictions field. func (p *ProtectionRequest) GetRestrictions() *BranchRestrictionsRequest { if p == nil { @@ -7876,6 +7932,22 @@ func (p *PublicEvent) GetSender() *User { return p.Sender } +// GetKey returns the Key field if it's non-nil, zero value otherwise. +func (p *PublicKey) GetKey() string { + if p == nil || p.Key == nil { + return "" + } + return *p.Key +} + +// GetKeyID returns the KeyID field if it's non-nil, zero value otherwise. +func (p *PublicKey) GetKeyID() string { + if p == nil || p.KeyID == nil { + return "" + } + return *p.KeyID +} + // GetActiveLockReason returns the ActiveLockReason field if it's non-nil, zero value otherwise. func (p *PullRequest) GetActiveLockReason() string { if p == nil || p.ActiveLockReason == nil { @@ -8492,6 +8564,14 @@ func (p *PullRequestEvent) GetAction() string { return *p.Action } +// GetAfter returns the After field if it's non-nil, zero value otherwise. +func (p *PullRequestEvent) GetAfter() string { + if p == nil || p.After == nil { + return "" + } + return *p.After +} + // GetAssignee returns the Assignee field. func (p *PullRequestEvent) GetAssignee() *User { if p == nil { @@ -8500,6 +8580,14 @@ func (p *PullRequestEvent) GetAssignee() *User { return p.Assignee } +// GetBefore returns the Before field if it's non-nil, zero value otherwise. +func (p *PullRequestEvent) GetBefore() string { + if p == nil || p.Before == nil { + return "" + } + return *p.Before +} + // GetChanges returns the Changes field. func (p *PullRequestEvent) GetChanges() *EditChange { if p == nil { @@ -8636,6 +8724,14 @@ func (p *PullRequestMergeResult) GetSHA() string { return *p.SHA } +// GetAuthorAssociation returns the AuthorAssociation field if it's non-nil, zero value otherwise. +func (p *PullRequestReview) GetAuthorAssociation() string { + if p == nil || p.AuthorAssociation == nil { + return "" + } + return *p.AuthorAssociation +} + // GetBody returns the Body field if it's non-nil, zero value otherwise. func (p *PullRequestReview) GetBody() string { if p == nil || p.Body == nil { @@ -9172,6 +9268,14 @@ func (p *PushEventRepoOwner) GetName() string { return *p.Name } +// GetArchived returns the Archived field if it's non-nil, zero value otherwise. +func (p *PushEventRepository) GetArchived() bool { + if p == nil || p.Archived == nil { + return false + } + return *p.Archived +} + // GetArchiveURL returns the ArchiveURL field if it's non-nil, zero value otherwise. func (p *PushEventRepository) GetArchiveURL() string { if p == nil || p.ArchiveURL == nil { @@ -9212,6 +9316,14 @@ func (p *PushEventRepository) GetDescription() string { return *p.Description } +// GetDisabled returns the Disabled field if it's non-nil, zero value otherwise. +func (p *PushEventRepository) GetDisabled() bool { + if p == nil || p.Disabled == nil { + return false + } + return *p.Disabled +} + // GetFork returns the Fork field if it's non-nil, zero value otherwise. func (p *PushEventRepository) GetFork() bool { if p == nil || p.Fork == nil { @@ -9916,6 +10028,14 @@ func (r *Repository) GetDefaultBranch() string { return *r.DefaultBranch } +// GetDeleteBranchOnMerge returns the DeleteBranchOnMerge field if it's non-nil, zero value otherwise. +func (r *Repository) GetDeleteBranchOnMerge() bool { + if r == nil || r.DeleteBranchOnMerge == nil { + return false + } + return *r.DeleteBranchOnMerge +} + // GetDeploymentsURL returns the DeploymentsURL field if it's non-nil, zero value otherwise. func (r *Repository) GetDeploymentsURL() string { if r == nil || r.DeploymentsURL == nil { diff --git a/vendor/github.com/google/go-github/v29/github/github.go b/vendor/github.com/google/go-github/v29/github/github.go index 3ea1f6adcd..696684b931 100644 --- a/vendor/github.com/google/go-github/v29/github/github.go +++ b/vendor/github.com/google/go-github/v29/github/github.go @@ -46,6 +46,9 @@ const ( // Media Type values to access preview APIs + // https://developer.github.com/changes/2020-01-10-revoke-installation-token/ + mediaTypeRevokeTokenPreview = "application/vnd.github.gambit-preview+json" + // https://developer.github.com/changes/2014-12-09-new-attributes-for-stars-api/ mediaTypeStarringPreview = "application/vnd.github.v3.star+json" @@ -58,9 +61,6 @@ const ( // https://developer.github.com/changes/2018-10-16-deployments-environments-states-and-auto-inactive-updates/ mediaTypeExpandDeploymentStatusPreview = "application/vnd.github.flash-preview+json" - // https://developer.github.com/changes/2016-02-19-source-import-preview-api/ - mediaTypeImportPreview = "application/vnd.github.barred-rock-preview" - // https://developer.github.com/changes/2016-05-12-reactions-api-preview/ mediaTypeReactionsPreview = "application/vnd.github.squirrel-girl-preview" @@ -135,9 +135,6 @@ const ( // https://developer.github.com/changes/2019-10-03-multi-line-comments/ mediaTypeMultiLineCommentsPreview = "application/vnd.github.comfort-fade-preview+json" - - // https://developer.github.com/v3/repos/#create-a-repository-dispatch-event - mediaTypeRepositoryDispatchPreview = "application/vnd.github.everest-preview+json" ) // A Client manages communication with the GitHub API. @@ -162,6 +159,7 @@ type Client struct { common service // Reuse a single struct instead of allocating one for each service on the heap. // Services used for talking to different parts of the GitHub API. + Actions *ActionsService Activity *ActivityService Admin *AdminService Apps *AppsService @@ -190,7 +188,7 @@ type service struct { } // ListOptions specifies the optional parameters to various List methods that -// support pagination. +// support offset pagination. type ListOptions struct { // For paginated result sets, page of results to retrieve. Page int `url:"page,omitempty"` @@ -199,6 +197,16 @@ type ListOptions struct { PerPage int `url:"per_page,omitempty"` } +// ListCursorOptions specifies the optional parameters to various List methods that +// support cursor pagination. +type ListCursorOptions struct { + // For paginated result sets, page of results to retrieve. + Page string `url:"page,omitempty"` + + // For paginated result sets, the number of results to include per page. + PerPage int `url:"per_page,omitempty"` +} + // UploadOptions specifies the parameters to methods that support uploads. type UploadOptions struct { Name string `url:"name,omitempty"` @@ -224,8 +232,8 @@ type RawOptions struct { // addOptions adds the parameters in opt as URL query parameters to s. opt // must be a struct whose fields may contain "url" tags. -func addOptions(s string, opt interface{}) (string, error) { - v := reflect.ValueOf(opt) +func addOptions(s string, opts interface{}) (string, error) { + v := reflect.ValueOf(opts) if v.Kind() == reflect.Ptr && v.IsNil() { return s, nil } @@ -235,7 +243,7 @@ func addOptions(s string, opt interface{}) (string, error) { return s, err } - qs, err := query.Values(opt) + qs, err := query.Values(opts) if err != nil { return s, err } @@ -257,6 +265,7 @@ func NewClient(httpClient *http.Client) *Client { c := &Client{client: httpClient, BaseURL: baseURL, UserAgent: userAgent, UploadURL: uploadURL} c.common.client = c + c.Actions = (*ActionsService)(&c.common) c.Activity = (*ActivityService)(&c.common) c.Admin = (*AdminService)(&c.common) c.Apps = (*AppsService)(&c.common) @@ -337,7 +346,7 @@ func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Requ var buf io.ReadWriter if body != nil { - buf = new(bytes.Buffer) + buf = &bytes.Buffer{} enc := json.NewEncoder(buf) enc.SetEscapeHTML(false) err := enc.Encode(body) @@ -398,12 +407,27 @@ type Response struct { // results. Any or all of these may be set to the zero value for // responses that are not part of a paginated set, or for which there // are no additional pages. - + // + // These fields support what is called "offset pagination" and should + // be used with the ListOptions struct. NextPage int PrevPage int FirstPage int LastPage int + // Additionally, some APIs support "cursor pagination" instead of offset. + // This means that a token points directly to the next record which + // can lead to O(1) performance compared to O(n) performance provided + // by offset pagination. + // + // For APIs that support cursor pagination (such as + // TeamsService.ListIDPGroupsInOrganization), the following field + // will be populated to point to the next page. + // + // To use this token, set ListCursorOptions.Page to this value before + // calling the endpoint again. + NextPageToken string + // Explicitly specify the Rate type so Rate's String() receiver doesn't // propagate to Response. Rate Rate @@ -448,7 +472,9 @@ func (r *Response) populatePageValues() { for _, segment := range segments[1:] { switch strings.TrimSpace(segment) { case `rel="next"`: - r.NextPage, _ = strconv.Atoi(page) + if r.NextPage, err = strconv.Atoi(page); err != nil { + r.NextPageToken = page + } case `rel="prev"`: r.PrevPage, _ = strconv.Atoi(page) case `rel="first"`: diff --git a/vendor/github.com/google/go-github/v29/github/issues.go b/vendor/github.com/google/go-github/v29/github/issues.go index b08934c3e5..63a5fde75c 100644 --- a/vendor/github.com/google/go-github/v29/github/issues.go +++ b/vendor/github.com/google/go-github/v29/github/issues.go @@ -129,27 +129,27 @@ type PullRequestLinks struct { // repositories. // // GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) List(ctx context.Context, all bool, opt *IssueListOptions) ([]*Issue, *Response, error) { +func (s *IssuesService) List(ctx context.Context, all bool, opts *IssueListOptions) ([]*Issue, *Response, error) { var u string if all { u = "issues" } else { u = "user/issues" } - return s.listIssues(ctx, u, opt) + return s.listIssues(ctx, u, opts) } // ListByOrg fetches the issues in the specified organization for the // authenticated user. // // GitHub API docs: https://developer.github.com/v3/issues/#list-issues -func (s *IssuesService) ListByOrg(ctx context.Context, org string, opt *IssueListOptions) ([]*Issue, *Response, error) { +func (s *IssuesService) ListByOrg(ctx context.Context, org string, opts *IssueListOptions) ([]*Issue, *Response, error) { u := fmt.Sprintf("orgs/%v/issues", org) - return s.listIssues(ctx, u, opt) + return s.listIssues(ctx, u, opts) } -func (s *IssuesService) listIssues(ctx context.Context, u string, opt *IssueListOptions) ([]*Issue, *Response, error) { - u, err := addOptions(u, opt) +func (s *IssuesService) listIssues(ctx context.Context, u string, opts *IssueListOptions) ([]*Issue, *Response, error) { + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -215,9 +215,9 @@ type IssueListByRepoOptions struct { // ListByRepo lists the issues for the specified repository. // // GitHub API docs: https://developer.github.com/v3/issues/#list-issues-for-a-repository -func (s *IssuesService) ListByRepo(ctx context.Context, owner string, repo string, opt *IssueListByRepoOptions) ([]*Issue, *Response, error) { +func (s *IssuesService) ListByRepo(ctx context.Context, owner string, repo string, opts *IssueListByRepoOptions) ([]*Issue, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -313,14 +313,14 @@ type LockIssueOptions struct { // Lock an issue's conversation. // // GitHub API docs: https://developer.github.com/v3/issues/#lock-an-issue -func (s *IssuesService) Lock(ctx context.Context, owner string, repo string, number int, opt *LockIssueOptions) (*Response, error) { +func (s *IssuesService) Lock(ctx context.Context, owner string, repo string, number int, opts *LockIssueOptions) (*Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/%d/lock", owner, repo, number) - req, err := s.client.NewRequest("PUT", u, opt) + req, err := s.client.NewRequest("PUT", u, opts) if err != nil { return nil, err } - if opt != nil { + if opts != nil { req.Header.Set("Accept", mediaTypeLockReasonPreview) } diff --git a/vendor/github.com/google/go-github/v29/github/issues_assignees.go b/vendor/github.com/google/go-github/v29/github/issues_assignees.go index 9cb366f50a..c09806fd62 100644 --- a/vendor/github.com/google/go-github/v29/github/issues_assignees.go +++ b/vendor/github.com/google/go-github/v29/github/issues_assignees.go @@ -14,9 +14,9 @@ import ( // which issues may be assigned. // // GitHub API docs: https://developer.github.com/v3/issues/assignees/#list-assignees -func (s *IssuesService) ListAssignees(ctx context.Context, owner, repo string, opt *ListOptions) ([]*User, *Response, error) { +func (s *IssuesService) ListAssignees(ctx context.Context, owner, repo string, opts *ListOptions) ([]*User, *Response, error) { u := fmt.Sprintf("repos/%v/%v/assignees", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/issues_comments.go b/vendor/github.com/google/go-github/v29/github/issues_comments.go index 42d6bc7889..56b24c1917 100644 --- a/vendor/github.com/google/go-github/v29/github/issues_comments.go +++ b/vendor/github.com/google/go-github/v29/github/issues_comments.go @@ -51,14 +51,14 @@ type IssueListCommentsOptions struct { // number of 0 will return all comments on all issues for the repository. // // GitHub API docs: https://developer.github.com/v3/issues/comments/#list-comments-on-an-issue -func (s *IssuesService) ListComments(ctx context.Context, owner string, repo string, number int, opt *IssueListCommentsOptions) ([]*IssueComment, *Response, error) { +func (s *IssuesService) ListComments(ctx context.Context, owner string, repo string, number int, opts *IssueListCommentsOptions) ([]*IssueComment, *Response, error) { var u string if number == 0 { u = fmt.Sprintf("repos/%v/%v/issues/comments", owner, repo) } else { u = fmt.Sprintf("repos/%v/%v/issues/%d/comments", owner, repo, number) } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/issues_events.go b/vendor/github.com/google/go-github/v29/github/issues_events.go index 4456d67e5c..fa948596a3 100644 --- a/vendor/github.com/google/go-github/v29/github/issues_events.go +++ b/vendor/github.com/google/go-github/v29/github/issues_events.go @@ -96,9 +96,9 @@ type DismissedReview struct { // ListIssueEvents lists events for the specified issue. // // GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-an-issue -func (s *IssuesService) ListIssueEvents(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*IssueEvent, *Response, error) { +func (s *IssuesService) ListIssueEvents(ctx context.Context, owner, repo string, number int, opts *ListOptions) ([]*IssueEvent, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/%v/events", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -123,9 +123,9 @@ func (s *IssuesService) ListIssueEvents(ctx context.Context, owner, repo string, // ListRepositoryEvents lists events for the specified repository. // // GitHub API docs: https://developer.github.com/v3/issues/events/#list-events-for-a-repository -func (s *IssuesService) ListRepositoryEvents(ctx context.Context, owner, repo string, opt *ListOptions) ([]*IssueEvent, *Response, error) { +func (s *IssuesService) ListRepositoryEvents(ctx context.Context, owner, repo string, opts *ListOptions) ([]*IssueEvent, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/events", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/issues_labels.go b/vendor/github.com/google/go-github/v29/github/issues_labels.go index 0771a28c8f..fa3002599a 100644 --- a/vendor/github.com/google/go-github/v29/github/issues_labels.go +++ b/vendor/github.com/google/go-github/v29/github/issues_labels.go @@ -28,9 +28,9 @@ func (l Label) String() string { // ListLabels lists all labels for a repository. // // GitHub API docs: https://developer.github.com/v3/issues/labels/#list-all-labels-for-this-repository -func (s *IssuesService) ListLabels(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Label, *Response, error) { +func (s *IssuesService) ListLabels(ctx context.Context, owner string, repo string, opts *ListOptions) ([]*Label, *Response, error) { u := fmt.Sprintf("repos/%v/%v/labels", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -121,9 +121,9 @@ func (s *IssuesService) DeleteLabel(ctx context.Context, owner string, repo stri // ListLabelsByIssue lists all labels for an issue. // // GitHub API docs: https://developer.github.com/v3/issues/labels/#list-labels-on-an-issue -func (s *IssuesService) ListLabelsByIssue(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { +func (s *IssuesService) ListLabelsByIssue(ctx context.Context, owner string, repo string, number int, opts *ListOptions) ([]*Label, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -209,9 +209,9 @@ func (s *IssuesService) RemoveLabelsForIssue(ctx context.Context, owner string, // ListLabelsForMilestone lists labels for every issue in a milestone. // // GitHub API docs: https://developer.github.com/v3/issues/labels/#get-labels-for-every-issue-in-a-milestone -func (s *IssuesService) ListLabelsForMilestone(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*Label, *Response, error) { +func (s *IssuesService) ListLabelsForMilestone(ctx context.Context, owner string, repo string, number int, opts *ListOptions) ([]*Label, *Response, error) { u := fmt.Sprintf("repos/%v/%v/milestones/%d/labels", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/issues_milestones.go b/vendor/github.com/google/go-github/v29/github/issues_milestones.go index ffe9aae14c..4e44350722 100644 --- a/vendor/github.com/google/go-github/v29/github/issues_milestones.go +++ b/vendor/github.com/google/go-github/v29/github/issues_milestones.go @@ -56,9 +56,9 @@ type MilestoneListOptions struct { // ListMilestones lists all milestones for a repository. // // GitHub API docs: https://developer.github.com/v3/issues/milestones/#list-milestones-for-a-repository -func (s *IssuesService) ListMilestones(ctx context.Context, owner string, repo string, opt *MilestoneListOptions) ([]*Milestone, *Response, error) { +func (s *IssuesService) ListMilestones(ctx context.Context, owner string, repo string, opts *MilestoneListOptions) ([]*Milestone, *Response, error) { u := fmt.Sprintf("repos/%v/%v/milestones", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/issues_timeline.go b/vendor/github.com/google/go-github/v29/github/issues_timeline.go index d0e4a3a942..58465e2228 100644 --- a/vendor/github.com/google/go-github/v29/github/issues_timeline.go +++ b/vendor/github.com/google/go-github/v29/github/issues_timeline.go @@ -132,9 +132,9 @@ type Source struct { // ListIssueTimeline lists events for the specified issue. // // GitHub API docs: https://developer.github.com/v3/issues/timeline/#list-events-for-an-issue -func (s *IssuesService) ListIssueTimeline(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Timeline, *Response, error) { +func (s *IssuesService) ListIssueTimeline(ctx context.Context, owner, repo string, number int, opts *ListOptions) ([]*Timeline, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/%v/timeline", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/migrations.go b/vendor/github.com/google/go-github/v29/github/migrations.go index ef0095e066..f4260bb77c 100644 --- a/vendor/github.com/google/go-github/v29/github/migrations.go +++ b/vendor/github.com/google/go-github/v29/github/migrations.go @@ -75,13 +75,13 @@ type startMigration struct { // repos is a slice of repository names to migrate. // // GitHub API docs: https://developer.github.com/v3/migration/migrations/#start-a-migration -func (s *MigrationService) StartMigration(ctx context.Context, org string, repos []string, opt *MigrationOptions) (*Migration, *Response, error) { +func (s *MigrationService) StartMigration(ctx context.Context, org string, repos []string, opts *MigrationOptions) (*Migration, *Response, error) { u := fmt.Sprintf("orgs/%v/migrations", org) body := &startMigration{Repositories: repos} - if opt != nil { - body.LockRepositories = Bool(opt.LockRepositories) - body.ExcludeAttachments = Bool(opt.ExcludeAttachments) + if opts != nil { + body.LockRepositories = Bool(opts.LockRepositories) + body.ExcludeAttachments = Bool(opts.ExcludeAttachments) } req, err := s.client.NewRequest("POST", u, body) diff --git a/vendor/github.com/google/go-github/v29/github/migrations_source_import.go b/vendor/github.com/google/go-github/v29/github/migrations_source_import.go index fd45e78006..080a5503f6 100644 --- a/vendor/github.com/google/go-github/v29/github/migrations_source_import.go +++ b/vendor/github.com/google/go-github/v29/github/migrations_source_import.go @@ -154,9 +154,6 @@ func (s *MigrationService) StartImport(ctx context.Context, owner, repo string, return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - out := new(Import) resp, err := s.client.Do(ctx, req, out) if err != nil { @@ -176,9 +173,6 @@ func (s *MigrationService) ImportProgress(ctx context.Context, owner, repo strin return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - out := new(Import) resp, err := s.client.Do(ctx, req, out) if err != nil { @@ -198,9 +192,6 @@ func (s *MigrationService) UpdateImport(ctx context.Context, owner, repo string, return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - out := new(Import) resp, err := s.client.Do(ctx, req, out) if err != nil { @@ -230,9 +221,6 @@ func (s *MigrationService) CommitAuthors(ctx context.Context, owner, repo string return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - var authors []*SourceImportAuthor resp, err := s.client.Do(ctx, req, &authors) if err != nil { @@ -254,9 +242,6 @@ func (s *MigrationService) MapCommitAuthor(ctx context.Context, owner, repo stri return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - out := new(SourceImportAuthor) resp, err := s.client.Do(ctx, req, out) if err != nil { @@ -278,9 +263,6 @@ func (s *MigrationService) SetLFSPreference(ctx context.Context, owner, repo str return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - out := new(Import) resp, err := s.client.Do(ctx, req, out) if err != nil { @@ -300,9 +282,6 @@ func (s *MigrationService) LargeFiles(ctx context.Context, owner, repo string) ( return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - var files []*LargeFile resp, err := s.client.Do(ctx, req, &files) if err != nil { @@ -322,8 +301,5 @@ func (s *MigrationService) CancelImport(ctx context.Context, owner, repo string) return nil, err } - // TODO: remove custom Accept header when this API fully launches - req.Header.Set("Accept", mediaTypeImportPreview) - return s.client.Do(ctx, req, nil) } diff --git a/vendor/github.com/google/go-github/v29/github/migrations_user.go b/vendor/github.com/google/go-github/v29/github/migrations_user.go index d45555f216..5b58d29354 100644 --- a/vendor/github.com/google/go-github/v29/github/migrations_user.go +++ b/vendor/github.com/google/go-github/v29/github/migrations_user.go @@ -68,13 +68,13 @@ type startUserMigration struct { // repos is a slice of repository names to migrate. // // GitHub API docs: https://developer.github.com/v3/migrations/users/#start-a-user-migration -func (s *MigrationService) StartUserMigration(ctx context.Context, repos []string, opt *UserMigrationOptions) (*UserMigration, *Response, error) { +func (s *MigrationService) StartUserMigration(ctx context.Context, repos []string, opts *UserMigrationOptions) (*UserMigration, *Response, error) { u := "user/migrations" body := &startUserMigration{Repositories: repos} - if opt != nil { - body.LockRepositories = Bool(opt.LockRepositories) - body.ExcludeAttachments = Bool(opt.ExcludeAttachments) + if opts != nil { + body.LockRepositories = Bool(opts.LockRepositories) + body.ExcludeAttachments = Bool(opts.ExcludeAttachments) } req, err := s.client.NewRequest("POST", u, body) diff --git a/vendor/github.com/google/go-github/v29/github/misc.go b/vendor/github.com/google/go-github/v29/github/misc.go index e9b0ea22a6..139a0dc66a 100644 --- a/vendor/github.com/google/go-github/v29/github/misc.go +++ b/vendor/github.com/google/go-github/v29/github/misc.go @@ -40,14 +40,14 @@ type markdownRequest struct { // Markdown renders an arbitrary Markdown document. // // GitHub API docs: https://developer.github.com/v3/markdown/ -func (c *Client) Markdown(ctx context.Context, text string, opt *MarkdownOptions) (string, *Response, error) { +func (c *Client) Markdown(ctx context.Context, text string, opts *MarkdownOptions) (string, *Response, error) { request := &markdownRequest{Text: String(text)} - if opt != nil { - if opt.Mode != "" { - request.Mode = String(opt.Mode) + if opts != nil { + if opts.Mode != "" { + request.Mode = String(opts.Mode) } - if opt.Context != "" { - request.Context = String(opt.Context) + if opts.Context != "" { + request.Context = String(opts.Context) } } diff --git a/vendor/github.com/google/go-github/v29/github/orgs.go b/vendor/github.com/google/go-github/v29/github/orgs.go index bae67dad58..3c87ec84d4 100644 --- a/vendor/github.com/google/go-github/v29/github/orgs.go +++ b/vendor/github.com/google/go-github/v29/github/orgs.go @@ -122,8 +122,8 @@ type OrganizationsListOptions struct { // as the opts.Since parameter for the next call. // // GitHub API docs: https://developer.github.com/v3/orgs/#list-all-organizations -func (s *OrganizationsService) ListAll(ctx context.Context, opt *OrganizationsListOptions) ([]*Organization, *Response, error) { - u, err := addOptions("organizations", opt) +func (s *OrganizationsService) ListAll(ctx context.Context, opts *OrganizationsListOptions) ([]*Organization, *Response, error) { + u, err := addOptions("organizations", opts) if err != nil { return nil, nil, err } @@ -145,14 +145,14 @@ func (s *OrganizationsService) ListAll(ctx context.Context, opt *OrganizationsLi // organizations for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/orgs/#list-user-organizations -func (s *OrganizationsService) List(ctx context.Context, user string, opt *ListOptions) ([]*Organization, *Response, error) { +func (s *OrganizationsService) List(ctx context.Context, user string, opts *ListOptions) ([]*Organization, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/orgs", user) } else { u = "user/orgs" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -237,10 +237,10 @@ func (s *OrganizationsService) Edit(ctx context.Context, name string, org *Organ // ListInstallations lists installations for an organization. // // GitHub API docs: https://developer.github.com/v3/orgs/#list-installations-for-an-organization -func (s *OrganizationsService) ListInstallations(ctx context.Context, org string, opt *ListOptions) (*OrganizationInstallations, *Response, error) { +func (s *OrganizationsService) ListInstallations(ctx context.Context, org string, opts *ListOptions) (*OrganizationInstallations, *Response, error) { u := fmt.Sprintf("orgs/%v/installations", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/orgs_hooks.go b/vendor/github.com/google/go-github/v29/github/orgs_hooks.go index 5357eb8784..0913fb83da 100644 --- a/vendor/github.com/google/go-github/v29/github/orgs_hooks.go +++ b/vendor/github.com/google/go-github/v29/github/orgs_hooks.go @@ -13,9 +13,9 @@ import ( // ListHooks lists all Hooks for the specified organization. // // GitHub API docs: https://developer.github.com/v3/orgs/hooks/#list-hooks -func (s *OrganizationsService) ListHooks(ctx context.Context, org string, opt *ListOptions) ([]*Hook, *Response, error) { +func (s *OrganizationsService) ListHooks(ctx context.Context, org string, opts *ListOptions) ([]*Hook, *Response, error) { u := fmt.Sprintf("orgs/%v/hooks", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/orgs_members.go b/vendor/github.com/google/go-github/v29/github/orgs_members.go index a2fc9265df..6b96d05f67 100644 --- a/vendor/github.com/google/go-github/v29/github/orgs_members.go +++ b/vendor/github.com/google/go-github/v29/github/orgs_members.go @@ -72,14 +72,14 @@ type ListMembersOptions struct { // public members, otherwise it will only return public members. // // GitHub API docs: https://developer.github.com/v3/orgs/members/#members-list -func (s *OrganizationsService) ListMembers(ctx context.Context, org string, opt *ListMembersOptions) ([]*User, *Response, error) { +func (s *OrganizationsService) ListMembers(ctx context.Context, org string, opts *ListMembersOptions) ([]*User, *Response, error) { var u string - if opt != nil && opt.PublicOnly { + if opts != nil && opts.PublicOnly { u = fmt.Sprintf("orgs/%v/public_members", org) } else { u = fmt.Sprintf("orgs/%v/members", org) } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -181,9 +181,9 @@ type ListOrgMembershipsOptions struct { // ListOrgMemberships lists the organization memberships for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/orgs/members/#list-your-organization-memberships -func (s *OrganizationsService) ListOrgMemberships(ctx context.Context, opt *ListOrgMembershipsOptions) ([]*Membership, *Response, error) { +func (s *OrganizationsService) ListOrgMemberships(ctx context.Context, opts *ListOrgMembershipsOptions) ([]*Membership, *Response, error) { u := "user/memberships/orgs" - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -278,9 +278,9 @@ func (s *OrganizationsService) RemoveOrgMembership(ctx context.Context, user, or // ListPendingOrgInvitations returns a list of pending invitations. // // GitHub API docs: https://developer.github.com/v3/orgs/members/#list-pending-organization-invitations -func (s *OrganizationsService) ListPendingOrgInvitations(ctx context.Context, org string, opt *ListOptions) ([]*Invitation, *Response, error) { +func (s *OrganizationsService) ListPendingOrgInvitations(ctx context.Context, org string, opts *ListOptions) ([]*Invitation, *Response, error) { u := fmt.Sprintf("orgs/%v/invitations", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -323,10 +323,10 @@ type CreateOrgInvitationOptions struct { // the authenticated user must be an organization owner. // // https://developer.github.com/v3/orgs/members/#create-organization-invitation -func (s *OrganizationsService) CreateOrgInvitation(ctx context.Context, org string, opt *CreateOrgInvitationOptions) (*Invitation, *Response, error) { +func (s *OrganizationsService) CreateOrgInvitation(ctx context.Context, org string, opts *CreateOrgInvitationOptions) (*Invitation, *Response, error) { u := fmt.Sprintf("orgs/%v/invitations", org) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } @@ -343,9 +343,9 @@ func (s *OrganizationsService) CreateOrgInvitation(ctx context.Context, org stri // the authenticated user must be an organization owner. // // GitHub API docs: https://developer.github.com/v3/orgs/members/#list-organization-invitation-teams -func (s *OrganizationsService) ListOrgInvitationTeams(ctx context.Context, org, invitationID string, opt *ListOptions) ([]*Team, *Response, error) { +func (s *OrganizationsService) ListOrgInvitationTeams(ctx context.Context, org, invitationID string, opts *ListOptions) ([]*Team, *Response, error) { u := fmt.Sprintf("orgs/%v/invitations/%v/teams", org, invitationID) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/orgs_outside_collaborators.go b/vendor/github.com/google/go-github/v29/github/orgs_outside_collaborators.go index 85ffd05f61..dde8e0b03a 100644 --- a/vendor/github.com/google/go-github/v29/github/orgs_outside_collaborators.go +++ b/vendor/github.com/google/go-github/v29/github/orgs_outside_collaborators.go @@ -28,9 +28,9 @@ type ListOutsideCollaboratorsOptions struct { // Preview features are not supported for production use. // // GitHub API docs: https://developer.github.com/v3/orgs/outside_collaborators/#list-outside-collaborators -func (s *OrganizationsService) ListOutsideCollaborators(ctx context.Context, org string, opt *ListOutsideCollaboratorsOptions) ([]*User, *Response, error) { +func (s *OrganizationsService) ListOutsideCollaborators(ctx context.Context, org string, opts *ListOutsideCollaboratorsOptions) ([]*User, *Response, error) { u := fmt.Sprintf("orgs/%v/outside_collaborators", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/orgs_projects.go b/vendor/github.com/google/go-github/v29/github/orgs_projects.go index e57cba9782..cc3ed3b1bb 100644 --- a/vendor/github.com/google/go-github/v29/github/orgs_projects.go +++ b/vendor/github.com/google/go-github/v29/github/orgs_projects.go @@ -13,9 +13,9 @@ import ( // ListProjects lists the projects for an organization. // // GitHub API docs: https://developer.github.com/v3/projects/#list-organization-projects -func (s *OrganizationsService) ListProjects(ctx context.Context, org string, opt *ProjectListOptions) ([]*Project, *Response, error) { +func (s *OrganizationsService) ListProjects(ctx context.Context, org string, opts *ProjectListOptions) ([]*Project, *Response, error) { u := fmt.Sprintf("orgs/%v/projects", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -40,9 +40,9 @@ func (s *OrganizationsService) ListProjects(ctx context.Context, org string, opt // CreateProject creates a GitHub Project for the specified organization. // // GitHub API docs: https://developer.github.com/v3/projects/#create-an-organization-project -func (s *OrganizationsService) CreateProject(ctx context.Context, org string, opt *ProjectOptions) (*Project, *Response, error) { +func (s *OrganizationsService) CreateProject(ctx context.Context, org string, opts *ProjectOptions) (*Project, *Response, error) { u := fmt.Sprintf("orgs/%v/projects", org) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/orgs_users_blocking.go b/vendor/github.com/google/go-github/v29/github/orgs_users_blocking.go index b1aecf4453..bf48716d73 100644 --- a/vendor/github.com/google/go-github/v29/github/orgs_users_blocking.go +++ b/vendor/github.com/google/go-github/v29/github/orgs_users_blocking.go @@ -13,9 +13,9 @@ import ( // ListBlockedUsers lists all the users blocked by an organization. // // GitHub API docs: https://developer.github.com/v3/orgs/blocking/#list-blocked-users -func (s *OrganizationsService) ListBlockedUsers(ctx context.Context, org string, opt *ListOptions) ([]*User, *Response, error) { +func (s *OrganizationsService) ListBlockedUsers(ctx context.Context, org string, opts *ListOptions) ([]*User, *Response, error) { u := fmt.Sprintf("orgs/%v/blocks", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/projects.go b/vendor/github.com/google/go-github/v29/github/projects.go index 1e9620dfd9..e11d74a559 100644 --- a/vendor/github.com/google/go-github/v29/github/projects.go +++ b/vendor/github.com/google/go-github/v29/github/projects.go @@ -89,9 +89,9 @@ type ProjectOptions struct { // UpdateProject updates a repository project. // // GitHub API docs: https://developer.github.com/v3/projects/#update-a-project -func (s *ProjectsService) UpdateProject(ctx context.Context, id int64, opt *ProjectOptions) (*Project, *Response, error) { +func (s *ProjectsService) UpdateProject(ctx context.Context, id int64, opts *ProjectOptions) (*Project, *Response, error) { u := fmt.Sprintf("projects/%v", id) - req, err := s.client.NewRequest("PATCH", u, opt) + req, err := s.client.NewRequest("PATCH", u, opts) if err != nil { return nil, nil, err } @@ -141,9 +141,9 @@ type ProjectColumn struct { // ListProjectColumns lists the columns of a GitHub Project for a repo. // // GitHub API docs: https://developer.github.com/v3/projects/columns/#list-project-columns -func (s *ProjectsService) ListProjectColumns(ctx context.Context, projectID int64, opt *ListOptions) ([]*ProjectColumn, *Response, error) { +func (s *ProjectsService) ListProjectColumns(ctx context.Context, projectID int64, opts *ListOptions) ([]*ProjectColumn, *Response, error) { u := fmt.Sprintf("projects/%v/columns", projectID) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -198,9 +198,9 @@ type ProjectColumnOptions struct { // CreateProjectColumn creates a column for the specified (by number) project. // // GitHub API docs: https://developer.github.com/v3/projects/columns/#create-a-project-column -func (s *ProjectsService) CreateProjectColumn(ctx context.Context, projectID int64, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { +func (s *ProjectsService) CreateProjectColumn(ctx context.Context, projectID int64, opts *ProjectColumnOptions) (*ProjectColumn, *Response, error) { u := fmt.Sprintf("projects/%v/columns", projectID) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } @@ -220,9 +220,9 @@ func (s *ProjectsService) CreateProjectColumn(ctx context.Context, projectID int // UpdateProjectColumn updates a column of a GitHub Project. // // GitHub API docs: https://developer.github.com/v3/projects/columns/#update-a-project-column -func (s *ProjectsService) UpdateProjectColumn(ctx context.Context, columnID int64, opt *ProjectColumnOptions) (*ProjectColumn, *Response, error) { +func (s *ProjectsService) UpdateProjectColumn(ctx context.Context, columnID int64, opts *ProjectColumnOptions) (*ProjectColumn, *Response, error) { u := fmt.Sprintf("projects/columns/%v", columnID) - req, err := s.client.NewRequest("PATCH", u, opt) + req, err := s.client.NewRequest("PATCH", u, opts) if err != nil { return nil, nil, err } @@ -266,9 +266,9 @@ type ProjectColumnMoveOptions struct { // MoveProjectColumn moves a column within a GitHub Project. // // GitHub API docs: https://developer.github.com/v3/projects/columns/#move-a-project-column -func (s *ProjectsService) MoveProjectColumn(ctx context.Context, columnID int64, opt *ProjectColumnMoveOptions) (*Response, error) { +func (s *ProjectsService) MoveProjectColumn(ctx context.Context, columnID int64, opts *ProjectColumnMoveOptions) (*Response, error) { u := fmt.Sprintf("projects/columns/%v/moves", columnID) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, err } @@ -317,9 +317,9 @@ type ProjectCardListOptions struct { // ListProjectCards lists the cards in a column of a GitHub Project. // // GitHub API docs: https://developer.github.com/v3/projects/cards/#list-project-cards -func (s *ProjectsService) ListProjectCards(ctx context.Context, columnID int64, opt *ProjectCardListOptions) ([]*ProjectCard, *Response, error) { +func (s *ProjectsService) ListProjectCards(ctx context.Context, columnID int64, opts *ProjectCardListOptions) ([]*ProjectCard, *Response, error) { u := fmt.Sprintf("projects/columns/%v/cards", columnID) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -382,9 +382,9 @@ type ProjectCardOptions struct { // CreateProjectCard creates a card in the specified column of a GitHub Project. // // GitHub API docs: https://developer.github.com/v3/projects/cards/#create-a-project-card -func (s *ProjectsService) CreateProjectCard(ctx context.Context, columnID int64, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { +func (s *ProjectsService) CreateProjectCard(ctx context.Context, columnID int64, opts *ProjectCardOptions) (*ProjectCard, *Response, error) { u := fmt.Sprintf("projects/columns/%v/cards", columnID) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } @@ -404,9 +404,9 @@ func (s *ProjectsService) CreateProjectCard(ctx context.Context, columnID int64, // UpdateProjectCard updates a card of a GitHub Project. // // GitHub API docs: https://developer.github.com/v3/projects/cards/#update-a-project-card -func (s *ProjectsService) UpdateProjectCard(ctx context.Context, cardID int64, opt *ProjectCardOptions) (*ProjectCard, *Response, error) { +func (s *ProjectsService) UpdateProjectCard(ctx context.Context, cardID int64, opts *ProjectCardOptions) (*ProjectCard, *Response, error) { u := fmt.Sprintf("projects/columns/cards/%v", cardID) - req, err := s.client.NewRequest("PATCH", u, opt) + req, err := s.client.NewRequest("PATCH", u, opts) if err != nil { return nil, nil, err } @@ -454,9 +454,9 @@ type ProjectCardMoveOptions struct { // MoveProjectCard moves a card within a GitHub Project. // // GitHub API docs: https://developer.github.com/v3/projects/cards/#move-a-project-card -func (s *ProjectsService) MoveProjectCard(ctx context.Context, cardID int64, opt *ProjectCardMoveOptions) (*Response, error) { +func (s *ProjectsService) MoveProjectCard(ctx context.Context, cardID int64, opts *ProjectCardMoveOptions) (*Response, error) { u := fmt.Sprintf("projects/columns/cards/%v/moves", cardID) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, err } @@ -484,9 +484,9 @@ type ProjectCollaboratorOptions struct { // their permission level. You must be an organization owner or a project admin to add a collaborator. // // GitHub API docs: https://developer.github.com/v3/projects/collaborators/#add-user-as-a-collaborator -func (s *ProjectsService) AddProjectCollaborator(ctx context.Context, id int64, username string, opt *ProjectCollaboratorOptions) (*Response, error) { +func (s *ProjectsService) AddProjectCollaborator(ctx context.Context, id int64, username string, opts *ProjectCollaboratorOptions) (*Response, error) { u := fmt.Sprintf("projects/%v/collaborators/%v", id, username) - req, err := s.client.NewRequest("PUT", u, opt) + req, err := s.client.NewRequest("PUT", u, opts) if err != nil { return nil, err } @@ -537,9 +537,9 @@ type ListCollaboratorOptions struct { // organization owner or a project admin to list collaborators. // // GitHub API docs: https://developer.github.com/v3/projects/collaborators/#list-collaborators -func (s *ProjectsService) ListProjectCollaborators(ctx context.Context, id int64, opt *ListCollaboratorOptions) ([]*User, *Response, error) { +func (s *ProjectsService) ListProjectCollaborators(ctx context.Context, id int64, opts *ListCollaboratorOptions) ([]*User, *Response, error) { u := fmt.Sprintf("projects/%v/collaborators", id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/pulls.go b/vendor/github.com/google/go-github/v29/github/pulls.go index 867455aeaf..bd799cede1 100644 --- a/vendor/github.com/google/go-github/v29/github/pulls.go +++ b/vendor/github.com/google/go-github/v29/github/pulls.go @@ -136,9 +136,9 @@ type PullRequestListOptions struct { // List the pull requests for the specified repository. // // GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests -func (s *PullRequestsService) List(ctx context.Context, owner string, repo string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error) { +func (s *PullRequestsService) List(ctx context.Context, owner string, repo string, opts *PullRequestListOptions) ([]*PullRequest, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -166,9 +166,9 @@ func (s *PullRequestsService) List(ctx context.Context, owner string, repo strin // The results will include open and closed pull requests. // // GitHub API docs: https://developer.github.com/v3/repos/commits/#list-pull-requests-associated-with-commit -func (s *PullRequestsService) ListPullRequestsWithCommit(ctx context.Context, owner, repo, sha string, opt *PullRequestListOptions) ([]*PullRequest, *Response, error) { +func (s *PullRequestsService) ListPullRequestsWithCommit(ctx context.Context, owner, repo, sha string, opts *PullRequestListOptions) ([]*PullRequest, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits/%v/pulls", owner, repo, sha) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -214,20 +214,20 @@ func (s *PullRequestsService) Get(ctx context.Context, owner string, repo string } // GetRaw gets a single pull request in raw (diff or patch) format. -func (s *PullRequestsService) GetRaw(ctx context.Context, owner string, repo string, number int, opt RawOptions) (string, *Response, error) { +func (s *PullRequestsService) GetRaw(ctx context.Context, owner string, repo string, number int, opts RawOptions) (string, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d", owner, repo, number) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return "", nil, err } - switch opt.Type { + switch opts.Type { case Diff: req.Header.Set("Accept", mediaTypeV3Diff) case Patch: req.Header.Set("Accept", mediaTypeV3Patch) default: - return "", nil, fmt.Errorf("unsupported raw type %d", opt.Type) + return "", nil, fmt.Errorf("unsupported raw type %d", opts.Type) } var buf bytes.Buffer @@ -372,9 +372,9 @@ func (s *PullRequestsService) Edit(ctx context.Context, owner string, repo strin // ListCommits lists the commits in a pull request. // // GitHub API docs: https://developer.github.com/v3/pulls/#list-commits-on-a-pull-request -func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*RepositoryCommit, *Response, error) { +func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, repo string, number int, opts *ListOptions) ([]*RepositoryCommit, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/commits", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -396,9 +396,9 @@ func (s *PullRequestsService) ListCommits(ctx context.Context, owner string, rep // ListFiles lists the files in a pull request. // // GitHub API docs: https://developer.github.com/v3/pulls/#list-pull-requests-files -func (s *PullRequestsService) ListFiles(ctx context.Context, owner string, repo string, number int, opt *ListOptions) ([]*CommitFile, *Response, error) { +func (s *PullRequestsService) ListFiles(ctx context.Context, owner string, repo string, number int, opts *ListOptions) ([]*CommitFile, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/files", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/pulls_comments.go b/vendor/github.com/google/go-github/v29/github/pulls_comments.go index 3372e3383e..88fb209b6f 100644 --- a/vendor/github.com/google/go-github/v29/github/pulls_comments.go +++ b/vendor/github.com/google/go-github/v29/github/pulls_comments.go @@ -67,14 +67,14 @@ type PullRequestListCommentsOptions struct { // the repository. // // GitHub API docs: https://developer.github.com/v3/pulls/comments/#list-comments-on-a-pull-request -func (s *PullRequestsService) ListComments(ctx context.Context, owner string, repo string, number int, opt *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error) { +func (s *PullRequestsService) ListComments(ctx context.Context, owner string, repo string, number int, opts *PullRequestListCommentsOptions) ([]*PullRequestComment, *Response, error) { var u string if number == 0 { u = fmt.Sprintf("repos/%v/%v/pulls/comments", owner, repo) } else { u = fmt.Sprintf("repos/%v/%v/pulls/%d/comments", owner, repo, number) } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/pulls_reviewers.go b/vendor/github.com/google/go-github/v29/github/pulls_reviewers.go index beae953c4c..368f9680a8 100644 --- a/vendor/github.com/google/go-github/v29/github/pulls_reviewers.go +++ b/vendor/github.com/google/go-github/v29/github/pulls_reviewers.go @@ -45,9 +45,9 @@ func (s *PullRequestsService) RequestReviewers(ctx context.Context, owner, repo // ListReviewers lists reviewers whose reviews have been requested on the specified pull request. // // GitHub API docs: https://developer.github.com/v3/pulls/review_requests/#list-review-requests -func (s *PullRequestsService) ListReviewers(ctx context.Context, owner, repo string, number int, opt *ListOptions) (*Reviewers, *Response, error) { +func (s *PullRequestsService) ListReviewers(ctx context.Context, owner, repo string, number int, opts *ListOptions) (*Reviewers, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/requested_reviewers", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/pulls_reviews.go b/vendor/github.com/google/go-github/v29/github/pulls_reviews.go index 88b82982f6..5bceb61c4c 100644 --- a/vendor/github.com/google/go-github/v29/github/pulls_reviews.go +++ b/vendor/github.com/google/go-github/v29/github/pulls_reviews.go @@ -22,6 +22,9 @@ type PullRequestReview struct { HTMLURL *string `json:"html_url,omitempty"` PullRequestURL *string `json:"pull_request_url,omitempty"` State *string `json:"state,omitempty"` + // AuthorAssociation is the comment author's relationship to the issue's repository. + // Possible values are "COLLABORATOR", "CONTRIBUTOR", "FIRST_TIMER", "FIRST_TIME_CONTRIBUTOR", "MEMBER", "OWNER", or "NONE". + AuthorAssociation *string `json:"author_association,omitempty"` } func (p PullRequestReview) String() string { @@ -68,9 +71,9 @@ func (r PullRequestReviewDismissalRequest) String() string { // Read more about it here - https://github.com/google/go-github/issues/540 // // GitHub API docs: https://developer.github.com/v3/pulls/reviews/#list-reviews-on-a-pull-request -func (s *PullRequestsService) ListReviews(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*PullRequestReview, *Response, error) { +func (s *PullRequestsService) ListReviews(ctx context.Context, owner, repo string, number int, opts *ListOptions) ([]*PullRequestReview, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -144,9 +147,9 @@ func (s *PullRequestsService) DeletePendingReview(ctx context.Context, owner, re // Read more about it here - https://github.com/google/go-github/issues/540 // // GitHub API docs: https://developer.github.com/v3/pulls/reviews/#get-comments-for-a-single-review -func (s *PullRequestsService) ListReviewComments(ctx context.Context, owner, repo string, number int, reviewID int64, opt *ListOptions) ([]*PullRequestComment, *Response, error) { +func (s *PullRequestsService) ListReviewComments(ctx context.Context, owner, repo string, number int, reviewID int64, opts *ListOptions) ([]*PullRequestComment, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/%d/reviews/%d/comments", owner, repo, number, reviewID) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/reactions.go b/vendor/github.com/google/go-github/v29/github/reactions.go index 1935ce1117..43c863af61 100644 --- a/vendor/github.com/google/go-github/v29/github/reactions.go +++ b/vendor/github.com/google/go-github/v29/github/reactions.go @@ -58,9 +58,9 @@ type ListCommentReactionOptions struct { // ListCommentReactions lists the reactions for a commit comment. // // GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-commit-comment -func (s *ReactionsService) ListCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListCommentReactionOptions) ([]*Reaction, *Response, error) { +func (s *ReactionsService) ListCommentReactions(ctx context.Context, owner, repo string, id int64, opts *ListCommentReactionOptions) ([]*Reaction, *Response, error) { u := fmt.Sprintf("repos/%v/%v/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -112,9 +112,9 @@ func (s ReactionsService) CreateCommentReaction(ctx context.Context, owner, repo // ListIssueReactions lists the reactions for an issue. // // GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue -func (s *ReactionsService) ListIssueReactions(ctx context.Context, owner, repo string, number int, opt *ListOptions) ([]*Reaction, *Response, error) { +func (s *ReactionsService) ListIssueReactions(ctx context.Context, owner, repo string, number int, opts *ListOptions) ([]*Reaction, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/%v/reactions", owner, repo, number) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -166,9 +166,9 @@ func (s ReactionsService) CreateIssueReaction(ctx context.Context, owner, repo s // ListIssueCommentReactions lists the reactions for an issue comment. // // GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListIssueCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { +func (s *ReactionsService) ListIssueCommentReactions(ctx context.Context, owner, repo string, id int64, opts *ListOptions) ([]*Reaction, *Response, error) { u := fmt.Sprintf("repos/%v/%v/issues/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -220,9 +220,9 @@ func (s ReactionsService) CreateIssueCommentReaction(ctx context.Context, owner, // ListPullRequestCommentReactions lists the reactions for a pull request review comment. // // GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-an-issue-comment -func (s *ReactionsService) ListPullRequestCommentReactions(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*Reaction, *Response, error) { +func (s *ReactionsService) ListPullRequestCommentReactions(ctx context.Context, owner, repo string, id int64, opts *ListOptions) ([]*Reaction, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pulls/comments/%v/reactions", owner, repo, id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -274,9 +274,9 @@ func (s ReactionsService) CreatePullRequestCommentReaction(ctx context.Context, // ListTeamDiscussionReactions lists the reactions for a team discussion. // // GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion -func (s *ReactionsService) ListTeamDiscussionReactions(ctx context.Context, teamID int64, discussionNumber int, opt *ListOptions) ([]*Reaction, *Response, error) { +func (s *ReactionsService) ListTeamDiscussionReactions(ctx context.Context, teamID int64, discussionNumber int, opts *ListOptions) ([]*Reaction, *Response, error) { u := fmt.Sprintf("teams/%v/discussions/%v/reactions", teamID, discussionNumber) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -324,9 +324,9 @@ func (s *ReactionsService) CreateTeamDiscussionReaction(ctx context.Context, tea // ListTeamDiscussionCommentReactions lists the reactions for a team discussion comment. // // GitHub API docs: https://developer.github.com/v3/reactions/#list-reactions-for-a-team-discussion-comment -func (s *ReactionsService) ListTeamDiscussionCommentReactions(ctx context.Context, teamID int64, discussionNumber, commentNumber int, opt *ListOptions) ([]*Reaction, *Response, error) { +func (s *ReactionsService) ListTeamDiscussionCommentReactions(ctx context.Context, teamID int64, discussionNumber, commentNumber int, opts *ListOptions) ([]*Reaction, *Response, error) { u := fmt.Sprintf("teams/%v/discussions/%v/comments/%v/reactions", teamID, discussionNumber, commentNumber) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos.go b/vendor/github.com/google/go-github/v29/github/repos.go index c695d8c0bb..5aa56006ee 100644 --- a/vendor/github.com/google/go-github/v29/github/repos.go +++ b/vendor/github.com/google/go-github/v29/github/repos.go @@ -20,46 +20,47 @@ type RepositoriesService service // Repository represents a GitHub repository. type Repository struct { - ID *int64 `json:"id,omitempty"` - NodeID *string `json:"node_id,omitempty"` - Owner *User `json:"owner,omitempty"` - Name *string `json:"name,omitempty"` - FullName *string `json:"full_name,omitempty"` - Description *string `json:"description,omitempty"` - Homepage *string `json:"homepage,omitempty"` - CodeOfConduct *CodeOfConduct `json:"code_of_conduct,omitempty"` - DefaultBranch *string `json:"default_branch,omitempty"` - MasterBranch *string `json:"master_branch,omitempty"` - CreatedAt *Timestamp `json:"created_at,omitempty"` - PushedAt *Timestamp `json:"pushed_at,omitempty"` - UpdatedAt *Timestamp `json:"updated_at,omitempty"` - HTMLURL *string `json:"html_url,omitempty"` - CloneURL *string `json:"clone_url,omitempty"` - GitURL *string `json:"git_url,omitempty"` - MirrorURL *string `json:"mirror_url,omitempty"` - SSHURL *string `json:"ssh_url,omitempty"` - SVNURL *string `json:"svn_url,omitempty"` - Language *string `json:"language,omitempty"` - Fork *bool `json:"fork,omitempty"` - ForksCount *int `json:"forks_count,omitempty"` - NetworkCount *int `json:"network_count,omitempty"` - OpenIssuesCount *int `json:"open_issues_count,omitempty"` - StargazersCount *int `json:"stargazers_count,omitempty"` - SubscribersCount *int `json:"subscribers_count,omitempty"` - WatchersCount *int `json:"watchers_count,omitempty"` - Size *int `json:"size,omitempty"` - AutoInit *bool `json:"auto_init,omitempty"` - Parent *Repository `json:"parent,omitempty"` - Source *Repository `json:"source,omitempty"` - TemplateRepository *Repository `json:"template_repository,omitempty"` - Organization *Organization `json:"organization,omitempty"` - Permissions *map[string]bool `json:"permissions,omitempty"` - AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` - AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` - AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` - Topics []string `json:"topics,omitempty"` - Archived *bool `json:"archived,omitempty"` - Disabled *bool `json:"disabled,omitempty"` + ID *int64 `json:"id,omitempty"` + NodeID *string `json:"node_id,omitempty"` + Owner *User `json:"owner,omitempty"` + Name *string `json:"name,omitempty"` + FullName *string `json:"full_name,omitempty"` + Description *string `json:"description,omitempty"` + Homepage *string `json:"homepage,omitempty"` + CodeOfConduct *CodeOfConduct `json:"code_of_conduct,omitempty"` + DefaultBranch *string `json:"default_branch,omitempty"` + MasterBranch *string `json:"master_branch,omitempty"` + CreatedAt *Timestamp `json:"created_at,omitempty"` + PushedAt *Timestamp `json:"pushed_at,omitempty"` + UpdatedAt *Timestamp `json:"updated_at,omitempty"` + HTMLURL *string `json:"html_url,omitempty"` + CloneURL *string `json:"clone_url,omitempty"` + GitURL *string `json:"git_url,omitempty"` + MirrorURL *string `json:"mirror_url,omitempty"` + SSHURL *string `json:"ssh_url,omitempty"` + SVNURL *string `json:"svn_url,omitempty"` + Language *string `json:"language,omitempty"` + Fork *bool `json:"fork,omitempty"` + ForksCount *int `json:"forks_count,omitempty"` + NetworkCount *int `json:"network_count,omitempty"` + OpenIssuesCount *int `json:"open_issues_count,omitempty"` + StargazersCount *int `json:"stargazers_count,omitempty"` + SubscribersCount *int `json:"subscribers_count,omitempty"` + WatchersCount *int `json:"watchers_count,omitempty"` + Size *int `json:"size,omitempty"` + AutoInit *bool `json:"auto_init,omitempty"` + Parent *Repository `json:"parent,omitempty"` + Source *Repository `json:"source,omitempty"` + TemplateRepository *Repository `json:"template_repository,omitempty"` + Organization *Organization `json:"organization,omitempty"` + Permissions *map[string]bool `json:"permissions,omitempty"` + AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` + AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` + AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` + DeleteBranchOnMerge *bool `json:"delete_branch_on_merge,omitempty"` + Topics []string `json:"topics,omitempty"` + Archived *bool `json:"archived,omitempty"` + Disabled *bool `json:"disabled,omitempty"` // Only provided when using RepositoriesService.Get while in preview License *License `json:"license,omitempty"` @@ -177,14 +178,14 @@ type RepositoryListOptions struct { // repositories for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/repos/#list-user-repositories -func (s *RepositoriesService) List(ctx context.Context, user string, opt *RepositoryListOptions) ([]*Repository, *Response, error) { +func (s *RepositoriesService) List(ctx context.Context, user string, opts *RepositoryListOptions) ([]*Repository, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/repos", user) } else { u = "user/repos" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -228,9 +229,9 @@ type RepositoryListByOrgOptions struct { // ListByOrg lists the repositories for an organization. // // GitHub API docs: https://developer.github.com/v3/repos/#list-organization-repositories -func (s *RepositoriesService) ListByOrg(ctx context.Context, org string, opt *RepositoryListByOrgOptions) ([]*Repository, *Response, error) { +func (s *RepositoriesService) ListByOrg(ctx context.Context, org string, opts *RepositoryListByOrgOptions) ([]*Repository, *Response, error) { u := fmt.Sprintf("orgs/%v/repos", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -263,8 +264,8 @@ type RepositoryListAllOptions struct { // ListAll lists all GitHub repositories in the order that they were created. // // GitHub API docs: https://developer.github.com/v3/repos/#list-all-public-repositories -func (s *RepositoriesService) ListAll(ctx context.Context, opt *RepositoryListAllOptions) ([]*Repository, *Response, error) { - u, err := addOptions("repositories", opt) +func (s *RepositoriesService) ListAll(ctx context.Context, opts *RepositoryListAllOptions) ([]*Repository, *Response, error) { + u, err := addOptions("repositories", opts) if err != nil { return nil, nil, err } @@ -303,12 +304,13 @@ type createRepoRequest struct { // Creating an organization repository. Required for non-owners. TeamID *int64 `json:"team_id,omitempty"` - AutoInit *bool `json:"auto_init,omitempty"` - GitignoreTemplate *string `json:"gitignore_template,omitempty"` - LicenseTemplate *string `json:"license_template,omitempty"` - AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` - AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` - AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` + AutoInit *bool `json:"auto_init,omitempty"` + GitignoreTemplate *string `json:"gitignore_template,omitempty"` + LicenseTemplate *string `json:"license_template,omitempty"` + AllowSquashMerge *bool `json:"allow_squash_merge,omitempty"` + AllowMergeCommit *bool `json:"allow_merge_commit,omitempty"` + AllowRebaseMerge *bool `json:"allow_rebase_merge,omitempty"` + DeleteBranchOnMerge *bool `json:"delete_branch_on_merge,omitempty"` } // Create a new repository. If an organization is specified, the new @@ -328,21 +330,22 @@ func (s *RepositoriesService) Create(ctx context.Context, org string, repo *Repo } repoReq := &createRepoRequest{ - Name: repo.Name, - Description: repo.Description, - Homepage: repo.Homepage, - Private: repo.Private, - HasIssues: repo.HasIssues, - HasProjects: repo.HasProjects, - HasWiki: repo.HasWiki, - IsTemplate: repo.IsTemplate, - TeamID: repo.TeamID, - AutoInit: repo.AutoInit, - GitignoreTemplate: repo.GitignoreTemplate, - LicenseTemplate: repo.LicenseTemplate, - AllowSquashMerge: repo.AllowSquashMerge, - AllowMergeCommit: repo.AllowMergeCommit, - AllowRebaseMerge: repo.AllowRebaseMerge, + Name: repo.Name, + Description: repo.Description, + Homepage: repo.Homepage, + Private: repo.Private, + HasIssues: repo.HasIssues, + HasProjects: repo.HasProjects, + HasWiki: repo.HasWiki, + IsTemplate: repo.IsTemplate, + TeamID: repo.TeamID, + AutoInit: repo.AutoInit, + GitignoreTemplate: repo.GitignoreTemplate, + LicenseTemplate: repo.LicenseTemplate, + AllowSquashMerge: repo.AllowSquashMerge, + AllowMergeCommit: repo.AllowMergeCommit, + AllowRebaseMerge: repo.AllowRebaseMerge, + DeleteBranchOnMerge: repo.DeleteBranchOnMerge, } req, err := s.client.NewRequest("POST", u, repoReq) @@ -493,6 +496,7 @@ func (s *RepositoriesService) Delete(ctx context.Context, owner, repo string) (* type Contributor struct { Login *string `json:"login,omitempty"` ID *int64 `json:"id,omitempty"` + NodeID *string `json:"node_id,omitempty"` AvatarURL *string `json:"avatar_url,omitempty"` GravatarID *string `json:"gravatar_id,omitempty"` URL *string `json:"url,omitempty"` @@ -611,9 +615,9 @@ func (s *RepositoriesService) DisableAutomatedSecurityFixes(ctx context.Context, // ListContributors lists contributors for a repository. // // GitHub API docs: https://developer.github.com/v3/repos/#list-contributors -func (s *RepositoriesService) ListContributors(ctx context.Context, owner string, repository string, opt *ListContributorsOptions) ([]*Contributor, *Response, error) { +func (s *RepositoriesService) ListContributors(ctx context.Context, owner string, repository string, opts *ListContributorsOptions) ([]*Contributor, *Response, error) { u := fmt.Sprintf("repos/%v/%v/contributors", owner, repository) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -661,9 +665,9 @@ func (s *RepositoriesService) ListLanguages(ctx context.Context, owner string, r // ListTeams lists the teams for the specified repository. // // GitHub API docs: https://developer.github.com/v3/repos/#list-teams -func (s *RepositoriesService) ListTeams(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Team, *Response, error) { +func (s *RepositoriesService) ListTeams(ctx context.Context, owner string, repo string, opts *ListOptions) ([]*Team, *Response, error) { u := fmt.Sprintf("repos/%v/%v/teams", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -693,9 +697,9 @@ type RepositoryTag struct { // ListTags lists tags for the specified repository. // // GitHub API docs: https://developer.github.com/v3/repos/#list-tags -func (s *RepositoriesService) ListTags(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*RepositoryTag, *Response, error) { +func (s *RepositoriesService) ListTags(ctx context.Context, owner string, repo string, opts *ListOptions) ([]*RepositoryTag, *Response, error) { u := fmt.Sprintf("repos/%v/%v/tags", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -727,6 +731,9 @@ type Protection struct { RequiredPullRequestReviews *PullRequestReviewsEnforcement `json:"required_pull_request_reviews"` EnforceAdmins *AdminEnforcement `json:"enforce_admins"` Restrictions *BranchRestrictions `json:"restrictions"` + RequireLinearHistory *RequireLinearHistory `json:"required_linear_history"` + AllowForcePushes *AllowForcePushes `json:"allow_force_pushes"` + AllowDeletions *AllowDeletions `json:"allow_deletions"` } // ProtectionRequest represents a request to create/edit a branch's protection. @@ -735,6 +742,12 @@ type ProtectionRequest struct { RequiredPullRequestReviews *PullRequestReviewsEnforcementRequest `json:"required_pull_request_reviews"` EnforceAdmins bool `json:"enforce_admins"` Restrictions *BranchRestrictionsRequest `json:"restrictions"` + // Enforces a linear commit Git history, which prevents anyone from pushing merge commits to a branch. + RequireLinearHistory *bool `json:"required_linear_history,omitempty"` + // Permits force pushes to the protected branch by anyone with write access to the repository. + AllowForcePushes *bool `json:"allow_force_pushes,omitempty"` + // Allows deletion of the protected branch by anyone with write access to the repository. + AllowDeletions *bool `json:"allow_deletions,omitempty"` } // RequiredStatusChecks represents the protection status of a individual branch. @@ -797,6 +810,21 @@ type PullRequestReviewsEnforcementUpdate struct { RequiredApprovingReviewCount int `json:"required_approving_review_count"` } +// RequireLinearHistory represents the configuration to enfore branches with no merge commit. +type RequireLinearHistory struct { + Enabled bool `json:"enabled"` +} + +// AllowDeletions represents the configuration to accept deletion of protected branches. +type AllowDeletions struct { + Enabled bool `json:"enabled"` +} + +// AllowForcePushes represents the configuration to accept forced pushes on protected branches. +type AllowForcePushes struct { + Enabled bool `json:"enabled"` +} + // AdminEnforcement represents the configuration to enforce required status checks for repository administrators. type AdminEnforcement struct { URL *string `json:"url,omitempty"` @@ -857,9 +885,9 @@ type SignaturesProtectedBranch struct { // ListBranches lists branches for the specified repository. // // GitHub API docs: https://developer.github.com/v3/repos/#list-branches -func (s *RepositoriesService) ListBranches(ctx context.Context, owner string, repo string, opt *BranchListOptions) ([]*Branch, *Response, error) { +func (s *RepositoriesService) ListBranches(ctx context.Context, owner string, repo string, opts *BranchListOptions) ([]*Branch, *Response, error) { u := fmt.Sprintf("repos/%v/%v/branches", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -1449,9 +1477,6 @@ func (s *RepositoriesService) Dispatch(ctx context.Context, owner, repo string, return nil, nil, err } - // TODO: remove custom Accept header when this API fully launches. - req.Header.Set("Accept", mediaTypeRepositoryDispatchPreview) - r := new(Repository) resp, err := s.client.Do(ctx, req, r) if err != nil { diff --git a/vendor/github.com/google/go-github/v29/github/repos_collaborators.go b/vendor/github.com/google/go-github/v29/github/repos_collaborators.go index 8254ac0661..bdfe04f13f 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_collaborators.go +++ b/vendor/github.com/google/go-github/v29/github/repos_collaborators.go @@ -42,9 +42,9 @@ type CollaboratorInvitation struct { // ListCollaborators lists the GitHub users that have access to the repository. // // GitHub API docs: https://developer.github.com/v3/repos/collaborators/#list-collaborators -func (s *RepositoriesService) ListCollaborators(ctx context.Context, owner, repo string, opt *ListCollaboratorsOptions) ([]*User, *Response, error) { +func (s *RepositoriesService) ListCollaborators(ctx context.Context, owner, repo string, opts *ListCollaboratorsOptions) ([]*User, *Response, error) { u := fmt.Sprintf("repos/%v/%v/collaborators", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -124,9 +124,9 @@ type RepositoryAddCollaboratorOptions struct { // to become a collaborator to the given repo. // // GitHub API docs: https://developer.github.com/v3/repos/collaborators/#add-user-as-a-collaborator -func (s *RepositoriesService) AddCollaborator(ctx context.Context, owner, repo, user string, opt *RepositoryAddCollaboratorOptions) (*CollaboratorInvitation, *Response, error) { +func (s *RepositoriesService) AddCollaborator(ctx context.Context, owner, repo, user string, opts *RepositoryAddCollaboratorOptions) (*CollaboratorInvitation, *Response, error) { u := fmt.Sprintf("repos/%v/%v/collaborators/%v", owner, repo, user) - req, err := s.client.NewRequest("PUT", u, opt) + req, err := s.client.NewRequest("PUT", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_comments.go b/vendor/github.com/google/go-github/v29/github/repos_comments.go index 380ca3d3b4..891825f965 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_comments.go +++ b/vendor/github.com/google/go-github/v29/github/repos_comments.go @@ -37,9 +37,9 @@ func (r RepositoryComment) String() string { // ListComments lists all the comments for the repository. // // GitHub API docs: https://developer.github.com/v3/repos/comments/#list-commit-comments-for-a-repository -func (s *RepositoriesService) ListComments(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { +func (s *RepositoriesService) ListComments(ctx context.Context, owner, repo string, opts *ListOptions) ([]*RepositoryComment, *Response, error) { u := fmt.Sprintf("repos/%v/%v/comments", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -64,9 +64,9 @@ func (s *RepositoriesService) ListComments(ctx context.Context, owner, repo stri // ListCommitComments lists all the comments for a given commit SHA. // // GitHub API docs: https://developer.github.com/v3/repos/comments/#list-comments-for-a-single-commit -func (s *RepositoriesService) ListCommitComments(ctx context.Context, owner, repo, sha string, opt *ListOptions) ([]*RepositoryComment, *Response, error) { +func (s *RepositoriesService) ListCommitComments(ctx context.Context, owner, repo, sha string, opts *ListOptions) ([]*RepositoryComment, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits/%v/comments", owner, repo, sha) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_commits.go b/vendor/github.com/google/go-github/v29/github/repos_commits.go index f28ae9c6ab..a4ff2be4b9 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_commits.go +++ b/vendor/github.com/google/go-github/v29/github/repos_commits.go @@ -125,9 +125,9 @@ type BranchCommit struct { // ListCommits lists the commits of a repository. // // GitHub API docs: https://developer.github.com/v3/repos/commits/#list -func (s *RepositoriesService) ListCommits(ctx context.Context, owner, repo string, opt *CommitsListOptions) ([]*RepositoryCommit, *Response, error) { +func (s *RepositoriesService) ListCommits(ctx context.Context, owner, repo string, opts *CommitsListOptions) ([]*RepositoryCommit, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -168,20 +168,20 @@ func (s *RepositoriesService) GetCommit(ctx context.Context, owner, repo, sha st } // GetCommitRaw fetches the specified commit in raw (diff or patch) format. -func (s *RepositoriesService) GetCommitRaw(ctx context.Context, owner string, repo string, sha string, opt RawOptions) (string, *Response, error) { +func (s *RepositoriesService) GetCommitRaw(ctx context.Context, owner string, repo string, sha string, opts RawOptions) (string, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits/%v", owner, repo, sha) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return "", nil, err } - switch opt.Type { + switch opts.Type { case Diff: req.Header.Set("Accept", mediaTypeV3Diff) case Patch: req.Header.Set("Accept", mediaTypeV3Patch) default: - return "", nil, fmt.Errorf("unsupported raw type %d", opt.Type) + return "", nil, fmt.Errorf("unsupported raw type %d", opts.Type) } var buf bytes.Buffer diff --git a/vendor/github.com/google/go-github/v29/github/repos_contents.go b/vendor/github.com/google/go-github/v29/github/repos_contents.go index eed0420ab8..ede93e4f4b 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_contents.go +++ b/vendor/github.com/google/go-github/v29/github/repos_contents.go @@ -12,6 +12,7 @@ import ( "context" "encoding/base64" "encoding/json" + "errors" "fmt" "io" "net/http" @@ -76,6 +77,9 @@ func (r *RepositoryContent) GetContent() (string, error) { switch encoding { case "base64": + if r.Content == nil { + return "", errors.New("malformed response: base64 encoding of null content") + } c, err := base64.StdEncoding.DecodeString(*r.Content) return string(c), err case "": @@ -91,9 +95,9 @@ func (r *RepositoryContent) GetContent() (string, error) { // GetReadme gets the Readme file for the repository. // // GitHub API docs: https://developer.github.com/v3/repos/contents/#get-the-readme -func (s *RepositoriesService) GetReadme(ctx context.Context, owner, repo string, opt *RepositoryContentGetOptions) (*RepositoryContent, *Response, error) { +func (s *RepositoriesService) GetReadme(ctx context.Context, owner, repo string, opts *RepositoryContentGetOptions) (*RepositoryContent, *Response, error) { u := fmt.Sprintf("repos/%v/%v/readme", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -113,10 +117,10 @@ func (s *RepositoriesService) GetReadme(ctx context.Context, owner, repo string, // specified file. This function will work with files of any size, as opposed // to GetContents which is limited to 1 Mb files. It is the caller's // responsibility to close the ReadCloser. -func (s *RepositoriesService) DownloadContents(ctx context.Context, owner, repo, filepath string, opt *RepositoryContentGetOptions) (io.ReadCloser, error) { +func (s *RepositoriesService) DownloadContents(ctx context.Context, owner, repo, filepath string, opts *RepositoryContentGetOptions) (io.ReadCloser, error) { dir := path.Dir(filepath) filename := path.Base(filepath) - _, dirContents, _, err := s.GetContents(ctx, owner, repo, dir, opt) + _, dirContents, _, err := s.GetContents(ctx, owner, repo, dir, opts) if err != nil { return nil, err } @@ -143,10 +147,10 @@ func (s *RepositoriesService) DownloadContents(ctx context.Context, owner, repo, // value and the other will be nil. // // GitHub API docs: https://developer.github.com/v3/repos/contents/#get-contents -func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path string, opt *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error) { +func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path string, opts *RepositoryContentGetOptions) (fileContent *RepositoryContent, directoryContent []*RepositoryContent, resp *Response, err error) { escapedPath := (&url.URL{Path: path}).String() u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, escapedPath) - u, err = addOptions(u, opt) + u, err = addOptions(u, opts) if err != nil { return nil, nil, nil, err } @@ -174,9 +178,9 @@ func (s *RepositoriesService) GetContents(ctx context.Context, owner, repo, path // the commit and file metadata. // // GitHub API docs: https://developer.github.com/v3/repos/contents/#create-a-file -func (s *RepositoriesService) CreateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { +func (s *RepositoriesService) CreateFile(ctx context.Context, owner, repo, path string, opts *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) + req, err := s.client.NewRequest("PUT", u, opts) if err != nil { return nil, nil, err } @@ -192,9 +196,9 @@ func (s *RepositoriesService) CreateFile(ctx context.Context, owner, repo, path // commit and file metadata. Requires the blob SHA of the file being updated. // // GitHub API docs: https://developer.github.com/v3/repos/contents/#update-a-file -func (s *RepositoriesService) UpdateFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { +func (s *RepositoriesService) UpdateFile(ctx context.Context, owner, repo, path string, opts *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("PUT", u, opt) + req, err := s.client.NewRequest("PUT", u, opts) if err != nil { return nil, nil, err } @@ -210,9 +214,9 @@ func (s *RepositoriesService) UpdateFile(ctx context.Context, owner, repo, path // Requires the blob SHA of the file to be deleted. // // GitHub API docs: https://developer.github.com/v3/repos/contents/#delete-a-file -func (s *RepositoriesService) DeleteFile(ctx context.Context, owner, repo, path string, opt *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { +func (s *RepositoriesService) DeleteFile(ctx context.Context, owner, repo, path string, opts *RepositoryContentFileOptions) (*RepositoryContentResponse, *Response, error) { u := fmt.Sprintf("repos/%s/%s/contents/%s", owner, repo, path) - req, err := s.client.NewRequest("DELETE", u, opt) + req, err := s.client.NewRequest("DELETE", u, opts) if err != nil { return nil, nil, err } @@ -240,10 +244,10 @@ const ( // or github.Zipball constant. // // GitHub API docs: https://developer.github.com/v3/repos/contents/#get-archive-link -func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo string, archiveformat archiveFormat, opt *RepositoryContentGetOptions, followRedirects bool) (*url.URL, *Response, error) { +func (s *RepositoriesService) GetArchiveLink(ctx context.Context, owner, repo string, archiveformat archiveFormat, opts *RepositoryContentGetOptions, followRedirects bool) (*url.URL, *Response, error) { u := fmt.Sprintf("repos/%s/%s/%s", owner, repo, archiveformat) - if opt != nil && opt.Ref != "" { - u += fmt.Sprintf("/%s", opt.Ref) + if opts != nil && opts.Ref != "" { + u += fmt.Sprintf("/%s", opts.Ref) } resp, err := s.getArchiveLinkFromURL(ctx, u, followRedirects) if err != nil { diff --git a/vendor/github.com/google/go-github/v29/github/repos_deployments.go b/vendor/github.com/google/go-github/v29/github/repos_deployments.go index 6453345e04..ace1778e9e 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_deployments.go +++ b/vendor/github.com/google/go-github/v29/github/repos_deployments.go @@ -64,9 +64,9 @@ type DeploymentsListOptions struct { // ListDeployments lists the deployments of a repository. // // GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployments -func (s *RepositoriesService) ListDeployments(ctx context.Context, owner, repo string, opt *DeploymentsListOptions) ([]*Deployment, *Response, error) { +func (s *RepositoriesService) ListDeployments(ctx context.Context, owner, repo string, opts *DeploymentsListOptions) ([]*Deployment, *Response, error) { u := fmt.Sprintf("repos/%v/%v/deployments", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -159,9 +159,9 @@ type DeploymentStatusRequest struct { // ListDeploymentStatuses lists the statuses of a given deployment of a repository. // // GitHub API docs: https://developer.github.com/v3/repos/deployments/#list-deployment-statuses -func (s *RepositoriesService) ListDeploymentStatuses(ctx context.Context, owner, repo string, deployment int64, opt *ListOptions) ([]*DeploymentStatus, *Response, error) { +func (s *RepositoriesService) ListDeploymentStatuses(ctx context.Context, owner, repo string, deployment int64, opts *ListOptions) ([]*DeploymentStatus, *Response, error) { u := fmt.Sprintf("repos/%v/%v/deployments/%v/statuses", owner, repo, deployment) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_forks.go b/vendor/github.com/google/go-github/v29/github/repos_forks.go index bfff27bb95..5973587dd5 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_forks.go +++ b/vendor/github.com/google/go-github/v29/github/repos_forks.go @@ -25,9 +25,9 @@ type RepositoryListForksOptions struct { // ListForks lists the forks of the specified repository. // // GitHub API docs: https://developer.github.com/v3/repos/forks/#list-forks -func (s *RepositoriesService) ListForks(ctx context.Context, owner, repo string, opt *RepositoryListForksOptions) ([]*Repository, *Response, error) { +func (s *RepositoriesService) ListForks(ctx context.Context, owner, repo string, opts *RepositoryListForksOptions) ([]*Repository, *Response, error) { u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -66,9 +66,9 @@ type RepositoryCreateForkOptions struct { // in a successful request. // // GitHub API docs: https://developer.github.com/v3/repos/forks/#create-a-fork -func (s *RepositoriesService) CreateFork(ctx context.Context, owner, repo string, opt *RepositoryCreateForkOptions) (*Repository, *Response, error) { +func (s *RepositoriesService) CreateFork(ctx context.Context, owner, repo string, opts *RepositoryCreateForkOptions) (*Repository, *Response, error) { u := fmt.Sprintf("repos/%v/%v/forks", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_hooks.go b/vendor/github.com/google/go-github/v29/github/repos_hooks.go index 7674947df3..8672822384 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_hooks.go +++ b/vendor/github.com/google/go-github/v29/github/repos_hooks.go @@ -132,9 +132,9 @@ func (s *RepositoriesService) CreateHook(ctx context.Context, owner, repo string // ListHooks lists all Hooks for the specified repository. // // GitHub API docs: https://developer.github.com/v3/repos/hooks/#list -func (s *RepositoriesService) ListHooks(ctx context.Context, owner, repo string, opt *ListOptions) ([]*Hook, *Response, error) { +func (s *RepositoriesService) ListHooks(ctx context.Context, owner, repo string, opts *ListOptions) ([]*Hook, *Response, error) { u := fmt.Sprintf("repos/%v/%v/hooks", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_invitations.go b/vendor/github.com/google/go-github/v29/github/repos_invitations.go index b88e9359f3..6e76f2d579 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_invitations.go +++ b/vendor/github.com/google/go-github/v29/github/repos_invitations.go @@ -28,9 +28,9 @@ type RepositoryInvitation struct { // ListInvitations lists all currently-open repository invitations. // // GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-invitations-for-a-repository -func (s *RepositoriesService) ListInvitations(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { +func (s *RepositoriesService) ListInvitations(ctx context.Context, owner, repo string, opts *ListOptions) ([]*RepositoryInvitation, *Response, error) { u := fmt.Sprintf("repos/%v/%v/invitations", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_keys.go b/vendor/github.com/google/go-github/v29/github/repos_keys.go index b484f84446..64ee7422a0 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_keys.go +++ b/vendor/github.com/google/go-github/v29/github/repos_keys.go @@ -15,9 +15,9 @@ import ( // ListKeys lists the deploy keys for a repository. // // GitHub API docs: https://developer.github.com/v3/repos/keys/#list -func (s *RepositoriesService) ListKeys(ctx context.Context, owner string, repo string, opt *ListOptions) ([]*Key, *Response, error) { +func (s *RepositoriesService) ListKeys(ctx context.Context, owner string, repo string, opts *ListOptions) ([]*Key, *Response, error) { u := fmt.Sprintf("repos/%v/%v/keys", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_pages.go b/vendor/github.com/google/go-github/v29/github/repos_pages.go index 7eb32a9df0..ff8d2d55b9 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_pages.go +++ b/vendor/github.com/google/go-github/v29/github/repos_pages.go @@ -43,12 +43,23 @@ type PagesBuild struct { UpdatedAt *Timestamp `json:"updated_at,omitempty"` } +// createPagesRequest is a subset of Pages and is used internally +// by EnablePages to pass only the known fields for the endpoint. +type createPagesRequest struct { + Source *PagesSource `json:"source,omitempty"` +} + // EnablePages enables GitHub Pages for the named repo. // // GitHub API docs: https://developer.github.com/v3/repos/pages/#enable-a-pages-site -func (s *RepositoriesService) EnablePages(ctx context.Context, owner, repo string) (*Pages, *Response, error) { +func (s *RepositoriesService) EnablePages(ctx context.Context, owner, repo string, pages *Pages) (*Pages, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pages", owner, repo) - req, err := s.client.NewRequest("POST", u, nil) + + pagesReq := &createPagesRequest{ + Source: pages.Source, + } + + req, err := s.client.NewRequest("POST", u, pagesReq) if err != nil { return nil, nil, err } @@ -102,9 +113,9 @@ func (s *RepositoriesService) GetPagesInfo(ctx context.Context, owner, repo stri // ListPagesBuilds lists the builds for a GitHub Pages site. // // GitHub API docs: https://developer.github.com/v3/repos/pages/#list-pages-builds -func (s *RepositoriesService) ListPagesBuilds(ctx context.Context, owner, repo string, opt *ListOptions) ([]*PagesBuild, *Response, error) { +func (s *RepositoriesService) ListPagesBuilds(ctx context.Context, owner, repo string, opts *ListOptions) ([]*PagesBuild, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pages/builds", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_prereceive_hooks.go b/vendor/github.com/google/go-github/v29/github/repos_prereceive_hooks.go index cab09f7479..1ce6478d33 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_prereceive_hooks.go +++ b/vendor/github.com/google/go-github/v29/github/repos_prereceive_hooks.go @@ -25,9 +25,9 @@ func (p PreReceiveHook) String() string { // ListPreReceiveHooks lists all pre-receive hooks for the specified repository. // // GitHub API docs: https://developer.github.com/enterprise/2.13/v3/repos/pre_receive_hooks/#list-pre-receive-hooks -func (s *RepositoriesService) ListPreReceiveHooks(ctx context.Context, owner, repo string, opt *ListOptions) ([]*PreReceiveHook, *Response, error) { +func (s *RepositoriesService) ListPreReceiveHooks(ctx context.Context, owner, repo string, opts *ListOptions) ([]*PreReceiveHook, *Response, error) { u := fmt.Sprintf("repos/%v/%v/pre-receive-hooks", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_projects.go b/vendor/github.com/google/go-github/v29/github/repos_projects.go index d6486d293c..442f5232a3 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_projects.go +++ b/vendor/github.com/google/go-github/v29/github/repos_projects.go @@ -22,9 +22,9 @@ type ProjectListOptions struct { // ListProjects lists the projects for a repo. // // GitHub API docs: https://developer.github.com/v3/projects/#list-repository-projects -func (s *RepositoriesService) ListProjects(ctx context.Context, owner, repo string, opt *ProjectListOptions) ([]*Project, *Response, error) { +func (s *RepositoriesService) ListProjects(ctx context.Context, owner, repo string, opts *ProjectListOptions) ([]*Project, *Response, error) { u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -49,9 +49,9 @@ func (s *RepositoriesService) ListProjects(ctx context.Context, owner, repo stri // CreateProject creates a GitHub Project for the specified repository. // // GitHub API docs: https://developer.github.com/v3/projects/#create-a-repository-project -func (s *RepositoriesService) CreateProject(ctx context.Context, owner, repo string, opt *ProjectOptions) (*Project, *Response, error) { +func (s *RepositoriesService) CreateProject(ctx context.Context, owner, repo string, opts *ProjectOptions) (*Project, *Response, error) { u := fmt.Sprintf("repos/%v/%v/projects", owner, repo) - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_releases.go b/vendor/github.com/google/go-github/v29/github/repos_releases.go index 5c0a1cea84..645f980a53 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_releases.go +++ b/vendor/github.com/google/go-github/v29/github/repos_releases.go @@ -69,9 +69,9 @@ func (r ReleaseAsset) String() string { // ListReleases lists the releases for a repository. // // GitHub API docs: https://developer.github.com/v3/repos/releases/#list-releases-for-a-repository -func (s *RepositoriesService) ListReleases(ctx context.Context, owner, repo string, opt *ListOptions) ([]*RepositoryRelease, *Response, error) { +func (s *RepositoriesService) ListReleases(ctx context.Context, owner, repo string, opts *ListOptions) ([]*RepositoryRelease, *Response, error) { u := fmt.Sprintf("repos/%s/%s/releases", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -220,9 +220,9 @@ func (s *RepositoriesService) DeleteRelease(ctx context.Context, owner, repo str // ListReleaseAssets lists the release's assets. // // GitHub API docs: https://developer.github.com/v3/repos/releases/#list-assets-for-a-release -func (s *RepositoriesService) ListReleaseAssets(ctx context.Context, owner, repo string, id int64, opt *ListOptions) ([]*ReleaseAsset, *Response, error) { +func (s *RepositoriesService) ListReleaseAssets(ctx context.Context, owner, repo string, id int64, opts *ListOptions) ([]*ReleaseAsset, *Response, error) { u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -266,8 +266,13 @@ func (s *RepositoriesService) GetReleaseAsset(ctx context.Context, owner, repo s // If a redirect is returned, the redirect URL will be returned as a string instead // of the io.ReadCloser. Exactly one of rc and redirectURL will be zero. // +// followRedirectsClient can be passed to download the asset from a redirected +// location. Passing http.DefaultClient is recommended unless special circumstances +// exist, but it's possible to pass any http.Client. If nil is passed the +// redirectURL will be returned instead. +// // GitHub API docs: https://developer.github.com/v3/repos/releases/#get-a-single-release-asset -func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, repo string, id int64) (rc io.ReadCloser, redirectURL string, err error) { +func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, repo string, id int64, followRedirectsClient *http.Client) (rc io.ReadCloser, redirectURL string, err error) { u := fmt.Sprintf("repos/%s/%s/releases/assets/%d", owner, repo, id) req, err := s.client.NewRequest("GET", u, nil) @@ -293,6 +298,10 @@ func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, r if !strings.Contains(err.Error(), "disable redirect") { return nil, "", err } + if followRedirectsClient != nil { + rc, err := s.downloadReleaseAssetFromURL(ctx, followRedirectsClient, loc) + return rc, "", err + } return nil, loc, nil // Intentionally return no error with valid redirect URL. } @@ -304,6 +313,24 @@ func (s *RepositoriesService) DownloadReleaseAsset(ctx context.Context, owner, r return resp.Body, "", nil } +func (s *RepositoriesService) downloadReleaseAssetFromURL(ctx context.Context, followRedirectsClient *http.Client, url string) (rc io.ReadCloser, err error) { + req, err := http.NewRequest("GET", url, nil) + if err != nil { + return nil, err + } + req = withContext(ctx, req) + req.Header.Set("Accept", "*/*") + resp, err := followRedirectsClient.Do(req) + if err != nil { + return nil, err + } + if err := CheckResponse(resp); err != nil { + resp.Body.Close() + return nil, err + } + return resp.Body, nil +} + // EditReleaseAsset edits a repository release asset. // // GitHub API docs: https://developer.github.com/v3/repos/releases/#edit-a-release-asset @@ -340,9 +367,9 @@ func (s *RepositoriesService) DeleteReleaseAsset(ctx context.Context, owner, rep // To upload assets that cannot be represented by an os.File, call NewUploadRequest directly. // // GitHub API docs: https://developer.github.com/v3/repos/releases/#upload-a-release-asset -func (s *RepositoriesService) UploadReleaseAsset(ctx context.Context, owner, repo string, id int64, opt *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error) { +func (s *RepositoriesService) UploadReleaseAsset(ctx context.Context, owner, repo string, id int64, opts *UploadOptions, file *os.File) (*ReleaseAsset, *Response, error) { u := fmt.Sprintf("repos/%s/%s/releases/%d/assets", owner, repo, id) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -356,8 +383,8 @@ func (s *RepositoriesService) UploadReleaseAsset(ctx context.Context, owner, rep } mediaType := mime.TypeByExtension(filepath.Ext(file.Name())) - if opt.MediaType != "" { - mediaType = opt.MediaType + if opts.MediaType != "" { + mediaType = opts.MediaType } req, err := s.client.NewUploadRequest(u, file, stat.Size(), mediaType) diff --git a/vendor/github.com/google/go-github/v29/github/repos_statuses.go b/vendor/github.com/google/go-github/v29/github/repos_statuses.go index 6d6a0d2fe4..5543265880 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_statuses.go +++ b/vendor/github.com/google/go-github/v29/github/repos_statuses.go @@ -45,9 +45,9 @@ func (r RepoStatus) String() string { // reference. ref can be a SHA, a branch name, or a tag name. // // GitHub API docs: https://developer.github.com/v3/repos/statuses/#list-statuses-for-a-specific-ref -func (s *RepositoriesService) ListStatuses(ctx context.Context, owner, repo, ref string, opt *ListOptions) ([]*RepoStatus, *Response, error) { +func (s *RepositoriesService) ListStatuses(ctx context.Context, owner, repo, ref string, opts *ListOptions) ([]*RepoStatus, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits/%v/statuses", owner, repo, url.QueryEscape(ref)) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -109,9 +109,9 @@ func (s CombinedStatus) String() string { // reference. ref can be a SHA, a branch name, or a tag name. // // GitHub API docs: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref -func (s *RepositoriesService) GetCombinedStatus(ctx context.Context, owner, repo, ref string, opt *ListOptions) (*CombinedStatus, *Response, error) { +func (s *RepositoriesService) GetCombinedStatus(ctx context.Context, owner, repo, ref string, opts *ListOptions) (*CombinedStatus, *Response, error) { u := fmt.Sprintf("repos/%v/%v/commits/%v/status", owner, repo, url.QueryEscape(ref)) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/repos_traffic.go b/vendor/github.com/google/go-github/v29/github/repos_traffic.go index fb1c97648a..e7ee18849a 100644 --- a/vendor/github.com/google/go-github/v29/github/repos_traffic.go +++ b/vendor/github.com/google/go-github/v29/github/repos_traffic.go @@ -95,9 +95,9 @@ func (s *RepositoriesService) ListTrafficPaths(ctx context.Context, owner, repo // ListTrafficViews get total number of views for the last 14 days and breaks it down either per day or week. // // GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficViews(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficViews, *Response, error) { +func (s *RepositoriesService) ListTrafficViews(ctx context.Context, owner, repo string, opts *TrafficBreakdownOptions) (*TrafficViews, *Response, error) { u := fmt.Sprintf("repos/%v/%v/traffic/views", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -119,9 +119,9 @@ func (s *RepositoriesService) ListTrafficViews(ctx context.Context, owner, repo // ListTrafficClones get total number of clones for the last 14 days and breaks it down either per day or week for the last 14 days. // // GitHub API docs: https://developer.github.com/v3/repos/traffic/#views -func (s *RepositoriesService) ListTrafficClones(ctx context.Context, owner, repo string, opt *TrafficBreakdownOptions) (*TrafficClones, *Response, error) { +func (s *RepositoriesService) ListTrafficClones(ctx context.Context, owner, repo string, opts *TrafficBreakdownOptions) (*TrafficClones, *Response, error) { u := fmt.Sprintf("repos/%v/%v/traffic/clones", owner, repo) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/search.go b/vendor/github.com/google/go-github/v29/github/search.go index d294a4f06e..80587a3e76 100644 --- a/vendor/github.com/google/go-github/v29/github/search.go +++ b/vendor/github.com/google/go-github/v29/github/search.go @@ -70,9 +70,9 @@ type RepositoriesSearchResult struct { // Repositories searches repositories via various criteria. // // GitHub API docs: https://developer.github.com/v3/search/#search-repositories -func (s *SearchService) Repositories(ctx context.Context, query string, opt *SearchOptions) (*RepositoriesSearchResult, *Response, error) { +func (s *SearchService) Repositories(ctx context.Context, query string, opts *SearchOptions) (*RepositoriesSearchResult, *Response, error) { result := new(RepositoriesSearchResult) - resp, err := s.search(ctx, "repositories", &searchParameters{Query: query}, opt, result) + resp, err := s.search(ctx, "repositories", &searchParameters{Query: query}, opts, result) return result, resp, err } @@ -101,9 +101,9 @@ type TopicResult struct { // information about search qualifiers. // // GitHub API docs: https://developer.github.com/v3/search/#search-topics -func (s *SearchService) Topics(ctx context.Context, query string, opt *SearchOptions) (*TopicsSearchResult, *Response, error) { +func (s *SearchService) Topics(ctx context.Context, query string, opts *SearchOptions) (*TopicsSearchResult, *Response, error) { result := new(TopicsSearchResult) - resp, err := s.search(ctx, "topics", &searchParameters{Query: query}, opt, result) + resp, err := s.search(ctx, "topics", &searchParameters{Query: query}, opts, result) return result, resp, err } @@ -132,9 +132,9 @@ type CommitResult struct { // Commits searches commits via various criteria. // // GitHub API docs: https://developer.github.com/v3/search/#search-commits -func (s *SearchService) Commits(ctx context.Context, query string, opt *SearchOptions) (*CommitsSearchResult, *Response, error) { +func (s *SearchService) Commits(ctx context.Context, query string, opts *SearchOptions) (*CommitsSearchResult, *Response, error) { result := new(CommitsSearchResult) - resp, err := s.search(ctx, "commits", &searchParameters{Query: query}, opt, result) + resp, err := s.search(ctx, "commits", &searchParameters{Query: query}, opts, result) return result, resp, err } @@ -148,9 +148,9 @@ type IssuesSearchResult struct { // Issues searches issues via various criteria. // // GitHub API docs: https://developer.github.com/v3/search/#search-issues -func (s *SearchService) Issues(ctx context.Context, query string, opt *SearchOptions) (*IssuesSearchResult, *Response, error) { +func (s *SearchService) Issues(ctx context.Context, query string, opts *SearchOptions) (*IssuesSearchResult, *Response, error) { result := new(IssuesSearchResult) - resp, err := s.search(ctx, "issues", &searchParameters{Query: query}, opt, result) + resp, err := s.search(ctx, "issues", &searchParameters{Query: query}, opts, result) return result, resp, err } @@ -164,9 +164,9 @@ type UsersSearchResult struct { // Users searches users via various criteria. // // GitHub API docs: https://developer.github.com/v3/search/#search-users -func (s *SearchService) Users(ctx context.Context, query string, opt *SearchOptions) (*UsersSearchResult, *Response, error) { +func (s *SearchService) Users(ctx context.Context, query string, opts *SearchOptions) (*UsersSearchResult, *Response, error) { result := new(UsersSearchResult) - resp, err := s.search(ctx, "users", &searchParameters{Query: query}, opt, result) + resp, err := s.search(ctx, "users", &searchParameters{Query: query}, opts, result) return result, resp, err } @@ -213,9 +213,9 @@ func (c CodeResult) String() string { // Code searches code via various criteria. // // GitHub API docs: https://developer.github.com/v3/search/#search-code -func (s *SearchService) Code(ctx context.Context, query string, opt *SearchOptions) (*CodeSearchResult, *Response, error) { +func (s *SearchService) Code(ctx context.Context, query string, opts *SearchOptions) (*CodeSearchResult, *Response, error) { result := new(CodeSearchResult) - resp, err := s.search(ctx, "code", &searchParameters{Query: query}, opt, result) + resp, err := s.search(ctx, "code", &searchParameters{Query: query}, opts, result) return result, resp, err } @@ -244,9 +244,9 @@ func (l LabelResult) String() string { // Labels searches labels in the repository with ID repoID via various criteria. // // GitHub API docs: https://developer.github.com/v3/search/#search-labels -func (s *SearchService) Labels(ctx context.Context, repoID int64, query string, opt *SearchOptions) (*LabelsSearchResult, *Response, error) { +func (s *SearchService) Labels(ctx context.Context, repoID int64, query string, opts *SearchOptions) (*LabelsSearchResult, *Response, error) { result := new(LabelsSearchResult) - resp, err := s.search(ctx, "labels", &searchParameters{RepositoryID: &repoID, Query: query}, opt, result) + resp, err := s.search(ctx, "labels", &searchParameters{RepositoryID: &repoID, Query: query}, opts, result) return result, resp, err } @@ -255,8 +255,8 @@ func (s *SearchService) Labels(ctx context.Context, repoID int64, query string, // // If searchParameters.Query includes multiple condition, it MUST NOT include "+" as condition separator. // For example, querying with "language:c++" and "leveldb", then searchParameters.Query should be "language:c++ leveldb" but not "language:c+++leveldb". -func (s *SearchService) search(ctx context.Context, searchType string, parameters *searchParameters, opt *SearchOptions, result interface{}) (*Response, error) { - params, err := qs.Values(opt) +func (s *SearchService) search(ctx context.Context, searchType string, parameters *searchParameters, opts *SearchOptions, result interface{}) (*Response, error) { + params, err := qs.Values(opts) if err != nil { return nil, err } @@ -284,7 +284,7 @@ func (s *SearchService) search(ctx context.Context, searchType string, parameter // Accept header for search repositories based on topics preview endpoint // TODO: remove custom Accept header when this API fully launches. req.Header.Set("Accept", mediaTypeTopicsPreview) - case opt != nil && opt.TextMatch: + case opts != nil && opts.TextMatch: // Accept header defaults to "application/vnd.github.v3+json" // We change it here to fetch back text-match metadata req.Header.Set("Accept", "application/vnd.github.v3.text-match+json") diff --git a/vendor/github.com/google/go-github/v29/github/teams.go b/vendor/github.com/google/go-github/v29/github/teams.go index 2f7c6cb76e..cfb814e7db 100644 --- a/vendor/github.com/google/go-github/v29/github/teams.go +++ b/vendor/github.com/google/go-github/v29/github/teams.go @@ -76,9 +76,9 @@ func (i Invitation) String() string { // ListTeams lists all of the teams for an organization. // // GitHub API docs: https://developer.github.com/v3/teams/#list-teams -func (s *TeamsService) ListTeams(ctx context.Context, org string, opt *ListOptions) ([]*Team, *Response, error) { +func (s *TeamsService) ListTeams(ctx context.Context, org string, opts *ListOptions) ([]*Team, *Response, error) { u := fmt.Sprintf("orgs/%v/teams", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -97,11 +97,11 @@ func (s *TeamsService) ListTeams(ctx context.Context, org string, opt *ListOptio return teams, resp, nil } -// GetTeam fetches a team by ID. +// GetTeamByID fetches a team, given a specified organization ID, by ID. // -// GitHub API docs: https://developer.github.com/v3/teams/#get-team -func (s *TeamsService) GetTeam(ctx context.Context, team int64) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", team) +// GitHub API docs: https://developer.github.com/v3/teams/#get-team-by-name +func (s *TeamsService) GetTeamByID(ctx context.Context, orgID, teamID int64) (*Team, *Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v", orgID, teamID) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err @@ -116,7 +116,7 @@ func (s *TeamsService) GetTeam(ctx context.Context, team int64) (*Team, *Respons return t, resp, nil } -// GetTeamBySlug fetches a team by slug. +// GetTeamBySlug fetches a team, given a specified organization name, by slug. // // GitHub API docs: https://developer.github.com/v3/teams/#get-team-by-name func (s *TeamsService) GetTeamBySlug(ctx context.Context, org, slug string) (*Team, *Response, error) { @@ -212,11 +212,38 @@ func copyNewTeamWithoutParent(team *NewTeam) *newTeamNoParent { } } -// EditTeam edits a team. +// EditTeamByID edits a team, given an organization ID, selected by ID. +// +// GitHub API docs: https://developer.github.com/v3/teams/#edit-team +func (s *TeamsService) EditTeamByID(ctx context.Context, orgID, teamID int64, team NewTeam, removeParent bool) (*Team, *Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v", orgID, teamID) + + var req *http.Request + var err error + if removeParent { + teamRemoveParent := copyNewTeamWithoutParent(&team) + req, err = s.client.NewRequest("PATCH", u, teamRemoveParent) + } else { + req, err = s.client.NewRequest("PATCH", u, team) + } + if err != nil { + return nil, nil, err + } + + t := new(Team) + resp, err := s.client.Do(ctx, req, t) + if err != nil { + return nil, resp, err + } + + return t, resp, nil +} + +// EditTeamBySlug edits a team, given an organization name, by slug. // // GitHub API docs: https://developer.github.com/v3/teams/#edit-team -func (s *TeamsService) EditTeam(ctx context.Context, id int64, team NewTeam, removeParent bool) (*Team, *Response, error) { - u := fmt.Sprintf("teams/%v", id) +func (s *TeamsService) EditTeamBySlug(ctx context.Context, org, slug string, team NewTeam, removeParent bool) (*Team, *Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v", org, slug) var req *http.Request var err error @@ -239,11 +266,24 @@ func (s *TeamsService) EditTeam(ctx context.Context, id int64, team NewTeam, rem return t, resp, nil } -// DeleteTeam deletes a team. +// DeleteTeamByID deletes a team referenced by ID. +// +// GitHub API docs: https://developer.github.com/v3/teams/#delete-team +func (s *TeamsService) DeleteTeamByID(ctx context.Context, orgID, teamID int64) (*Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v", orgID, teamID) + req, err := s.client.NewRequest("DELETE", u, nil) + if err != nil { + return nil, err + } + + return s.client.Do(ctx, req, nil) +} + +// DeleteTeamBySlug deletes a team reference by slug. // // GitHub API docs: https://developer.github.com/v3/teams/#delete-team -func (s *TeamsService) DeleteTeam(ctx context.Context, team int64) (*Response, error) { - u := fmt.Sprintf("teams/%v", team) +func (s *TeamsService) DeleteTeamBySlug(ctx context.Context, org, slug string) (*Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v", org, slug) req, err := s.client.NewRequest("DELETE", u, nil) if err != nil { return nil, err @@ -252,12 +292,36 @@ func (s *TeamsService) DeleteTeam(ctx context.Context, team int64) (*Response, e return s.client.Do(ctx, req, nil) } -// ListChildTeams lists child teams for a team. +// ListChildTeamsByParentID lists child teams for a parent team given parent ID. +// +// GitHub API docs: https://developer.github.com/v3/teams/#list-child-teams +func (s *TeamsService) ListChildTeamsByParentID(ctx context.Context, orgID, teamID int64, opts *ListOptions) ([]*Team, *Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/teams", orgID, teamID) + u, err := addOptions(u, opts) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + var teams []*Team + resp, err := s.client.Do(ctx, req, &teams) + if err != nil { + return nil, resp, err + } + + return teams, resp, nil +} + +// ListChildTeamsByParentSlug lists child teams for a parent team given parent slug. // // GitHub API docs: https://developer.github.com/v3/teams/#list-child-teams -func (s *TeamsService) ListChildTeams(ctx context.Context, teamID int64, opt *ListOptions) ([]*Team, *Response, error) { - u := fmt.Sprintf("teams/%v/teams", teamID) - u, err := addOptions(u, opt) +func (s *TeamsService) ListChildTeamsByParentSlug(ctx context.Context, org, slug string, opts *ListOptions) ([]*Team, *Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/teams", org, slug) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -276,12 +340,40 @@ func (s *TeamsService) ListChildTeams(ctx context.Context, teamID int64, opt *Li return teams, resp, nil } -// ListTeamRepos lists the repositories that the specified team has access to. +// ListTeamReposByID lists the repositories given a team ID that the specified team has access to. +// +// GitHub API docs: https://developer.github.com/v3/teams/#list-team-repos +func (s *TeamsService) ListTeamReposByID(ctx context.Context, orgID, teamID int64, opts *ListOptions) ([]*Repository, *Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/repos", orgID, teamID) + u, err := addOptions(u, opts) + if err != nil { + return nil, nil, err + } + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when topics API fully launches. + headers := []string{mediaTypeTopicsPreview} + req.Header.Set("Accept", strings.Join(headers, ", ")) + + var repos []*Repository + resp, err := s.client.Do(ctx, req, &repos) + if err != nil { + return nil, resp, err + } + + return repos, resp, nil +} + +// ListTeamReposBySlug lists the repositories given a team slug that the specified team has access to. // // GitHub API docs: https://developer.github.com/v3/teams/#list-team-repos -func (s *TeamsService) ListTeamRepos(ctx context.Context, team int64, opt *ListOptions) ([]*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos", team) - u, err := addOptions(u, opt) +func (s *TeamsService) ListTeamReposBySlug(ctx context.Context, org, slug string, opts *ListOptions) ([]*Repository, *Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/repos", org, slug) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -304,13 +396,37 @@ func (s *TeamsService) ListTeamRepos(ctx context.Context, team int64, opt *ListO return repos, resp, nil } -// IsTeamRepo checks if a team manages the specified repository. If the +// IsTeamRepoByID checks if a team, given its ID, manages the specified repository. If the +// repository is managed by team, a Repository is returned which includes the +// permissions team has for that repo. +// +// GitHub API docs: https://developer.github.com/v3/teams/#check-if-a-team-manages-a-repository +func (s *TeamsService) IsTeamRepoByID(ctx context.Context, orgID, teamID int64, owner, repo string) (*Repository, *Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/repos/%v/%v", orgID, teamID, owner, repo) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + headers := []string{mediaTypeOrgPermissionRepo} + req.Header.Set("Accept", strings.Join(headers, ", ")) + + repository := new(Repository) + resp, err := s.client.Do(ctx, req, repository) + if err != nil { + return nil, resp, err + } + + return repository, resp, nil +} + +// IsTeamRepoBySlug checks if a team, given its slug, manages the specified repository. If the // repository is managed by team, a Repository is returned which includes the // permissions team has for that repo. // // GitHub API docs: https://developer.github.com/v3/teams/#check-if-a-team-manages-a-repository -func (s *TeamsService) IsTeamRepo(ctx context.Context, team int64, owner string, repo string) (*Repository, *Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) +func (s *TeamsService) IsTeamRepoBySlug(ctx context.Context, org, slug, owner, repo string) (*Repository, *Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/repos/%v/%v", org, slug, owner, repo) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err @@ -341,14 +457,44 @@ type TeamAddTeamRepoOptions struct { Permission string `json:"permission,omitempty"` } -// AddTeamRepo adds a repository to be managed by the specified team. The -// specified repository must be owned by the organization to which the team +// AddTeamRepoByID adds a repository to be managed by the specified team given the team ID. +// The specified repository must be owned by the organization to which the team +// belongs, or a direct fork of a repository owned by the organization. +// +// GitHub API docs: https://developer.github.com/v3/teams/#add-team-repo +func (s *TeamsService) AddTeamRepoByID(ctx context.Context, orgID, teamID int64, owner, repo string, opts *TeamAddTeamRepoOptions) (*Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/repos/%v/%v", orgID, teamID, owner, repo) + req, err := s.client.NewRequest("PUT", u, opts) + if err != nil { + return nil, err + } + + return s.client.Do(ctx, req, nil) +} + +// AddTeamRepoBySlug adds a repository to be managed by the specified team given the team slug. +// The specified repository must be owned by the organization to which the team // belongs, or a direct fork of a repository owned by the organization. // // GitHub API docs: https://developer.github.com/v3/teams/#add-team-repo -func (s *TeamsService) AddTeamRepo(ctx context.Context, team int64, owner string, repo string, opt *TeamAddTeamRepoOptions) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) - req, err := s.client.NewRequest("PUT", u, opt) +func (s *TeamsService) AddTeamRepoBySlug(ctx context.Context, org, slug, owner, repo string, opts *TeamAddTeamRepoOptions) (*Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/repos/%v/%v", org, slug, owner, repo) + req, err := s.client.NewRequest("PUT", u, opts) + if err != nil { + return nil, err + } + + return s.client.Do(ctx, req, nil) +} + +// RemoveTeamRepoByID removes a repository from being managed by the specified +// team given the team ID. Note that this does not delete the repository, it +// just removes it from the team. +// +// GitHub API docs: https://developer.github.com/v3/teams/#remove-team-repo +func (s *TeamsService) RemoveTeamRepoByID(ctx context.Context, orgID, teamID int64, owner, repo string) (*Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/repos/%v/%v", orgID, teamID, owner, repo) + req, err := s.client.NewRequest("DELETE", u, nil) if err != nil { return nil, err } @@ -356,13 +502,13 @@ func (s *TeamsService) AddTeamRepo(ctx context.Context, team int64, owner string return s.client.Do(ctx, req, nil) } -// RemoveTeamRepo removes a repository from being managed by the specified -// team. Note that this does not delete the repository, it just removes it -// from the team. +// RemoveTeamRepoBySlug removes a repository from being managed by the specified +// team given the team slug. Note that this does not delete the repository, it +// just removes it from the team. // // GitHub API docs: https://developer.github.com/v3/teams/#remove-team-repo -func (s *TeamsService) RemoveTeamRepo(ctx context.Context, team int64, owner string, repo string) (*Response, error) { - u := fmt.Sprintf("teams/%v/repos/%v/%v", team, owner, repo) +func (s *TeamsService) RemoveTeamRepoBySlug(ctx context.Context, org, slug, owner, repo string) (*Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/repos/%v/%v", org, slug, owner, repo) req, err := s.client.NewRequest("DELETE", u, nil) if err != nil { return nil, err @@ -373,9 +519,9 @@ func (s *TeamsService) RemoveTeamRepo(ctx context.Context, team int64, owner str // ListUserTeams lists a user's teams // GitHub API docs: https://developer.github.com/v3/teams/#list-user-teams -func (s *TeamsService) ListUserTeams(ctx context.Context, opt *ListOptions) ([]*Team, *Response, error) { +func (s *TeamsService) ListUserTeams(ctx context.Context, opts *ListOptions) ([]*Team, *Response, error) { u := "user/teams" - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -394,11 +540,35 @@ func (s *TeamsService) ListUserTeams(ctx context.Context, opt *ListOptions) ([]* return teams, resp, nil } -// ListTeamProjects lists the organization projects for a team. +// ListTeamProjectsByID lists the organization projects for a team given the team ID. +// +// GitHub API docs: https://developer.github.com/v3/teams/#list-team-projects +func (s *TeamsService) ListTeamProjectsByID(ctx context.Context, orgID, teamID int64) ([]*Project, *Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/projects", orgID, teamID) + + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + acceptHeaders := []string{mediaTypeProjectsPreview} + req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) + + var projects []*Project + resp, err := s.client.Do(ctx, req, &projects) + if err != nil { + return nil, resp, err + } + + return projects, resp, nil +} + +// ListTeamProjectsBySlug lists the organization projects for a team given the team slug. // // GitHub API docs: https://developer.github.com/v3/teams/#list-team-projects -func (s *TeamsService) ListTeamProjects(ctx context.Context, teamID int64) ([]*Project, *Response, error) { - u := fmt.Sprintf("teams/%v/projects", teamID) +func (s *TeamsService) ListTeamProjectsBySlug(ctx context.Context, org, slug string) ([]*Project, *Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/projects", org, slug) req, err := s.client.NewRequest("GET", u, nil) if err != nil { @@ -418,12 +588,36 @@ func (s *TeamsService) ListTeamProjects(ctx context.Context, teamID int64) ([]*P return projects, resp, nil } -// ReviewTeamProjects checks whether a team has read, write, or admin +// ReviewTeamProjectsByID checks whether a team, given its ID, has read, write, or admin +// permissions for an organization project. +// +// GitHub API docs: https://developer.github.com/v3/teams/#review-a-team-project +func (s *TeamsService) ReviewTeamProjectsByID(ctx context.Context, orgID, teamID, projectID int64) (*Project, *Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/projects/%v", orgID, teamID, projectID) + req, err := s.client.NewRequest("GET", u, nil) + if err != nil { + return nil, nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + acceptHeaders := []string{mediaTypeProjectsPreview} + req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) + + projects := &Project{} + resp, err := s.client.Do(ctx, req, &projects) + if err != nil { + return nil, resp, err + } + + return projects, resp, nil +} + +// ReviewTeamProjectsBySlug checks whether a team, given its slug, has read, write, or admin // permissions for an organization project. // // GitHub API docs: https://developer.github.com/v3/teams/#review-a-team-project -func (s *TeamsService) ReviewTeamProjects(ctx context.Context, teamID, projectID int64) (*Project, *Response, error) { - u := fmt.Sprintf("teams/%v/projects/%v", teamID, projectID) +func (s *TeamsService) ReviewTeamProjectsBySlug(ctx context.Context, org, slug string, projectID int64) (*Project, *Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/projects/%v", org, slug, projectID) req, err := s.client.NewRequest("GET", u, nil) if err != nil { return nil, nil, err @@ -454,14 +648,55 @@ type TeamProjectOptions struct { Permission *string `json:"permission,omitempty"` } -// AddTeamProject adds an organization project to a team. To add a project to a team or -// update the team's permission on a project, the authenticated user must have admin -// permissions for the project. +// AddTeamProjectByID adds an organization project to a team given the team ID. +// To add a project to a team or update the team's permission on a project, the +// authenticated user must have admin permissions for the project. +// +// GitHub API docs: https://developer.github.com/v3/teams/#add-or-update-team-project +func (s *TeamsService) AddTeamProjectByID(ctx context.Context, orgID, teamID, projectID int64, opts *TeamProjectOptions) (*Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/projects/%v", orgID, teamID, projectID) + req, err := s.client.NewRequest("PUT", u, opts) + if err != nil { + return nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + acceptHeaders := []string{mediaTypeProjectsPreview} + req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) + + return s.client.Do(ctx, req, nil) +} + +// AddTeamProjectBySlug adds an organization project to a team given the team slug. +// To add a project to a team or update the team's permission on a project, the +// authenticated user must have admin permissions for the project. // // GitHub API docs: https://developer.github.com/v3/teams/#add-or-update-team-project -func (s *TeamsService) AddTeamProject(ctx context.Context, teamID, projectID int64, opt *TeamProjectOptions) (*Response, error) { - u := fmt.Sprintf("teams/%v/projects/%v", teamID, projectID) - req, err := s.client.NewRequest("PUT", u, opt) +func (s *TeamsService) AddTeamProjectBySlug(ctx context.Context, org, slug string, projectID int64, opts *TeamProjectOptions) (*Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/projects/%v", org, slug, projectID) + req, err := s.client.NewRequest("PUT", u, opts) + if err != nil { + return nil, err + } + + // TODO: remove custom Accept header when this API fully launches. + acceptHeaders := []string{mediaTypeProjectsPreview} + req.Header.Set("Accept", strings.Join(acceptHeaders, ", ")) + + return s.client.Do(ctx, req, nil) +} + +// RemoveTeamProjectByID removes an organization project from a team given team ID. +// An organization owner or a team maintainer can remove any project from the team. +// To remove a project from a team as an organization member, the authenticated user +// must have "read" access to both the team and project, or "admin" access to the team +// or project. +// Note: This endpoint removes the project from the team, but does not delete it. +// +// GitHub API docs: https://developer.github.com/v3/teams/#remove-team-project +func (s *TeamsService) RemoveTeamProjectByID(ctx context.Context, orgID, teamID, projectID int64) (*Response, error) { + u := fmt.Sprintf("organizations/%v/team/%v/projects/%v", orgID, teamID, projectID) + req, err := s.client.NewRequest("DELETE", u, nil) if err != nil { return nil, err } @@ -473,15 +708,16 @@ func (s *TeamsService) AddTeamProject(ctx context.Context, teamID, projectID int return s.client.Do(ctx, req, nil) } -// RemoveTeamProject removes an organization project from a team. An organization owner or -// a team maintainer can remove any project from the team. To remove a project from a team -// as an organization member, the authenticated user must have "read" access to both the team -// and project, or "admin" access to the team or project. +// RemoveTeamProjectBySlug removes an organization project from a team given team slug. +// An organization owner or a team maintainer can remove any project from the team. +// To remove a project from a team as an organization member, the authenticated user +// must have "read" access to both the team and project, or "admin" access to the team +// or project. // Note: This endpoint removes the project from the team, but does not delete it. // // GitHub API docs: https://developer.github.com/v3/teams/#remove-team-project -func (s *TeamsService) RemoveTeamProject(ctx context.Context, teamID int64, projectID int64) (*Response, error) { - u := fmt.Sprintf("teams/%v/projects/%v", teamID, projectID) +func (s *TeamsService) RemoveTeamProjectBySlug(ctx context.Context, org, slug string, projectID int64) (*Response, error) { + u := fmt.Sprintf("orgs/%v/teams/%v/projects/%v", org, slug, projectID) req, err := s.client.NewRequest("DELETE", u, nil) if err != nil { return nil, err @@ -496,7 +732,7 @@ func (s *TeamsService) RemoveTeamProject(ctx context.Context, teamID int64, proj // IDPGroupList represents a list of external identity provider (IDP) groups. type IDPGroupList struct { - Groups []*IDPGroup `json:"groups,omitempty"` + Groups []*IDPGroup `json:"groups"` } // IDPGroup represents an external identity provider (IDP) group. @@ -509,9 +745,9 @@ type IDPGroup struct { // ListIDPGroupsInOrganization lists IDP groups available in an organization. // // GitHub API docs: https://developer.github.com/v3/teams/team_sync/#list-idp-groups-in-an-organization -func (s *TeamsService) ListIDPGroupsInOrganization(ctx context.Context, org string, opt *ListOptions) (*IDPGroupList, *Response, error) { +func (s *TeamsService) ListIDPGroupsInOrganization(ctx context.Context, org string, opts *ListCursorOptions) (*IDPGroupList, *Response, error) { u := fmt.Sprintf("orgs/%v/team-sync/groups", org) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -552,10 +788,10 @@ func (s *TeamsService) ListIDPGroupsForTeam(ctx context.Context, teamID string) // and an IDP group. // // GitHub API docs: https://developer.github.com/v3/teams/team_sync/#create-or-update-idp-group-connections -func (s *TeamsService) CreateOrUpdateIDPGroupConnections(ctx context.Context, teamID string, opt IDPGroupList) (*IDPGroupList, *Response, error) { +func (s *TeamsService) CreateOrUpdateIDPGroupConnections(ctx context.Context, teamID string, opts IDPGroupList) (*IDPGroupList, *Response, error) { u := fmt.Sprintf("teams/%v/team-sync/group-mappings", teamID) - req, err := s.client.NewRequest("PATCH", u, opt) + req, err := s.client.NewRequest("PATCH", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/teams_members.go b/vendor/github.com/google/go-github/v29/github/teams_members.go index 2a211fe907..36ca74353b 100644 --- a/vendor/github.com/google/go-github/v29/github/teams_members.go +++ b/vendor/github.com/google/go-github/v29/github/teams_members.go @@ -24,9 +24,9 @@ type TeamListTeamMembersOptions struct { // team. // // GitHub API docs: https://developer.github.com/v3/teams/members/#list-team-members -func (s *TeamsService) ListTeamMembers(ctx context.Context, team int64, opt *TeamListTeamMembersOptions) ([]*User, *Response, error) { +func (s *TeamsService) ListTeamMembers(ctx context.Context, team int64, opts *TeamListTeamMembersOptions) ([]*User, *Response, error) { u := fmt.Sprintf("teams/%v/members", team) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -114,9 +114,9 @@ type TeamAddTeamMembershipOptions struct { // added as a member of the team. // // GitHub API docs: https://developer.github.com/v3/teams/members/#add-or-update-team-membership -func (s *TeamsService) AddTeamMembership(ctx context.Context, team int64, user string, opt *TeamAddTeamMembershipOptions) (*Membership, *Response, error) { +func (s *TeamsService) AddTeamMembership(ctx context.Context, team int64, user string, opts *TeamAddTeamMembershipOptions) (*Membership, *Response, error) { u := fmt.Sprintf("teams/%v/memberships/%v", team, user) - req, err := s.client.NewRequest("PUT", u, opt) + req, err := s.client.NewRequest("PUT", u, opts) if err != nil { return nil, nil, err } @@ -148,9 +148,9 @@ func (s *TeamsService) RemoveTeamMembership(ctx context.Context, team int64, use // Preview features are not supported for production use. // // GitHub API docs: https://developer.github.com/v3/teams/members/#list-pending-team-invitations -func (s *TeamsService) ListPendingTeamInvitations(ctx context.Context, team int64, opt *ListOptions) ([]*Invitation, *Response, error) { +func (s *TeamsService) ListPendingTeamInvitations(ctx context.Context, team int64, opts *ListOptions) ([]*Invitation, *Response, error) { u := fmt.Sprintf("teams/%v/invitations", team) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users.go b/vendor/github.com/google/go-github/v29/github/users.go index 88a15bdb76..f7c77c61d8 100644 --- a/vendor/github.com/google/go-github/v29/github/users.go +++ b/vendor/github.com/google/go-github/v29/github/users.go @@ -164,9 +164,9 @@ type UserContext struct { // via Basic Auth or via OAuth with the repo scope. // // GitHub API docs: https://developer.github.com/v3/users/#get-contextual-information-about-a-user -func (s *UsersService) GetHovercard(ctx context.Context, user string, opt *HovercardOptions) (*Hovercard, *Response, error) { +func (s *UsersService) GetHovercard(ctx context.Context, user string, opts *HovercardOptions) (*Hovercard, *Response, error) { u := fmt.Sprintf("users/%v/hovercard", user) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -202,8 +202,8 @@ type UserListOptions struct { // To paginate through all users, populate 'Since' with the ID of the last user. // // GitHub API docs: https://developer.github.com/v3/users/#get-all-users -func (s *UsersService) ListAll(ctx context.Context, opt *UserListOptions) ([]*User, *Response, error) { - u, err := addOptions("users", opt) +func (s *UsersService) ListAll(ctx context.Context, opts *UserListOptions) ([]*User, *Response, error) { + u, err := addOptions("users", opts) if err != nil { return nil, nil, err } @@ -226,8 +226,8 @@ func (s *UsersService) ListAll(ctx context.Context, opt *UserListOptions) ([]*Us // authenticated user. // // GitHub API docs: https://developer.github.com/v3/repos/invitations/#list-a-users-repository-invitations -func (s *UsersService) ListInvitations(ctx context.Context, opt *ListOptions) ([]*RepositoryInvitation, *Response, error) { - u, err := addOptions("user/repository_invitations", opt) +func (s *UsersService) ListInvitations(ctx context.Context, opts *ListOptions) ([]*RepositoryInvitation, *Response, error) { + u, err := addOptions("user/repository_invitations", opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users_administration.go b/vendor/github.com/google/go-github/v29/github/users_administration.go index 1c483a7b17..aef947ec45 100644 --- a/vendor/github.com/google/go-github/v29/github/users_administration.go +++ b/vendor/github.com/google/go-github/v29/github/users_administration.go @@ -46,10 +46,10 @@ type UserSuspendOptions struct { // Suspend a user on a GitHub Enterprise instance. // // GitHub API docs: https://developer.github.com/enterprise/v3/enterprise-admin/users/#suspend-a-user -func (s *UsersService) Suspend(ctx context.Context, user string, opt *UserSuspendOptions) (*Response, error) { +func (s *UsersService) Suspend(ctx context.Context, user string, opts *UserSuspendOptions) (*Response, error) { u := fmt.Sprintf("users/%v/suspended", user) - req, err := s.client.NewRequest("PUT", u, opt) + req, err := s.client.NewRequest("PUT", u, opts) if err != nil { return nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users_blocking.go b/vendor/github.com/google/go-github/v29/github/users_blocking.go index 39e45601cc..c60bfdbcd5 100644 --- a/vendor/github.com/google/go-github/v29/github/users_blocking.go +++ b/vendor/github.com/google/go-github/v29/github/users_blocking.go @@ -13,9 +13,9 @@ import ( // ListBlockedUsers lists all the blocked users by the authenticated user. // // GitHub API docs: https://developer.github.com/v3/users/blocking/#list-blocked-users -func (s *UsersService) ListBlockedUsers(ctx context.Context, opt *ListOptions) ([]*User, *Response, error) { +func (s *UsersService) ListBlockedUsers(ctx context.Context, opts *ListOptions) ([]*User, *Response, error) { u := "user/blocks" - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users_emails.go b/vendor/github.com/google/go-github/v29/github/users_emails.go index 78d2149119..bf02d1a610 100644 --- a/vendor/github.com/google/go-github/v29/github/users_emails.go +++ b/vendor/github.com/google/go-github/v29/github/users_emails.go @@ -18,9 +18,9 @@ type UserEmail struct { // ListEmails lists all email addresses for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/users/emails/#list-email-addresses-for-a-user -func (s *UsersService) ListEmails(ctx context.Context, opt *ListOptions) ([]*UserEmail, *Response, error) { +func (s *UsersService) ListEmails(ctx context.Context, opts *ListOptions) ([]*UserEmail, *Response, error) { u := "user/emails" - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users_followers.go b/vendor/github.com/google/go-github/v29/github/users_followers.go index c2224096a6..afa7d4b6b7 100644 --- a/vendor/github.com/google/go-github/v29/github/users_followers.go +++ b/vendor/github.com/google/go-github/v29/github/users_followers.go @@ -14,14 +14,14 @@ import ( // fetch followers for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/users/followers/#list-followers-of-a-user -func (s *UsersService) ListFollowers(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { +func (s *UsersService) ListFollowers(ctx context.Context, user string, opts *ListOptions) ([]*User, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/followers", user) } else { u = "user/followers" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -44,14 +44,14 @@ func (s *UsersService) ListFollowers(ctx context.Context, user string, opt *List // string will list people the authenticated user is following. // // GitHub API docs: https://developer.github.com/v3/users/followers/#list-users-followed-by-another-user -func (s *UsersService) ListFollowing(ctx context.Context, user string, opt *ListOptions) ([]*User, *Response, error) { +func (s *UsersService) ListFollowing(ctx context.Context, user string, opts *ListOptions) ([]*User, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/following", user) } else { u = "user/following" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users_gpg_keys.go b/vendor/github.com/google/go-github/v29/github/users_gpg_keys.go index 07ed38dcbe..42638eb541 100644 --- a/vendor/github.com/google/go-github/v29/github/users_gpg_keys.go +++ b/vendor/github.com/google/go-github/v29/github/users_gpg_keys.go @@ -45,14 +45,14 @@ type GPGEmail struct { // via Basic Auth or via OAuth with at least read:gpg_key scope. // // GitHub API docs: https://developer.github.com/v3/users/gpg_keys/#list-gpg-keys-for-a-user -func (s *UsersService) ListGPGKeys(ctx context.Context, user string, opt *ListOptions) ([]*GPGKey, *Response, error) { +func (s *UsersService) ListGPGKeys(ctx context.Context, user string, opts *ListOptions) ([]*GPGKey, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/gpg_keys", user) } else { u = "user/gpg_keys" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users_keys.go b/vendor/github.com/google/go-github/v29/github/users_keys.go index 39a4f54d6c..f12c01b9b0 100644 --- a/vendor/github.com/google/go-github/v29/github/users_keys.go +++ b/vendor/github.com/google/go-github/v29/github/users_keys.go @@ -28,14 +28,14 @@ func (k Key) String() string { // string will fetch keys for the authenticated user. // // GitHub API docs: https://developer.github.com/v3/users/keys/#list-public-keys-for-a-user -func (s *UsersService) ListKeys(ctx context.Context, user string, opt *ListOptions) ([]*Key, *Response, error) { +func (s *UsersService) ListKeys(ctx context.Context, user string, opts *ListOptions) ([]*Key, *Response, error) { var u string if user != "" { u = fmt.Sprintf("users/%v/keys", user) } else { u = "user/keys" } - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/google/go-github/v29/github/users_projects.go b/vendor/github.com/google/go-github/v29/github/users_projects.go index bd2ca75e1f..64e85a0322 100644 --- a/vendor/github.com/google/go-github/v29/github/users_projects.go +++ b/vendor/github.com/google/go-github/v29/github/users_projects.go @@ -13,9 +13,9 @@ import ( // ListProjects lists the projects for the specified user. // // GitHub API docs: https://developer.github.com/v3/projects/#list-user-projects -func (s *UsersService) ListProjects(ctx context.Context, user string, opt *ProjectListOptions) ([]*Project, *Response, error) { +func (s *UsersService) ListProjects(ctx context.Context, user string, opts *ProjectListOptions) ([]*Project, *Response, error) { u := fmt.Sprintf("users/%v/projects", user) - u, err := addOptions(u, opt) + u, err := addOptions(u, opts) if err != nil { return nil, nil, err } @@ -48,9 +48,9 @@ type CreateUserProjectOptions struct { // CreateProject creates a GitHub Project for the current user. // // GitHub API docs: https://developer.github.com/v3/projects/#create-a-user-project -func (s *UsersService) CreateProject(ctx context.Context, opt *CreateUserProjectOptions) (*Project, *Response, error) { +func (s *UsersService) CreateProject(ctx context.Context, opts *CreateUserProjectOptions) (*Project, *Response, error) { u := "users/projects" - req, err := s.client.NewRequest("POST", u, opt) + req, err := s.client.NewRequest("POST", u, opts) if err != nil { return nil, nil, err } diff --git a/vendor/github.com/hashicorp/go-getter/.travis.yml b/vendor/github.com/hashicorp/go-getter/.travis.yml deleted file mode 100644 index 4fe9176aab..0000000000 --- a/vendor/github.com/hashicorp/go-getter/.travis.yml +++ /dev/null @@ -1,24 +0,0 @@ -sudo: false - -addons: - apt: - sources: - - sourceline: 'ppa:git-core/ppa' - packages: - - git - -language: go - -os: - - linux - - osx - -go: - - "1.11.x" - -before_script: - - go build ./cmd/go-getter - -branches: - only: - - master diff --git a/vendor/github.com/hashicorp/go-getter/README.md b/vendor/github.com/hashicorp/go-getter/README.md index 3de23c7094..bbcd15de96 100644 --- a/vendor/github.com/hashicorp/go-getter/README.md +++ b/vendor/github.com/hashicorp/go-getter/README.md @@ -1,10 +1,10 @@ # go-getter -[![Build Status](http://img.shields.io/travis/hashicorp/go-getter.svg?style=flat-square)][travis] +[![CircleCI](https://circleci.com/gh/hashicorp/go-getter/tree/master.svg?style=svg)][circleci] [![Build status](https://ci.appveyor.com/api/projects/status/ulq3qr43n62croyq/branch/master?svg=true)][appveyor] [![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] -[travis]: http://travis-ci.org/hashicorp/go-getter +[circleci]: https://circleci.com/gh/hashicorp/go-getter/tree/master [godocs]: http://godoc.org/github.com/hashicorp/go-getter [appveyor]: https://ci.appveyor.com/project/hashicorp/go-getter/branch/master @@ -356,3 +356,7 @@ In order to access to GCS, authentication credentials should be provided. More i - gcs::https://www.googleapis.com/storage/v1/bucket - gcs::https://www.googleapis.com/storage/v1/bucket/foo.zip - www.googleapis.com/storage/v1/bucket/foo + +#### GCS Testing + +The tests for `get_gcs.go` require you to have GCP credentials set in your environment. These credentials can have any level of permissions to any project, they just need to exist. This means setting `GOOGLE_APPLICATION_CREDENTIALS="~/path/to/credentials.json"` or `GOOGLE_CREDENTIALS="{stringified-credentials-json}"`. Due to this configuration, `get_gcs_test.go` will fail for external contributors in CircleCI. diff --git a/vendor/github.com/hashicorp/go-getter/client.go b/vendor/github.com/hashicorp/go-getter/client.go index 007a78ba7c..38fb43b8f5 100644 --- a/vendor/github.com/hashicorp/go-getter/client.go +++ b/vendor/github.com/hashicorp/go-getter/client.go @@ -19,7 +19,7 @@ import ( // Using a client directly allows more fine-grained control over how downloading // is done, as well as customizing the protocols supported. type Client struct { - // Ctx for cancellation + // Ctx for cancellation Ctx context.Context // Src is the source URL to get. diff --git a/vendor/github.com/hashicorp/go-getter/get_git.go b/vendor/github.com/hashicorp/go-getter/get_git.go index bb1ec316d3..1b9f4be819 100644 --- a/vendor/github.com/hashicorp/go-getter/get_git.go +++ b/vendor/github.com/hashicorp/go-getter/get_git.go @@ -1,6 +1,7 @@ package getter import ( + "bytes" "context" "encoding/base64" "fmt" @@ -9,6 +10,7 @@ import ( "os" "os/exec" "path/filepath" + "regexp" "runtime" "strconv" "strings" @@ -24,6 +26,8 @@ type GitGetter struct { getter } +var defaultBranchRegexp = regexp.MustCompile(`\s->\sorigin/(.*)`) + func (g *GitGetter) ClientMode(_ *url.URL) (ClientMode, error) { return ClientModeDir, nil } @@ -182,10 +186,10 @@ func (g *GitGetter) update(ctx context.Context, dst, sshKeyFile, ref string, dep cmd.Dir = dst if getRunCommand(cmd) != nil { - // Not a branch, switch to master. This will also catch non-existent - // branches, in which case we want to switch to master and then - // checkout the proper branch later. - ref = "master" + // Not a branch, switch to default branch. This will also catch + // non-existent branches, in which case we want to switch to default + // and then checkout the proper branch later. + ref = findDefaultBranch(dst) } // We have to be on a branch to pull @@ -216,6 +220,22 @@ func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string, return getRunCommand(cmd) } +// findDefaultBranch checks the repo's origin remote for its default branch +// (generally "master"). "master" is returned if an origin default branch +// can't be determined. +func findDefaultBranch(dst string) string { + var stdoutbuf bytes.Buffer + cmd := exec.Command("git", "branch", "-r", "--points-at", "refs/remotes/origin/HEAD") + cmd.Dir = dst + cmd.Stdout = &stdoutbuf + err := cmd.Run() + matches := defaultBranchRegexp.FindStringSubmatch(stdoutbuf.String()) + if err != nil || matches == nil { + return "master" + } + return matches[len(matches)-1] +} + // setupGitEnv sets up the environment for the given command. This is used to // pass configuration data to git and ssh and enables advanced cloning methods. func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { diff --git a/vendor/github.com/hashicorp/go-getter/get_http.go b/vendor/github.com/hashicorp/go-getter/get_http.go index 7c4541c6e9..9ffdba78a5 100644 --- a/vendor/github.com/hashicorp/go-getter/get_http.go +++ b/vendor/github.com/hashicorp/go-getter/get_http.go @@ -9,7 +9,6 @@ import ( "net/url" "os" "path/filepath" - "strconv" "strings" safetemp "github.com/hashicorp/go-safetemp" @@ -88,7 +87,10 @@ func (g *HttpGetter) Get(dst string, u *url.URL) error { return err } - req.Header = g.Header + if g.Header != nil { + req.Header = g.Header + } + resp, err := g.Client.Do(req) if err != nil { return err @@ -128,6 +130,12 @@ func (g *HttpGetter) Get(dst string, u *url.URL) error { return g.getSubdir(ctx, dst, source, subDir) } +// GetFile fetches the file from src and stores it at dst. +// If the server supports Accept-Range, HttpGetter will attempt a range +// request. This means it is the caller's responsibility to ensure that an +// older version of the destination file does not exist, else it will be either +// falsely identified as being replaced, or corrupted with extra bytes +// appended. func (g *HttpGetter) GetFile(dst string, src *url.URL) error { ctx := g.Context() if g.Netrc { @@ -136,7 +144,6 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { return err } } - // Create all the parent directories if needed if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { return err @@ -165,18 +172,17 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { req.Header = g.Header } headResp, err := g.Client.Do(req) - if err == nil && headResp != nil { + if err == nil { headResp.Body.Close() if headResp.StatusCode == 200 { // If the HEAD request succeeded, then attempt to set the range // query if we can. - if headResp.Header.Get("Accept-Ranges") == "bytes" { + if headResp.Header.Get("Accept-Ranges") == "bytes" && headResp.ContentLength >= 0 { if fi, err := f.Stat(); err == nil { - if _, err = f.Seek(0, os.SEEK_END); err == nil { - req.Header.Set("Range", fmt.Sprintf("bytes=%d-", fi.Size())) + if _, err = f.Seek(0, io.SeekEnd); err == nil { currentFileSize = fi.Size() - totalFileSize, _ := strconv.ParseInt(headResp.Header.Get("Content-Length"), 10, 64) - if currentFileSize >= totalFileSize { + req.Header.Set("Range", fmt.Sprintf("bytes=%d-", currentFileSize)) + if currentFileSize >= headResp.ContentLength { // file already present return nil } diff --git a/vendor/github.com/hashicorp/hcl/v2/appveyor.yml b/vendor/github.com/hashicorp/hcl/v2/appveyor.yml new file mode 100644 index 0000000000..e382f8f571 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/appveyor.yml @@ -0,0 +1,13 @@ +build: off + +clone_folder: c:\gopath\src\github.com\hashicorp\hcl + +environment: + GOPATH: c:\gopath + GO111MODULE: on + GOPROXY: https://goproxy.io + +stack: go 1.12 + +test_script: + - go test ./... diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md new file mode 100644 index 0000000000..1636f577a0 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md @@ -0,0 +1,209 @@ +# HCL Custom Static Decoding Extension + +This HCL extension provides a mechanism for defining arguments in an HCL-based +language whose values are derived using custom decoding rules against the +HCL expression syntax, overriding the usual behavior of normal expression +evaluation. + +"Arguments", for the purpose of this extension, currently includes the +following two contexts: + +* For applications using `hcldec` for dynamic decoding, a `hcldec.AttrSpec` + or `hcldec.BlockAttrsSpec` can be given a special type constraint that + opts in to custom decoding behavior for the attribute(s) that are selected + by that specification. + +* When working with the HCL native expression syntax, a function given in + the `hcl.EvalContext` during evaluation can have parameters with special + type constraints that opt in to custom decoding behavior for the argument + expression associated with that parameter in any call. + +The above use-cases are rather abstract, so we'll consider a motivating +real-world example: sometimes we (language designers) need to allow users +to specify type constraints directly in the language itself, such as in +[Terraform's Input Variables](https://www.terraform.io/docs/configuration/variables.html). +Terraform's `variable` blocks include an argument called `type` which takes +a type constraint given using HCL expression building-blocks as defined by +[the HCL `typeexpr` extension](../typeexpr/README.md). + +A "type constraint expression" of that sort is not an expression intended to +be evaluated in the usual way. Instead, the physical expression is +deconstructed using [the static analysis operations](../../spec.md#static-analysis) +to produce a `cty.Type` as the result, rather than a `cty.Value`. + +The purpose of this Custom Static Decoding Extension, then, is to provide a +bridge to allow that sort of custom decoding to be used via mechanisms that +normally deal in `cty.Value`, such as `hcldec` and native syntax function +calls as listed above. + +(Note: [`gohcl`](https://pkg.go.dev/github.com/hashicorp/hcl/v2/gohcl) has +its own mechanism to support this use case, exploiting the fact that it is +working directly with "normal" Go types. Decoding into a struct field of +type `hcl.Expression` obtains the expression directly without evaluating it +first. The Custom Static Decoding Extension is not necessary for that `gohcl` +technique. You can also implement custom decoding by working directly with +the lowest-level HCL API, which separates extraction of and evaluation of +expressions into two steps.) + +## Custom Decoding Types + +This extension relies on a convention implemented in terms of +[_Capsule Types_ in the underlying `cty` type system](https://github.com/zclconf/go-cty/blob/master/docs/types.md#capsule-types). `cty` allows a capsule type to carry arbitrary +extension metadata values as an aid to creating higher-level abstractions like +this extension. + +A custom argument decoding mode, then, is implemented by creating a new `cty` +capsule type that implements the `ExtensionData` custom operation to return +a decoding function when requested. For example: + +```go +var keywordType cty.Type +keywordType = cty.CapsuleWithOps("keyword", reflect.TypeOf(""), &cty.CapsuleOps{ + ExtensionData: func(key interface{}) interface{} { + switch key { + case customdecode.CustomExpressionDecoder: + return customdecode.CustomExpressionDecoderFunc( + func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { + var diags hcl.Diagnostics + kw := hcl.ExprAsKeyword(expr) + if kw == "" { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid keyword", + Detail: "A keyword is required", + Subject: expr.Range().Ptr(), + }) + return cty.UnkownVal(keywordType), diags + } + return cty.CapsuleVal(keywordType, &kw) + }, + ) + default: + return nil + } + }, +}) +``` + +The boilerplate here is a bit fussy, but the important part for our purposes +is the `case customdecode.CustomExpressionDecoder:` clause, which uses +a custom extension key type defined in this package to recognize when a +component implementing this extension is checking to see if a target type +has a custom decode implementation. + +In the above case we've defined a type that decodes expressions as static +keywords, so a keyword like `foo` would decode as an encapsulated `"foo"` +string, while any other sort of expression like `"baz"` or `1 + 1` would +return an error. + +We could then use `keywordType` as a type constraint either for a function +parameter or a `hcldec` attribute specification, which would require the +argument for that function parameter or the expression for the matching +attributes to be a static keyword, rather than an arbitrary expression. +For example, in a `hcldec.AttrSpec`: + +```go +keywordSpec := &hcldec.AttrSpec{ + Name: "keyword", + Type: keywordType, +} +``` + +The above would accept input like the following and would set its result to +a `cty.Value` of `keywordType`, after decoding: + +```hcl +keyword = foo +``` + +## The Expression and Expression Closure `cty` types + +Building on the above, this package also includes two capsule types that use +the above mechanism to allow calling applications to capture expressions +directly and thus defer analysis to a later step, after initial decoding. + +The `customdecode.ExpressionType` type encapsulates an `hcl.Expression` alone, +for situations like our type constraint expression example above where it's +the static structure of the expression we want to inspect, and thus any +variables and functions defined in the evaluation context are irrelevant. + +The `customdecode.ExpressionClosureType` type encapsulates a +`*customdecode.ExpressionClosure` value, which binds the given expression to +the `hcl.EvalContext` it was asked to evaluate against and thus allows the +receiver of that result to later perform normal evaluation of the expression +with all the same variables and functions that would've been available to it +naturally. + +Both of these types can be used as type constraints either for `hcldec` +attribute specifications or for function arguments. Here's an example of +`ExpressionClosureType` to implement a function that can evaluate +an expression with some additional variables defined locally, which we'll +call the `with(...)` function: + +```go +var WithFunc = function.New(&function.Spec{ + Params: []function.Parameter{ + { + Name: "variables", + Type: cty.DynamicPseudoType, + }, + { + Name: "expression", + Type: customdecode.ExpressionClosureType, + }, + }, + Type: func(args []cty.Value) (cty.Type, error) { + varsVal := args[0] + exprVal := args[1] + if !varsVal.Type().IsObjectType() { + return cty.NilVal, function.NewArgErrorf(0, "must be an object defining local variables") + } + if !varsVal.IsKnown() { + // We can't predict our result type until the variables object + // is known. + return cty.DynamicPseudoType, nil + } + vars := varsVal.AsValueMap() + closure := customdecode.ExpressionClosureFromVal(exprVal) + result, err := evalWithLocals(vars, closure) + if err != nil { + return cty.NilVal, err + } + return result.Type(), nil + }, + Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { + varsVal := args[0] + exprVal := args[1] + vars := varsVal.AsValueMap() + closure := customdecode.ExpressionClosureFromVal(exprVal) + return evalWithLocals(vars, closure) + }, +}) + +func evalWithLocals(locals map[string]cty.Value, closure *customdecode.ExpressionClosure) (cty.Value, error) { + childCtx := closure.EvalContext.NewChild() + childCtx.Variables = locals + val, diags := closure.Expression.Value(childCtx) + if diags.HasErrors() { + return cty.NilVal, function.NewArgErrorf(1, "couldn't evaluate expression: %s", diags.Error()) + } + return val, nil +} +``` + +If the above function were placed into an `hcl.EvalContext` as `with`, it +could be used in a native syntax call to that function as follows: + +```hcl + foo = with({name = "Cory"}, "${greeting}, ${name}!") +``` + +The above assumes a variable in the main context called `greeting`, to which +the `with` function adds `name` before evaluating the expression given in +its second argument. This makes that second argument context-sensitive -- it +would behave differently if the user wrote the same thing somewhere else -- so +this capability should be used with care to make sure it doesn't cause confusion +for the end-users of your language. + +There are some other examples of this capability to evaluate expressions in +unusual ways in the `tryfunc` directory that is a sibling of this one. diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go new file mode 100644 index 0000000000..c9d7a1efb2 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go @@ -0,0 +1,56 @@ +// Package customdecode contains a HCL extension that allows, in certain +// contexts, expression evaluation to be overridden by custom static analysis. +// +// This mechanism is only supported in certain specific contexts where +// expressions are decoded with a specific target type in mind. For more +// information, see the documentation on CustomExpressionDecoder. +package customdecode + +import ( + "github.com/hashicorp/hcl/v2" + "github.com/zclconf/go-cty/cty" +) + +type customDecoderImpl int + +// CustomExpressionDecoder is a value intended to be used as a cty capsule +// type ExtensionData key for capsule types whose values are to be obtained +// by static analysis of an expression rather than normal evaluation of that +// expression. +// +// When a cooperating capsule type is asked for ExtensionData with this key, +// it must return a non-nil CustomExpressionDecoderFunc value. +// +// This mechanism is not universally supported; instead, it's handled in a few +// specific places where expressions are evaluated with the intent of producing +// a cty.Value of a type given by the calling application. +// +// Specifically, this currently works for type constraints given in +// hcldec.AttrSpec and hcldec.BlockAttrsSpec, and it works for arguments to +// function calls in the HCL native syntax. HCL extensions implemented outside +// of the main HCL module may also implement this; consult their own +// documentation for details. +const CustomExpressionDecoder = customDecoderImpl(1) + +// CustomExpressionDecoderFunc is the type of value that must be returned by +// a capsule type handling the key CustomExpressionDecoder in its ExtensionData +// implementation. +// +// If no error diagnostics are returned, the result value MUST be of the +// capsule type that the decoder function was derived from. If the returned +// error diagnostics prevent producing a value at all, return cty.NilVal. +type CustomExpressionDecoderFunc func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) + +// CustomExpressionDecoderForType takes any cty type and returns its +// custom expression decoder implementation if it has one. If it is not a +// capsule type or it does not implement a custom expression decoder, this +// function returns nil. +func CustomExpressionDecoderForType(ty cty.Type) CustomExpressionDecoderFunc { + if !ty.IsCapsuleType() { + return nil + } + if fn, ok := ty.CapsuleExtensionData(CustomExpressionDecoder).(CustomExpressionDecoderFunc); ok { + return fn + } + return nil +} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go new file mode 100644 index 0000000000..af7c66c235 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go @@ -0,0 +1,146 @@ +package customdecode + +import ( + "fmt" + "reflect" + + "github.com/hashicorp/hcl/v2" + "github.com/zclconf/go-cty/cty" +) + +// ExpressionType is a cty capsule type that carries hcl.Expression values. +// +// This type implements custom decoding in the most general way possible: it +// just captures whatever expression is given to it, with no further processing +// whatsoever. It could therefore be useful in situations where an application +// must defer processing of the expression content until a later step. +// +// ExpressionType only captures the expression, not the evaluation context it +// was destined to be evaluated in. That means this type can be fine for +// situations where the recipient of the value only intends to do static +// analysis, but ExpressionClosureType is more appropriate in situations where +// the recipient will eventually evaluate the given expression. +var ExpressionType cty.Type + +// ExpressionVal returns a new cty value of type ExpressionType, wrapping the +// given expression. +func ExpressionVal(expr hcl.Expression) cty.Value { + return cty.CapsuleVal(ExpressionType, &expr) +} + +// ExpressionFromVal returns the expression encapsulated in the given value, or +// panics if the value is not a known value of ExpressionType. +func ExpressionFromVal(v cty.Value) hcl.Expression { + if !v.Type().Equals(ExpressionType) { + panic("value is not of ExpressionType") + } + ptr := v.EncapsulatedValue().(*hcl.Expression) + return *ptr +} + +// ExpressionClosureType is a cty capsule type that carries hcl.Expression +// values along with their original evaluation contexts. +// +// This is similar to ExpressionType except that during custom decoding it +// also captures the hcl.EvalContext that was provided, allowing callers to +// evaluate the expression later in the same context where it would originally +// have been evaluated, or a context derived from that one. +var ExpressionClosureType cty.Type + +// ExpressionClosure is the type encapsulated in ExpressionClosureType +type ExpressionClosure struct { + Expression hcl.Expression + EvalContext *hcl.EvalContext +} + +// ExpressionClosureVal returns a new cty value of type ExpressionClosureType, +// wrapping the given expression closure. +func ExpressionClosureVal(closure *ExpressionClosure) cty.Value { + return cty.CapsuleVal(ExpressionClosureType, closure) +} + +// Value evaluates the closure's expression using the closure's EvalContext, +// returning the result. +func (c *ExpressionClosure) Value() (cty.Value, hcl.Diagnostics) { + return c.Expression.Value(c.EvalContext) +} + +// ExpressionClosureFromVal returns the expression closure encapsulated in the +// given value, or panics if the value is not a known value of +// ExpressionClosureType. +// +// The caller MUST NOT modify the returned closure or the EvalContext inside +// it. To derive a new EvalContext, either create a child context or make +// a copy. +func ExpressionClosureFromVal(v cty.Value) *ExpressionClosure { + if !v.Type().Equals(ExpressionClosureType) { + panic("value is not of ExpressionClosureType") + } + return v.EncapsulatedValue().(*ExpressionClosure) +} + +func init() { + // Getting hold of a reflect.Type for hcl.Expression is a bit tricky because + // it's an interface type, but we can do it with some indirection. + goExpressionType := reflect.TypeOf((*hcl.Expression)(nil)).Elem() + + ExpressionType = cty.CapsuleWithOps("expression", goExpressionType, &cty.CapsuleOps{ + ExtensionData: func(key interface{}) interface{} { + switch key { + case CustomExpressionDecoder: + return CustomExpressionDecoderFunc( + func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { + return ExpressionVal(expr), nil + }, + ) + default: + return nil + } + }, + TypeGoString: func(_ reflect.Type) string { + return "customdecode.ExpressionType" + }, + GoString: func(raw interface{}) string { + exprPtr := raw.(*hcl.Expression) + return fmt.Sprintf("customdecode.ExpressionVal(%#v)", *exprPtr) + }, + RawEquals: func(a, b interface{}) bool { + aPtr := a.(*hcl.Expression) + bPtr := b.(*hcl.Expression) + return reflect.DeepEqual(*aPtr, *bPtr) + }, + }) + ExpressionClosureType = cty.CapsuleWithOps("expression closure", reflect.TypeOf(ExpressionClosure{}), &cty.CapsuleOps{ + ExtensionData: func(key interface{}) interface{} { + switch key { + case CustomExpressionDecoder: + return CustomExpressionDecoderFunc( + func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { + return ExpressionClosureVal(&ExpressionClosure{ + Expression: expr, + EvalContext: ctx, + }), nil + }, + ) + default: + return nil + } + }, + TypeGoString: func(_ reflect.Type) string { + return "customdecode.ExpressionClosureType" + }, + GoString: func(raw interface{}) string { + closure := raw.(*ExpressionClosure) + return fmt.Sprintf("customdecode.ExpressionClosureVal(%#v)", closure) + }, + RawEquals: func(a, b interface{}) bool { + closureA := a.(*ExpressionClosure) + closureB := b.(*ExpressionClosure) + // The expression itself compares by deep equality, but EvalContexts + // conventionally compare by pointer identity, so we'll comply + // with both conventions here by testing them separately. + return closureA.EvalContext == closureB.EvalContext && + reflect.DeepEqual(closureA.Expression, closureB.Expression) + }, + }) +} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md b/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md new file mode 100644 index 0000000000..5d56eeca83 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md @@ -0,0 +1,44 @@ +# "Try" and "can" functions + +This Go package contains two `cty` functions intended for use in an +`hcl.EvalContext` when evaluating HCL native syntax expressions. + +The first function `try` attempts to evaluate each of its argument expressions +in order until one produces a result without any errors. + +```hcl +try(non_existent_variable, 2) # returns 2 +``` + +If none of the expressions succeed, the function call fails with all of the +errors it encountered. + +The second function `can` is similar except that it ignores the result of +the given expression altogether and simply returns `true` if the expression +produced a successful result or `false` if it produced errors. + +Both of these are primarily intended for working with deep data structures +which might not have a dependable shape. For example, we can use `try` to +attempt to fetch a value from deep inside a data structure but produce a +default value if any step of the traversal fails: + +```hcl +result = try(foo.deep[0].lots.of["traversals"], null) +``` + +The final result to `try` should generally be some sort of constant value that +will always evaluate successfully. + +## Using these functions + +Languages built on HCL can make `try` and `can` available to user code by +exporting them in the `hcl.EvalContext` used for expression evaluation: + +```go +ctx := &hcl.EvalContext{ + Functions: map[string]function.Function{ + "try": tryfunc.TryFunc, + "can": tryfunc.CanFunc, + }, +} +``` diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go b/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go new file mode 100644 index 0000000000..2f4862f4a3 --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go @@ -0,0 +1,150 @@ +// Package tryfunc contains some optional functions that can be exposed in +// HCL-based languages to allow authors to test whether a particular expression +// can succeed and take dynamic action based on that result. +// +// These functions are implemented in terms of the customdecode extension from +// the sibling directory "customdecode", and so they are only useful when +// used within an HCL EvalContext. Other systems using cty functions are +// unlikely to support the HCL-specific "customdecode" extension. +package tryfunc + +import ( + "errors" + "fmt" + "strings" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/ext/customdecode" + "github.com/zclconf/go-cty/cty" + "github.com/zclconf/go-cty/cty/function" +) + +// TryFunc is a variadic function that tries to evaluate all of is arguments +// in sequence until one succeeds, in which case it returns that result, or +// returns an error if none of them succeed. +var TryFunc function.Function + +// CanFunc tries to evaluate the expression given in its first argument. +var CanFunc function.Function + +func init() { + TryFunc = function.New(&function.Spec{ + VarParam: &function.Parameter{ + Name: "expressions", + Type: customdecode.ExpressionClosureType, + }, + Type: func(args []cty.Value) (cty.Type, error) { + v, err := try(args) + if err != nil { + return cty.NilType, err + } + return v.Type(), nil + }, + Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { + return try(args) + }, + }) + CanFunc = function.New(&function.Spec{ + Params: []function.Parameter{ + { + Name: "expression", + Type: customdecode.ExpressionClosureType, + }, + }, + Type: function.StaticReturnType(cty.Bool), + Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { + return can(args[0]) + }, + }) +} + +func try(args []cty.Value) (cty.Value, error) { + if len(args) == 0 { + return cty.NilVal, errors.New("at least one argument is required") + } + + // We'll collect up all of the diagnostics we encounter along the way + // and report them all if none of the expressions succeed, so that the + // user might get some hints on how to make at least one succeed. + var diags hcl.Diagnostics + for _, arg := range args { + closure := customdecode.ExpressionClosureFromVal(arg) + if dependsOnUnknowns(closure.Expression, closure.EvalContext) { + // We can't safely decide if this expression will succeed yet, + // and so our entire result must be unknown until we have + // more information. + return cty.DynamicVal, nil + } + + v, moreDiags := closure.Value() + diags = append(diags, moreDiags...) + if moreDiags.HasErrors() { + continue // try the next one, if there is one to try + } + return v, nil // ignore any accumulated diagnostics if one succeeds + } + + // If we fall out here then none of the expressions succeeded, and so + // we must have at least one diagnostic and we'll return all of them + // so that the user can see the errors related to whichever one they + // were expecting to have succeeded in this case. + // + // Because our function must return a single error value rather than + // diagnostics, we'll construct a suitable error message string + // that will make sense in the context of the function call failure + // diagnostic HCL will eventually wrap this in. + var buf strings.Builder + buf.WriteString("no expression succeeded:\n") + for _, diag := range diags { + if diag.Subject != nil { + buf.WriteString(fmt.Sprintf("- %s (at %s)\n %s\n", diag.Summary, diag.Subject, diag.Detail)) + } else { + buf.WriteString(fmt.Sprintf("- %s\n %s\n", diag.Summary, diag.Detail)) + } + } + buf.WriteString("\nAt least one expression must produce a successful result") + return cty.NilVal, errors.New(buf.String()) +} + +func can(arg cty.Value) (cty.Value, error) { + closure := customdecode.ExpressionClosureFromVal(arg) + if dependsOnUnknowns(closure.Expression, closure.EvalContext) { + // Can't decide yet, then. + return cty.UnknownVal(cty.Bool), nil + } + + _, diags := closure.Value() + if diags.HasErrors() { + return cty.False, nil + } + return cty.True, nil +} + +// dependsOnUnknowns returns true if any of the variables that the given +// expression might access are unknown values or contain unknown values. +// +// This is a conservative result that prefers to return true if there's any +// chance that the expression might derive from an unknown value during its +// evaluation; it is likely to produce false-positives for more complex +// expressions involving deep data structures. +func dependsOnUnknowns(expr hcl.Expression, ctx *hcl.EvalContext) bool { + for _, traversal := range expr.Variables() { + val, diags := traversal.TraverseAbs(ctx) + if diags.HasErrors() { + // If the traversal returned a definitive error then it must + // not traverse through any unknowns. + continue + } + if !val.IsWhollyKnown() { + // The value will be unknown if either it refers directly to + // an unknown value or if the traversal moves through an unknown + // collection. We're using IsWhollyKnown, so this also catches + // situations where the traversal refers to a compound data + // structure that contains any unknown values. That's important, + // because during evaluation the expression might evaluate more + // deeply into this structure and encounter the unknowns. + return true + } + } + return false +} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go new file mode 100644 index 0000000000..5462d82c3c --- /dev/null +++ b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go @@ -0,0 +1,118 @@ +package typeexpr + +import ( + "fmt" + "reflect" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/ext/customdecode" + "github.com/zclconf/go-cty/cty" + "github.com/zclconf/go-cty/cty/convert" + "github.com/zclconf/go-cty/cty/function" +) + +// TypeConstraintType is a cty capsule type that allows cty type constraints to +// be used as values. +// +// If TypeConstraintType is used in a context supporting the +// customdecode.CustomExpressionDecoder extension then it will implement +// expression decoding using the TypeConstraint function, thus allowing +// type expressions to be used in contexts where value expressions might +// normally be expected, such as in arguments to function calls. +var TypeConstraintType cty.Type + +// TypeConstraintVal constructs a cty.Value whose type is +// TypeConstraintType. +func TypeConstraintVal(ty cty.Type) cty.Value { + return cty.CapsuleVal(TypeConstraintType, &ty) +} + +// TypeConstraintFromVal extracts the type from a cty.Value of +// TypeConstraintType that was previously constructed using TypeConstraintVal. +// +// If the given value isn't a known, non-null value of TypeConstraintType +// then this function will panic. +func TypeConstraintFromVal(v cty.Value) cty.Type { + if !v.Type().Equals(TypeConstraintType) { + panic("value is not of TypeConstraintType") + } + ptr := v.EncapsulatedValue().(*cty.Type) + return *ptr +} + +// ConvertFunc is a cty function that implements type conversions. +// +// Its signature is as follows: +// convert(value, type_constraint) +// +// ...where type_constraint is a type constraint expression as defined by +// typeexpr.TypeConstraint. +// +// It relies on HCL's customdecode extension and so it's not suitable for use +// in non-HCL contexts or if you are using a HCL syntax implementation that +// does not support customdecode for function arguments. However, it _is_ +// supported for function calls in the HCL native expression syntax. +var ConvertFunc function.Function + +func init() { + TypeConstraintType = cty.CapsuleWithOps("type constraint", reflect.TypeOf(cty.Type{}), &cty.CapsuleOps{ + ExtensionData: func(key interface{}) interface{} { + switch key { + case customdecode.CustomExpressionDecoder: + return customdecode.CustomExpressionDecoderFunc( + func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { + ty, diags := TypeConstraint(expr) + if diags.HasErrors() { + return cty.NilVal, diags + } + return TypeConstraintVal(ty), nil + }, + ) + default: + return nil + } + }, + TypeGoString: func(_ reflect.Type) string { + return "typeexpr.TypeConstraintType" + }, + GoString: func(raw interface{}) string { + tyPtr := raw.(*cty.Type) + return fmt.Sprintf("typeexpr.TypeConstraintVal(%#v)", *tyPtr) + }, + RawEquals: func(a, b interface{}) bool { + aPtr := a.(*cty.Type) + bPtr := b.(*cty.Type) + return (*aPtr).Equals(*bPtr) + }, + }) + + ConvertFunc = function.New(&function.Spec{ + Params: []function.Parameter{ + { + Name: "value", + Type: cty.DynamicPseudoType, + AllowNull: true, + AllowDynamicType: true, + }, + { + Name: "type", + Type: TypeConstraintType, + }, + }, + Type: func(args []cty.Value) (cty.Type, error) { + wantTypePtr := args[1].EncapsulatedValue().(*cty.Type) + got, err := convert.Convert(args[0], *wantTypePtr) + if err != nil { + return cty.NilType, function.NewArgError(0, err) + } + return got.Type(), nil + }, + Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { + v, err := convert.Convert(args[0], retType) + if err != nil { + return cty.NilVal, function.NewArgError(0, err) + } + return v, nil + }, + }) +} diff --git a/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go b/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go index 7ba08eee00..f0d589d777 100644 --- a/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go +++ b/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go @@ -147,7 +147,9 @@ func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) if len(blocks) == 0 { if isSlice || isPtr { - val.Field(fieldIdx).Set(reflect.Zero(field.Type)) + if val.Field(fieldIdx).IsNil() { + val.Field(fieldIdx).Set(reflect.Zero(field.Type)) + } } else { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, @@ -166,11 +168,20 @@ func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) if isPtr { elemType = reflect.PtrTo(ty) } - sli := reflect.MakeSlice(reflect.SliceOf(elemType), len(blocks), len(blocks)) + sli := val.Field(fieldIdx) + if sli.IsNil() { + sli = reflect.MakeSlice(reflect.SliceOf(elemType), len(blocks), len(blocks)) + } for i, block := range blocks { if isPtr { - v := reflect.New(ty) + if i >= sli.Len() { + sli = reflect.Append(sli, reflect.New(ty)) + } + v := sli.Index(i) + if v.IsNil() { + v = reflect.New(ty) + } diags = append(diags, decodeBlockToValue(block, ctx, v.Elem())...) sli.Index(i).Set(v) } else { @@ -178,12 +189,19 @@ func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) } } + if sli.Len() > len(blocks) { + sli.SetLen(len(blocks)) + } + val.Field(fieldIdx).Set(sli) default: block := blocks[0] if isPtr { - v := reflect.New(ty) + v := val.Field(fieldIdx) + if v.IsNil() { + v = reflect.New(ty) + } diags = append(diags, decodeBlockToValue(block, ctx, v.Elem())...) val.Field(fieldIdx).Set(v) } else { diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go index 6fb284a8f7..f67d989e54 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go @@ -760,7 +760,7 @@ Traversal: Each: travExpr, Item: itemExpr, - SrcRange: hcl.RangeBetween(dot.Range, lastRange), + SrcRange: hcl.RangeBetween(from.Range(), lastRange), MarkerRange: hcl.RangeBetween(dot.Range, marker.Range), } @@ -819,7 +819,7 @@ Traversal: Each: travExpr, Item: itemExpr, - SrcRange: hcl.RangeBetween(open.Range, travExpr.Range()), + SrcRange: hcl.RangeBetween(from.Range(), travExpr.Range()), MarkerRange: hcl.RangeBetween(open.Range, close.Range), } @@ -867,8 +867,9 @@ Traversal: Collection: ret, Key: keyExpr, - SrcRange: rng, - OpenRange: open.Range, + SrcRange: hcl.RangeBetween(from.Range(), rng), + OpenRange: open.Range, + BracketRange: rng, } } } @@ -899,7 +900,7 @@ func makeRelativeTraversal(expr Expression, next hcl.Traverser, rng hcl.Range) E return &RelativeTraversalExpr{ Source: expr, Traversal: hcl.Traversal{next}, - SrcRange: rng, + SrcRange: hcl.RangeBetween(expr.Range(), rng), } } } diff --git a/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go b/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go index 854e71690b..073c30871e 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go @@ -21,6 +21,29 @@ func newExpression() *Expression { } } +// NewExpressionRaw constructs an expression containing the given raw tokens. +// +// There is no automatic validation that the given tokens produce a valid +// expression. Callers of thus function must take care to produce invalid +// expression tokens. Where possible, use the higher-level functions +// NewExpressionLiteral or NewExpressionAbsTraversal instead. +// +// Because NewExpressionRaw does not interpret the given tokens in any way, +// an expression created by NewExpressionRaw will produce an empty result +// for calls to its method Variables, even if the given token sequence +// contains a subslice that would normally be interpreted as a traversal under +// parsing. +func NewExpressionRaw(tokens Tokens) *Expression { + expr := newExpression() + // We copy the tokens here in order to make sure that later mutations + // by the caller don't inadvertently cause our expression to become + // invalid. + copyTokens := make(Tokens, len(tokens)) + copy(copyTokens, tokens) + expr.children.AppendUnstructuredTokens(copyTokens) + return expr +} + // NewExpressionLiteral constructs an an expression that represents the given // literal value. // diff --git a/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go b/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go index 289a30d684..4d439acd7a 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go @@ -159,12 +159,12 @@ func appendTokensForValue(val cty.Value, toks Tokens) Tokens { func appendTokensForTraversal(traversal hcl.Traversal, toks Tokens) Tokens { for _, step := range traversal { - appendTokensForTraversalStep(step, toks) + toks = appendTokensForTraversalStep(step, toks) } return toks } -func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) { +func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) Tokens { switch ts := step.(type) { case hcl.TraverseRoot: toks = append(toks, &Token{ @@ -188,7 +188,7 @@ func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) { Type: hclsyntax.TokenOBrack, Bytes: []byte{'['}, }) - appendTokensForValue(ts.Key, toks) + toks = appendTokensForValue(ts.Key, toks) toks = append(toks, &Token{ Type: hclsyntax.TokenCBrack, Bytes: []byte{']'}, @@ -196,6 +196,8 @@ func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) { default: panic(fmt.Sprintf("unsupported traversal step type %T", step)) } + + return toks } func escapeQuotedStringLit(s string) []byte { diff --git a/vendor/github.com/hashicorp/logutils/LICENSE b/vendor/github.com/hashicorp/logutils/LICENSE deleted file mode 100644 index c33dcc7c92..0000000000 --- a/vendor/github.com/hashicorp/logutils/LICENSE +++ /dev/null @@ -1,354 +0,0 @@ -Mozilla Public License, version 2.0 - -1. Definitions - -1.1. “Contributor” - - means each individual or legal entity that creates, contributes to the - creation of, or owns Covered Software. - -1.2. “Contributor Version” - - means the combination of the Contributions of others (if any) used by a - Contributor and that particular Contributor’s Contribution. - -1.3. “Contribution” - - means Covered Software of a particular Contributor. - -1.4. “Covered Software” - - means Source Code Form to which the initial Contributor has attached the - notice in Exhibit A, the Executable Form of such Source Code Form, and - Modifications of such Source Code Form, in each case including portions - thereof. - -1.5. “Incompatible With Secondary Licenses” - means - - a. that the initial Contributor has attached the notice described in - Exhibit B to the Covered Software; or - - b. that the Covered Software was made available under the terms of version - 1.1 or earlier of the License, but not also under the terms of a - Secondary License. - -1.6. “Executable Form” - - means any form of the work other than Source Code Form. - -1.7. “Larger Work” - - means a work that combines Covered Software with other material, in a separate - file or files, that is not Covered Software. - -1.8. “License” - - means this document. - -1.9. “Licensable” - - means having the right to grant, to the maximum extent possible, whether at the - time of the initial grant or subsequently, any and all of the rights conveyed by - this License. - -1.10. “Modifications” - - means any of the following: - - a. any file in Source Code Form that results from an addition to, deletion - from, or modification of the contents of Covered Software; or - - b. any new file in Source Code Form that contains any Covered Software. - -1.11. “Patent Claims” of a Contributor - - means any patent claim(s), including without limitation, method, process, - and apparatus claims, in any patent Licensable by such Contributor that - would be infringed, but for the grant of the License, by the making, - using, selling, offering for sale, having made, import, or transfer of - either its Contributions or its Contributor Version. - -1.12. “Secondary License” - - means either the GNU General Public License, Version 2.0, the GNU Lesser - General Public License, Version 2.1, the GNU Affero General Public - License, Version 3.0, or any later versions of those licenses. - -1.13. “Source Code Form” - - means the form of the work preferred for making modifications. - -1.14. “You” (or “Your”) - - means an individual or a legal entity exercising rights under this - License. For legal entities, “You” includes any entity that controls, is - controlled by, or is under common control with You. For purposes of this - definition, “control” means (a) the power, direct or indirect, to cause - the direction or management of such entity, whether by contract or - otherwise, or (b) ownership of more than fifty percent (50%) of the - outstanding shares or beneficial ownership of such entity. - - -2. License Grants and Conditions - -2.1. Grants - - Each Contributor hereby grants You a world-wide, royalty-free, - non-exclusive license: - - a. under intellectual property rights (other than patent or trademark) - Licensable by such Contributor to use, reproduce, make available, - modify, display, perform, distribute, and otherwise exploit its - Contributions, either on an unmodified basis, with Modifications, or as - part of a Larger Work; and - - b. under Patent Claims of such Contributor to make, use, sell, offer for - sale, have made, import, and otherwise transfer either its Contributions - or its Contributor Version. - -2.2. Effective Date - - The licenses granted in Section 2.1 with respect to any Contribution become - effective for each Contribution on the date the Contributor first distributes - such Contribution. - -2.3. Limitations on Grant Scope - - The licenses granted in this Section 2 are the only rights granted under this - License. No additional rights or licenses will be implied from the distribution - or licensing of Covered Software under this License. Notwithstanding Section - 2.1(b) above, no patent license is granted by a Contributor: - - a. for any code that a Contributor has removed from Covered Software; or - - b. for infringements caused by: (i) Your and any other third party’s - modifications of Covered Software, or (ii) the combination of its - Contributions with other software (except as part of its Contributor - Version); or - - c. under Patent Claims infringed by Covered Software in the absence of its - Contributions. - - This License does not grant any rights in the trademarks, service marks, or - logos of any Contributor (except as may be necessary to comply with the - notice requirements in Section 3.4). - -2.4. Subsequent Licenses - - No Contributor makes additional grants as a result of Your choice to - distribute the Covered Software under a subsequent version of this License - (see Section 10.2) or under the terms of a Secondary License (if permitted - under the terms of Section 3.3). - -2.5. Representation - - Each Contributor represents that the Contributor believes its Contributions - are its original creation(s) or it has sufficient rights to grant the - rights to its Contributions conveyed by this License. - -2.6. Fair Use - - This License is not intended to limit any rights You have under applicable - copyright doctrines of fair use, fair dealing, or other equivalents. - -2.7. Conditions - - Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in - Section 2.1. - - -3. Responsibilities - -3.1. Distribution of Source Form - - All distribution of Covered Software in Source Code Form, including any - Modifications that You create or to which You contribute, must be under the - terms of this License. You must inform recipients that the Source Code Form - of the Covered Software is governed by the terms of this License, and how - they can obtain a copy of this License. You may not attempt to alter or - restrict the recipients’ rights in the Source Code Form. - -3.2. Distribution of Executable Form - - If You distribute Covered Software in Executable Form then: - - a. such Covered Software must also be made available in Source Code Form, - as described in Section 3.1, and You must inform recipients of the - Executable Form how they can obtain a copy of such Source Code Form by - reasonable means in a timely manner, at a charge no more than the cost - of distribution to the recipient; and - - b. You may distribute such Executable Form under the terms of this License, - or sublicense it under different terms, provided that the license for - the Executable Form does not attempt to limit or alter the recipients’ - rights in the Source Code Form under this License. - -3.3. Distribution of a Larger Work - - You may create and distribute a Larger Work under terms of Your choice, - provided that You also comply with the requirements of this License for the - Covered Software. If the Larger Work is a combination of Covered Software - with a work governed by one or more Secondary Licenses, and the Covered - Software is not Incompatible With Secondary Licenses, this License permits - You to additionally distribute such Covered Software under the terms of - such Secondary License(s), so that the recipient of the Larger Work may, at - their option, further distribute the Covered Software under the terms of - either this License or such Secondary License(s). - -3.4. Notices - - You may not remove or alter the substance of any license notices (including - copyright notices, patent notices, disclaimers of warranty, or limitations - of liability) contained within the Source Code Form of the Covered - Software, except that You may alter any license notices to the extent - required to remedy known factual inaccuracies. - -3.5. Application of Additional Terms - - You may choose to offer, and to charge a fee for, warranty, support, - indemnity or liability obligations to one or more recipients of Covered - Software. However, You may do so only on Your own behalf, and not on behalf - of any Contributor. You must make it absolutely clear that any such - warranty, support, indemnity, or liability obligation is offered by You - alone, and You hereby agree to indemnify every Contributor for any - liability incurred by such Contributor as a result of warranty, support, - indemnity or liability terms You offer. You may include additional - disclaimers of warranty and limitations of liability specific to any - jurisdiction. - -4. Inability to Comply Due to Statute or Regulation - - If it is impossible for You to comply with any of the terms of this License - with respect to some or all of the Covered Software due to statute, judicial - order, or regulation then You must: (a) comply with the terms of this License - to the maximum extent possible; and (b) describe the limitations and the code - they affect. Such description must be placed in a text file included with all - distributions of the Covered Software under this License. Except to the - extent prohibited by statute or regulation, such description must be - sufficiently detailed for a recipient of ordinary skill to be able to - understand it. - -5. Termination - -5.1. The rights granted under this License will terminate automatically if You - fail to comply with any of its terms. However, if You become compliant, - then the rights granted under this License from a particular Contributor - are reinstated (a) provisionally, unless and until such Contributor - explicitly and finally terminates Your grants, and (b) on an ongoing basis, - if such Contributor fails to notify You of the non-compliance by some - reasonable means prior to 60 days after You have come back into compliance. - Moreover, Your grants from a particular Contributor are reinstated on an - ongoing basis if such Contributor notifies You of the non-compliance by - some reasonable means, this is the first time You have received notice of - non-compliance with this License from such Contributor, and You become - compliant prior to 30 days after Your receipt of the notice. - -5.2. If You initiate litigation against any entity by asserting a patent - infringement claim (excluding declaratory judgment actions, counter-claims, - and cross-claims) alleging that a Contributor Version directly or - indirectly infringes any patent, then the rights granted to You by any and - all Contributors for the Covered Software under Section 2.1 of this License - shall terminate. - -5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user - license agreements (excluding distributors and resellers) which have been - validly granted by You or Your distributors under this License prior to - termination shall survive termination. - -6. Disclaimer of Warranty - - Covered Software is provided under this License on an “as is” basis, without - warranty of any kind, either expressed, implied, or statutory, including, - without limitation, warranties that the Covered Software is free of defects, - merchantable, fit for a particular purpose or non-infringing. The entire - risk as to the quality and performance of the Covered Software is with You. - Should any Covered Software prove defective in any respect, You (not any - Contributor) assume the cost of any necessary servicing, repair, or - correction. This disclaimer of warranty constitutes an essential part of this - License. No use of any Covered Software is authorized under this License - except under this disclaimer. - -7. Limitation of Liability - - Under no circumstances and under no legal theory, whether tort (including - negligence), contract, or otherwise, shall any Contributor, or anyone who - distributes Covered Software as permitted above, be liable to You for any - direct, indirect, special, incidental, or consequential damages of any - character including, without limitation, damages for lost profits, loss of - goodwill, work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses, even if such party shall have been - informed of the possibility of such damages. This limitation of liability - shall not apply to liability for death or personal injury resulting from such - party’s negligence to the extent applicable law prohibits such limitation. - Some jurisdictions do not allow the exclusion or limitation of incidental or - consequential damages, so this exclusion and limitation may not apply to You. - -8. Litigation - - Any litigation relating to this License may be brought only in the courts of - a jurisdiction where the defendant maintains its principal place of business - and such litigation shall be governed by laws of that jurisdiction, without - reference to its conflict-of-law provisions. Nothing in this Section shall - prevent a party’s ability to bring cross-claims or counter-claims. - -9. Miscellaneous - - This License represents the complete agreement concerning the subject matter - hereof. If any provision of this License is held to be unenforceable, such - provision shall be reformed only to the extent necessary to make it - enforceable. Any law or regulation which provides that the language of a - contract shall be construed against the drafter shall not be used to construe - this License against a Contributor. - - -10. Versions of the License - -10.1. New Versions - - Mozilla Foundation is the license steward. Except as provided in Section - 10.3, no one other than the license steward has the right to modify or - publish new versions of this License. Each version will be given a - distinguishing version number. - -10.2. Effect of New Versions - - You may distribute the Covered Software under the terms of the version of - the License under which You originally received the Covered Software, or - under the terms of any subsequent version published by the license - steward. - -10.3. Modified Versions - - If you create software not governed by this License, and you want to - create a new license for such software, you may create and use a modified - version of this License if you rename the license and remove any - references to the name of the license steward (except to note that such - modified license differs from this License). - -10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses - If You choose to distribute Source Code Form that is Incompatible With - Secondary Licenses under the terms of this version of the License, the - notice described in Exhibit B of this License must be attached. - -Exhibit A - Source Code Form License Notice - - This Source Code Form is subject to the - terms of the Mozilla Public License, v. - 2.0. If a copy of the MPL was not - distributed with this file, You can - obtain one at - http://mozilla.org/MPL/2.0/. - -If it is not possible or desirable to put the notice in a particular file, then -You may include the notice in a location (such as a LICENSE file in a relevant -directory) where a recipient would be likely to look for such a notice. - -You may add additional accurate notices of copyright ownership. - -Exhibit B - “Incompatible With Secondary Licenses” Notice - - This Source Code Form is “Incompatible - With Secondary Licenses”, as defined by - the Mozilla Public License, v. 2.0. - diff --git a/vendor/github.com/hashicorp/logutils/README.md b/vendor/github.com/hashicorp/logutils/README.md deleted file mode 100644 index 49490eaeb6..0000000000 --- a/vendor/github.com/hashicorp/logutils/README.md +++ /dev/null @@ -1,36 +0,0 @@ -# logutils - -logutils is a Go package that augments the standard library "log" package -to make logging a bit more modern, without fragmenting the Go ecosystem -with new logging packages. - -## The simplest thing that could possibly work - -Presumably your application already uses the default `log` package. To switch, you'll want your code to look like the following: - -```go -package main - -import ( - "log" - "os" - - "github.com/hashicorp/logutils" -) - -func main() { - filter := &logutils.LevelFilter{ - Levels: []logutils.LogLevel{"DEBUG", "WARN", "ERROR"}, - MinLevel: logutils.LogLevel("WARN"), - Writer: os.Stderr, - } - log.SetOutput(filter) - - log.Print("[DEBUG] Debugging") // this will not print - log.Print("[WARN] Warning") // this will - log.Print("[ERROR] Erring") // and so will this - log.Print("Message I haven't updated") // and so will this -} -``` - -This logs to standard error exactly like go's standard logger. Any log messages you haven't converted to have a level will continue to print as before. diff --git a/vendor/github.com/hashicorp/logutils/go.mod b/vendor/github.com/hashicorp/logutils/go.mod deleted file mode 100644 index ba38a45764..0000000000 --- a/vendor/github.com/hashicorp/logutils/go.mod +++ /dev/null @@ -1 +0,0 @@ -module github.com/hashicorp/logutils diff --git a/vendor/github.com/hashicorp/logutils/level.go b/vendor/github.com/hashicorp/logutils/level.go deleted file mode 100644 index 6381bf1629..0000000000 --- a/vendor/github.com/hashicorp/logutils/level.go +++ /dev/null @@ -1,81 +0,0 @@ -// Package logutils augments the standard log package with levels. -package logutils - -import ( - "bytes" - "io" - "sync" -) - -type LogLevel string - -// LevelFilter is an io.Writer that can be used with a logger that -// will filter out log messages that aren't at least a certain level. -// -// Once the filter is in use somewhere, it is not safe to modify -// the structure. -type LevelFilter struct { - // Levels is the list of log levels, in increasing order of - // severity. Example might be: {"DEBUG", "WARN", "ERROR"}. - Levels []LogLevel - - // MinLevel is the minimum level allowed through - MinLevel LogLevel - - // The underlying io.Writer where log messages that pass the filter - // will be set. - Writer io.Writer - - badLevels map[LogLevel]struct{} - once sync.Once -} - -// Check will check a given line if it would be included in the level -// filter. -func (f *LevelFilter) Check(line []byte) bool { - f.once.Do(f.init) - - // Check for a log level - var level LogLevel - x := bytes.IndexByte(line, '[') - if x >= 0 { - y := bytes.IndexByte(line[x:], ']') - if y >= 0 { - level = LogLevel(line[x+1 : x+y]) - } - } - - _, ok := f.badLevels[level] - return !ok -} - -func (f *LevelFilter) Write(p []byte) (n int, err error) { - // Note in general that io.Writer can receive any byte sequence - // to write, but the "log" package always guarantees that we only - // get a single line. We use that as a slight optimization within - // this method, assuming we're dealing with a single, complete line - // of log data. - - if !f.Check(p) { - return len(p), nil - } - - return f.Writer.Write(p) -} - -// SetMinLevel is used to update the minimum log level -func (f *LevelFilter) SetMinLevel(min LogLevel) { - f.MinLevel = min - f.init() -} - -func (f *LevelFilter) init() { - badLevels := make(map[LogLevel]struct{}) - for _, level := range f.Levels { - if level == f.MinLevel { - break - } - badLevels[level] = struct{}{} - } - f.badLevels = badLevels -} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go index faa93ed6fb..a070f76e04 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go @@ -52,12 +52,12 @@ func (m *Module) init(diags Diagnostics) { // case so callers can easily recognize it. for _, r := range m.ManagedResources { if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = []string{} + m.RequiredProviders[r.Provider.Name] = &ProviderRequirement{} } } for _, r := range m.DataResources { if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = []string{} + m.RequiredProviders[r.Provider.Name] = &ProviderRequirement{} } } diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go index 86ffdf11dd..c79b033b6b 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go @@ -267,17 +267,15 @@ func loadModuleLegacyHCL(dir string) (*Module, Diagnostics) { if err != nil { return nil, diagnosticsErrorf("invalid provider block at %s: %s", item.Pos(), err) } - - if block.Version != "" { - mod.RequiredProviders[name] = append(mod.RequiredProviders[name], block.Version) - } - // Even if there wasn't an explicit version required, we still // need an entry in our map to signal the unversioned dependency. if _, exists := mod.RequiredProviders[name]; !exists { - mod.RequiredProviders[name] = []string{} + mod.RequiredProviders[name] = &ProviderRequirement{} } + if block.Version != "" { + mod.RequiredProviders[name].VersionConstraints = append(mod.RequiredProviders[name].VersionConstraints, block.Version) + } } } } diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go index 65ddb23073..63027d1841 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go @@ -9,8 +9,8 @@ type Module struct { Variables map[string]*Variable `json:"variables"` Outputs map[string]*Output `json:"outputs"` - RequiredCore []string `json:"required_core,omitempty"` - RequiredProviders map[string][]string `json:"required_providers"` + RequiredCore []string `json:"required_core,omitempty"` + RequiredProviders map[string]*ProviderRequirement `json:"required_providers"` ManagedResources map[string]*Resource `json:"managed_resources"` DataResources map[string]*Resource `json:"data_resources"` @@ -27,7 +27,7 @@ func newModule(path string) *Module { Path: path, Variables: make(map[string]*Variable), Outputs: make(map[string]*Output), - RequiredProviders: make(map[string][]string), + RequiredProviders: make(map[string]*ProviderRequirement), ManagedResources: make(map[string]*Resource), DataResources: make(map[string]*Resource), ModuleCalls: make(map[string]*ModuleCall), diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go index d924837785..157c8c2c15 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go @@ -1,5 +1,11 @@ package tfconfig +import ( + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/hcl/v2/gohcl" + "github.com/zclconf/go-cty/cty/gocty" +) + // ProviderRef is a reference to a provider configuration within a module. // It represents the contents of a "provider" argument in a resource, or // a value in the "providers" map for a module call. @@ -7,3 +13,73 @@ type ProviderRef struct { Name string `json:"name"` Alias string `json:"alias,omitempty"` // Empty if the default provider configuration is referenced } + +type ProviderRequirement struct { + Source string `json:"source,omitempty"` + VersionConstraints []string `json:"version_constraints,omitempty"` +} + +func decodeRequiredProvidersBlock(block *hcl.Block) (map[string]*ProviderRequirement, hcl.Diagnostics) { + attrs, diags := block.Body.JustAttributes() + reqs := make(map[string]*ProviderRequirement) + for name, attr := range attrs { + expr, err := attr.Expr.Value(nil) + if err != nil { + diags = append(diags, err...) + } + + switch { + case expr.Type().IsPrimitiveType(): + var version string + valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) + diags = append(diags, valDiags...) + if !valDiags.HasErrors() { + reqs[name] = &ProviderRequirement{ + VersionConstraints: []string{version}, + } + } + + case expr.Type().IsObjectType(): + var pr ProviderRequirement + if expr.Type().HasAttribute("version") { + var version string + err := gocty.FromCtyValue(expr.GetAttr("version"), &version) + if err == nil { + pr.VersionConstraints = append(pr.VersionConstraints, version) + } else { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unsuitable value type", + Detail: "Unsuitable value: string required", + Subject: attr.Expr.Range().Ptr(), + }) + } + } + if expr.Type().HasAttribute("source") { + var source string + err := gocty.FromCtyValue(expr.GetAttr("source"), &source) + if err == nil { + pr.Source = source + } else { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unsuitable value type", + Detail: "Unsuitable value: string required", + Subject: attr.Expr.Range().Ptr(), + }) + } + } + reqs[name] = &pr + + default: + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unsuitable value type", + Detail: "Unsuitable value: string required", + Subject: attr.Expr.Range().Ptr(), + }) + } + } + + return reqs, diags +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go index 6bd92f7778..75627cf02e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go @@ -7,8 +7,6 @@ import ( "os" "strings" "syscall" - - "github.com/hashicorp/logutils" ) // These are the environmental variables that determine if we log, and if @@ -18,13 +16,14 @@ const ( EnvLogFile = "TF_LOG_PATH" // Set to a file ) -var ValidLevels = []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} +// ValidLevels are the log level names that Terraform recognizes. +var ValidLevels = []LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} // LogOutput determines where we should send logs (if anywhere) and the log level. func LogOutput() (logOutput io.Writer, err error) { logOutput = ioutil.Discard - logLevel := LogLevel() + logLevel := CurrentLogLevel() if logLevel == "" { return } @@ -38,14 +37,21 @@ func LogOutput() (logOutput io.Writer, err error) { } } - // This was the default since the beginning - logOutput = &logutils.LevelFilter{ + if logLevel == "TRACE" { + // Just pass through logs directly then, without any level filtering at all. + return logOutput, nil + } + + // Otherwise we'll use our level filter, which is a heuristic-based + // best effort thing that is not totally reliable but helps to reduce + // the volume of logs in some cases. + logOutput = &LevelFilter{ Levels: ValidLevels, - MinLevel: logutils.LogLevel(logLevel), + MinLevel: LogLevel(logLevel), Writer: logOutput, } - return + return logOutput, nil } // SetOutput checks for a log destination with LogOutput, and calls @@ -64,8 +70,8 @@ func SetOutput() { log.SetOutput(out) } -// LogLevel returns the current log level string based the environment vars -func LogLevel() string { +// CurrentLogLevel returns the current log level string based the environment vars +func CurrentLogLevel() string { envLevel := os.Getenv(EnvLog) if envLevel == "" { return "" @@ -79,13 +85,16 @@ func LogLevel() string { log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v", envLevel, ValidLevels) } + if logLevel != "TRACE" { + log.Printf("[WARN] Log levels other than TRACE are currently unreliable, and are supported only for backward compatibility.\n Use TF_LOG=TRACE to see Terraform's internal logs.\n ----") + } return logLevel } // IsDebugOrHigher returns whether or not the current log level is debug or trace func IsDebugOrHigher() bool { - level := string(LogLevel()) + level := string(CurrentLogLevel()) return level == "DEBUG" || level == "TRACE" } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go index 561873dea1..5b74edd069 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go @@ -16,7 +16,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/terraform" ) -// testStepImportState runs an imort state test step +// testStepImportState runs an import state test step func testStepImportState( opts terraform.ContextOpts, state *terraform.State, @@ -96,7 +96,6 @@ func testStepImportState( if err != nil { return nil, err } - // Go through the new state and verify if step.ImportStateCheck != nil { var states []*terraform.InstanceState @@ -138,7 +137,7 @@ func testStepImportState( // this shouldn't happen in any reasonable case. var rsrcSchema *schema.Resource if providerAddr, diags := addrs.ParseAbsProviderConfigStr(r.Provider); !diags.HasErrors() { - providerType := providerAddr.ProviderConfig.Type + providerType := providerAddr.ProviderConfig.Type.LegacyString() if provider, ok := step.providers[providerType]; ok { if provider, ok := provider.(*schema.Provider); ok { rsrcSchema = provider.ResourcesMap[r.Type] diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go index d2c046c111..79829f969a 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go @@ -34,7 +34,7 @@ func (m ModuleInstance) InputVariable(name string) AbsInputVariableInstance { func (v AbsInputVariableInstance) String() string { if len(v.Module) == 0 { - return v.String() + return v.Variable.String() } return fmt.Sprintf("%s.%s", v.Module.String(), v.Variable.String()) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go index bb0901a26c..7b1f4e4e12 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go @@ -57,7 +57,7 @@ func ParseModuleInstance(traversal hcl.Traversal) (ModuleInstance, tfdiags.Diagn // If a reference string is coming from a source that should be identified in // error messages then the caller should instead parse it directly using a // suitable function from the HCL API and pass the traversal itself to -// ParseProviderConfigCompact. +// ParseModuleInstance. // // Error diagnostics are returned if either the parsing fails or the analysis // of the traversal fails. There is no way for the caller to distinguish the diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go index 103f8a28c3..108a45059f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go @@ -61,8 +61,9 @@ func (r Resource) DefaultProviderConfig() ProviderConfig { if under := strings.Index(typeName, "_"); under != -1 { typeName = typeName[:under] } + return ProviderConfig{ - Type: typeName, + Type: NewLegacyProvider(typeName), } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go index 0a2aa7d02e..70c86bdfea 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go @@ -70,22 +70,7 @@ func ResourceChange( } buf.WriteString(color.Color("[reset]\n")) - switch change.Action { - case plans.Create: - buf.WriteString(color.Color("[green] +[reset] ")) - case plans.Read: - buf.WriteString(color.Color("[cyan] <=[reset] ")) - case plans.Update: - buf.WriteString(color.Color("[yellow] ~[reset] ")) - case plans.DeleteThenCreate: - buf.WriteString(color.Color("[red]-[reset]/[green]+[reset] ")) - case plans.CreateThenDelete: - buf.WriteString(color.Color("[green]+[reset]/[red]-[reset] ")) - case plans.Delete: - buf.WriteString(color.Color("[red] -[reset] ")) - default: - buf.WriteString(color.Color("??? ")) - } + buf.WriteString(color.Color(DiffActionSymbol(change.Action)) + " ") switch addr.Resource.Resource.Mode { case addrs.ManagedResourceMode: @@ -502,7 +487,7 @@ func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, in ty, err := ctyjson.ImpliedType(src) // check for the special case of "null", which decodes to nil, // and just allow it to be printed out directly - if err == nil && !ty.IsPrimitiveType() && val.AsString() != "null" { + if err == nil && !ty.IsPrimitiveType() && strings.TrimSpace(val.AsString()) != "null" { jv, err := ctyjson.Unmarshal(src, ty) if err == nil { p.buf.WriteString("jsonencode(") @@ -520,6 +505,21 @@ func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, in } } } + + if strings.Contains(val.AsString(), "\n") { + // It's a multi-line string, so we want to use the multi-line + // rendering so it'll be readable. Rather than re-implement + // that here, we'll just re-use the multi-line string diff + // printer with no changes, which ends up producing the + // result we want here. + // The path argument is nil because we don't track path + // information into strings and we know that a string can't + // have any indices or attributes that might need to be marked + // as (requires replacement), which is what that argument is for. + p.writeValueDiff(val, val, indent, nil) + break + } + fmt.Fprintf(p.buf, "%q", val.AsString()) case cty.Bool: if val.True() { @@ -1014,8 +1014,9 @@ func (p *blockBodyDiffPrinter) writeActionSymbol(action plans.Action) { } func (p *blockBodyDiffPrinter) pathForcesNewResource(path cty.Path) bool { - if !p.action.IsReplace() { - // "requiredReplace" only applies when the instance is being replaced + if !p.action.IsReplace() || p.requiredReplace.Empty() { + // "requiredReplace" only applies when the instance is being replaced, + // and we should only inspect that set if it is not empty return false } return p.requiredReplace.Has(path) @@ -1071,8 +1072,8 @@ func ctySequenceDiff(old, new []cty.Value) []*plans.Change { var oldI, newI, lcsI int for oldI < len(old) || newI < len(new) || lcsI < len(lcs) { for oldI < len(old) && (lcsI >= len(lcs) || !old[oldI].RawEquals(lcs[lcsI])) { - isObjectDiff := old[oldI].Type().IsObjectType() && (newI >= len(new) || new[newI].Type().IsObjectType()) - if isObjectDiff && newI < len(new) { + isObjectDiff := old[oldI].Type().IsObjectType() && newI < len(new) && new[newI].Type().IsObjectType() && (lcsI >= len(lcs) || !new[newI].RawEquals(lcs[lcsI])) + if isObjectDiff { ret = append(ret, &plans.Change{ Action: plans.Update, Before: old[oldI], @@ -1190,3 +1191,26 @@ func ctyNullBlockSetAsEmpty(in cty.Value) cty.Value { // sets, so our result here is always a set. return cty.SetValEmpty(in.Type().ElementType()) } + +// DiffActionSymbol returns a string that, once passed through a +// colorstring.Colorize, will produce a result that can be written +// to a terminal to produce a symbol made of three printable +// characters, possibly interspersed with VT100 color codes. +func DiffActionSymbol(action plans.Action) string { + switch action { + case plans.DeleteThenCreate: + return "[red]-[reset]/[green]+[reset]" + case plans.CreateThenDelete: + return "[green]+[reset]/[red]-[reset]" + case plans.Create: + return " [green]+[reset]" + case plans.Delete: + return " [red]-[reset]" + case plans.Read: + return " [cyan]<=[reset]" + case plans.Update: + return " [yellow]~[reset]" + default: + return " ?" + } +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go index 14869ad3ca..9566a3dcab 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go @@ -138,7 +138,7 @@ func formatStateModule(p blockBodyDiffPrinter, m *states.Module, schemas *terraf } var schema *configschema.Block - provider := m.Resources[key].ProviderConfig.ProviderConfig.StringCompact() + provider := addr.DefaultProviderConfig().Absolute(m.Addr).ProviderConfig.StringCompact() if _, exists := schemas.Providers[provider]; !exists { // This should never happen in normal use because we should've // loaded all of the schemas and checked things prior to this diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go index e594ebd40f..b645ac8906 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go @@ -69,28 +69,21 @@ func shimTraversalInString(expr hcl.Expression, wantKeyword bool) (hcl.Expressio ) diags = append(diags, tDiags...) - // For initial release our deprecation warnings are disabled to allow - // a period where modules can be compatible with both old and new - // conventions. - // FIXME: Re-enable these deprecation warnings in a release prior to - // Terraform 0.13 and then remove the shims altogether for 0.13. - /* - if wantKeyword { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted keywords are deprecated", - Detail: "In this context, keywords are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this keyword to silence this warning.", - Subject: &srcRange, - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted references are deprecated", - Detail: "In this context, references are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this reference to silence this warning.", - Subject: &srcRange, - }) - } - */ + if wantKeyword { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Quoted keywords are deprecated", + Detail: "In this context, keywords are expected literally rather than in quotes. Terraform 0.11 and earlier required quotes, but quoted keywords are now deprecated and will be removed in a future version of Terraform. Remove the quotes surrounding this keyword to silence this warning.", + Subject: &srcRange, + }) + } else { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Quoted references are deprecated", + Detail: "In this context, references are expected literally rather than in quotes. Terraform 0.11 and earlier required quotes, but quoted references are now deprecated and will be removed in a future version of Terraform. Remove the quotes surrounding this reference to silence this warning.", + Subject: &srcRange, + }) + } return &hclsyntax.ScopeTraversalExpr{ Traversal: traversal, @@ -114,3 +107,58 @@ func shimIsIgnoreChangesStar(expr hcl.Expression) bool { } return val.AsString() == "*" } + +// warnForDeprecatedInterpolations returns warning diagnostics if the given +// body can be proven to contain attributes whose expressions are native +// syntax expressions consisting entirely of a single template interpolation, +// which is a deprecated way to include a non-literal value in configuration. +// +// This is a best-effort sort of thing which relies on the physical HCL native +// syntax AST, so it might not catch everything. The main goal is to catch the +// "obvious" cases in order to help spread awareness that this old form is +// deprecated, when folks copy it from older examples they've found on the +// internet that were written for Terraform 0.11 or earlier. +func warnForDeprecatedInterpolationsInBody(body hcl.Body) hcl.Diagnostics { + var diags hcl.Diagnostics + + nativeBody, ok := body.(*hclsyntax.Body) + if !ok { + // If it's not native syntax then we've nothing to do here. + return diags + } + + for _, attr := range nativeBody.Attributes { + moreDiags := warnForDeprecatedInterpolationsInExpr(attr.Expr) + diags = append(diags, moreDiags...) + } + + for _, block := range nativeBody.Blocks { + // We'll also go hunting in nested blocks + moreDiags := warnForDeprecatedInterpolationsInBody(block.Body) + diags = append(diags, moreDiags...) + } + + return diags +} + +func warnForDeprecatedInterpolationsInExpr(expr hcl.Expression) hcl.Diagnostics { + var diags hcl.Diagnostics + + if _, ok := expr.(*hclsyntax.TemplateWrapExpr); !ok { + // We're only interested in TemplateWrapExpr, because that's how + // the HCL native syntax parser represents the case of a template + // that consists entirely of a single interpolation expression, which + // is therefore subject to the special case of passing through the + // inner value without conversion to string. + return diags + } + + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Interpolation-only expressions are deprecated", + Detail: "Terraform 0.11 and earlier required all non-constant expressions to be provided via interpolation syntax, but this pattern is now deprecated. To silence this warning, remove the \"${ sequence from the start and the }\" sequence from the end of this expression, leaving just the inner expression.\n\nTemplate interpolation syntax is still used to construct strings from expressions when the template includes multiple interpolation sequences or a mixture of literal strings and interpolations. This deprecation applies only to templates that consist entirely of a single interpolation sequence.", + Subject: expr.Range().Ptr(), + }) + + return diags +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go index ebbeb3b629..840a7aa975 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go @@ -4,7 +4,6 @@ import ( "io" "os" "path/filepath" - "strings" ) // copyDir copies the src directory contents into dst. Both directories @@ -24,15 +23,6 @@ func copyDir(dst, src string) error { return nil } - if strings.HasPrefix(filepath.Base(path), ".") { - // Skip any dot files - if info.IsDir() { - return filepath.SkipDir - } else { - return nil - } - } - // The "path" has the src prefixed to it. We need to join our // destination with the path without the src on it. dstPath := filepath.Join(dst, path[len(src):]) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go index 6fb82acfbd..3a5e19e807 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go @@ -35,7 +35,7 @@ func (p *Provider) merge(op *Provider) hcl.Diagnostics { return diags } -func mergeProviderVersionConstraints(recv map[string][]VersionConstraint, ovrd []*ProviderRequirement) { +func mergeProviderVersionConstraints(recv map[string]ProviderRequirements, ovrd []*RequiredProvider) { // Any provider name that's mentioned in the override gets nilled out in // our map so that we'll rebuild it below. Any provider not mentioned is // left unchanged. @@ -43,7 +43,8 @@ func mergeProviderVersionConstraints(recv map[string][]VersionConstraint, ovrd [ delete(recv, reqd.Name) } for _, reqd := range ovrd { - recv[reqd.Name] = append(recv[reqd.Name], reqd.Requirement) + fqn := addrs.NewLegacyProvider(reqd.Name) + recv[reqd.Name] = ProviderRequirements{Type: fqn, VersionConstraints: []VersionConstraint{reqd.Requirement}} } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go index 8c8398e0b7..6b471bc7f9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go @@ -2,6 +2,7 @@ package configs import ( "fmt" + "unicode" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/ext/typeexpr" @@ -12,7 +13,7 @@ import ( ) // A consistent detail message for all "not a valid identifier" diagnostics. -const badIdentifierDetail = "A name must start with a letter and may contain only letters, digits, underscores, and dashes." +const badIdentifierDetail = "A name must start with a letter or underscore and may contain only letters, digits, underscores, and dashes." // Variable represents a "variable" block in a module or file. type Variable struct { @@ -21,6 +22,7 @@ type Variable struct { Default cty.Value Type cty.Type ParsingMode VariableParsingMode + Validations []*VariableValidation DescriptionSet bool @@ -117,6 +119,21 @@ func decodeVariableBlock(block *hcl.Block, override bool) (*Variable, hcl.Diagno v.Default = val } + for _, block := range content.Blocks { + switch block.Type { + + case "validation": + vv, moreDiags := decodeVariableValidationBlock(v.Name, block, override) + diags = append(diags, moreDiags...) + v.Validations = append(v.Validations, vv) + + default: + // The above cases should be exhaustive for all block types + // defined in variableBlockSchema + panic(fmt.Sprintf("unhandled block type %q", block.Type)) + } + } + return v, diags } @@ -136,10 +153,28 @@ func decodeVariableType(expr hcl.Expression) (cty.Type, VariableParsingMode, hcl str := val.AsString() switch str { case "string": + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Quoted type constraints are deprecated", + Detail: "Terraform 0.11 and earlier required type constraints to be given in quotes, but that form is now deprecated and will be removed in a future version of Terraform. To silence this warning, remove the quotes around \"string\".", + Subject: expr.Range().Ptr(), + }) return cty.String, VariableParseLiteral, diags case "list": + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Quoted type constraints are deprecated", + Detail: "Terraform 0.11 and earlier required type constraints to be given in quotes, but that form is now deprecated and will be removed in a future version of Terraform. To silence this warning, remove the quotes around \"list\" and write list(string) instead to explicitly indicate that the list elements are strings.", + Subject: expr.Range().Ptr(), + }) return cty.List(cty.DynamicPseudoType), VariableParseHCL, diags case "map": + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Quoted type constraints are deprecated", + Detail: "Terraform 0.11 and earlier required type constraints to be given in quotes, but that form is now deprecated and will be removed in a future version of Terraform. To silence this warning, remove the quotes around \"map\" and write map(string) instead to explicitly indicate that the map elements are strings.", + Subject: expr.Range().Ptr(), + }) return cty.Map(cty.DynamicPseudoType), VariableParseHCL, diags default: return cty.DynamicPseudoType, VariableParseHCL, hcl.Diagnostics{{ @@ -177,6 +212,12 @@ func decodeVariableType(expr hcl.Expression) (cty.Type, VariableParsingMode, hcl } } +// Required returns true if this variable is required to be set by the caller, +// or false if there is a default value that will be used when it isn't set. +func (v *Variable) Required() bool { + return v.Default == cty.NilVal +} + // VariableParsingMode defines how values of a particular variable given by // text-only mechanisms (command line arguments and environment variables) // should be parsed to produce the final value. @@ -224,6 +265,157 @@ func (m VariableParsingMode) Parse(name, value string) (cty.Value, hcl.Diagnosti } } +// VariableValidation represents a configuration-defined validation rule +// for a particular input variable, given as a "validation" block inside +// a "variable" block. +type VariableValidation struct { + // Condition is an expression that refers to the variable being tested + // and contains no other references. The expression must return true + // to indicate that the value is valid or false to indicate that it is + // invalid. If the expression produces an error, that's considered a bug + // in the module defining the validation rule, not an error in the caller. + Condition hcl.Expression + + // ErrorMessage is one or more full sentences, which would need to be in + // English for consistency with the rest of the error message output but + // can in practice be in any language as long as it ends with a period. + // The message should describe what is required for the condition to return + // true in a way that would make sense to a caller of the module. + ErrorMessage string + + DeclRange hcl.Range +} + +func decodeVariableValidationBlock(varName string, block *hcl.Block, override bool) (*VariableValidation, hcl.Diagnostics) { + var diags hcl.Diagnostics + vv := &VariableValidation{ + DeclRange: block.DefRange, + } + + if override { + // For now we'll just forbid overriding validation blocks, to simplify + // the initial design. If we can find a clear use-case for overriding + // validations in override files and there's a way to define it that + // isn't confusing then we could relax this. + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Can't override variable validation rules", + Detail: "Variable \"validation\" blocks cannot be used in override files.", + Subject: vv.DeclRange.Ptr(), + }) + return vv, diags + } + + content, moreDiags := block.Body.Content(variableValidationBlockSchema) + diags = append(diags, moreDiags...) + + if attr, exists := content.Attributes["condition"]; exists { + vv.Condition = attr.Expr + + // The validation condition can only refer to the variable itself, + // to ensure that the variable declaration can't create additional + // edges in the dependency graph. + goodRefs := 0 + for _, traversal := range vv.Condition.Variables() { + ref, moreDiags := addrs.ParseRef(traversal) + if !moreDiags.HasErrors() { + if addr, ok := ref.Subject.(addrs.InputVariable); ok { + if addr.Name == varName { + goodRefs++ + continue // Reference is valid + } + } + } + // If we fall out here then the reference is invalid. + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid reference in variable validation", + Detail: fmt.Sprintf("The condition for variable %q can only refer to the variable itself, using var.%s.", varName, varName), + Subject: traversal.SourceRange().Ptr(), + }) + } + if goodRefs < 1 { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid variable validation condition", + Detail: fmt.Sprintf("The condition for variable %q must refer to var.%s in order to test incoming values.", varName, varName), + Subject: attr.Expr.Range().Ptr(), + }) + } + } + + if attr, exists := content.Attributes["error_message"]; exists { + moreDiags := gohcl.DecodeExpression(attr.Expr, nil, &vv.ErrorMessage) + diags = append(diags, moreDiags...) + if !moreDiags.HasErrors() { + const errSummary = "Invalid validation error message" + switch { + case vv.ErrorMessage == "": + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: errSummary, + Detail: "An empty string is not a valid nor useful error message.", + Subject: attr.Expr.Range().Ptr(), + }) + case !looksLikeSentences(vv.ErrorMessage): + // Because we're going to include this string verbatim as part + // of a bigger error message written in our usual style in + // English, we'll require the given error message to conform + // to that. We might relax this in future if e.g. we start + // presenting these error messages in a different way, or if + // Terraform starts supporting producing error messages in + // other human languages, etc. + // For pragmatism we also allow sentences ending with + // exclamation points, but we don't mention it explicitly here + // because that's not really consistent with the Terraform UI + // writing style. + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: errSummary, + Detail: "Validation error message must be at least one full English sentence starting with an uppercase letter and ending with a period or question mark.", + Subject: attr.Expr.Range().Ptr(), + }) + } + } + } + + return vv, diags +} + +// looksLikeSentence is a simple heuristic that encourages writing error +// messages that will be presentable when included as part of a larger +// Terraform error diagnostic whose other text is written in the Terraform +// UI writing style. +// +// This is intentionally not a very strong validation since we're assuming +// that module authors want to write good messages and might just need a nudge +// about Terraform's specific style, rather than that they are going to try +// to work around these rules to write a lower-quality message. +func looksLikeSentences(s string) bool { + if len(s) < 1 { + return false + } + runes := []rune(s) // HCL guarantees that all strings are valid UTF-8 + first := runes[0] + last := runes[len(s)-1] + + // If the first rune is a letter then it must be an uppercase letter. + // (This will only see the first rune in a multi-rune combining sequence, + // but the first rune is generally the letter if any are, and if not then + // we'll just ignore it because we're primarily expecting English messages + // right now anyway, for consistency with all of Terraform's other output.) + if unicode.IsLetter(first) && !unicode.IsUpper(first) { + return false + } + + // The string must be at least one full sentence, which implies having + // sentence-ending punctuation. + // (This assumes that if a sentence ends with quotes then the period + // will be outside the quotes, which is consistent with Terraform's UI + // writing style.) + return last == '.' || last == '?' || last == '!' +} + // Output represents an "output" block in a module or file. type Output struct { Name string @@ -333,6 +525,24 @@ var variableBlockSchema = &hcl.BodySchema{ Name: "type", }, }, + Blocks: []hcl.BlockHeaderSchema{ + { + Type: "validation", + }, + }, +} + +var variableValidationBlockSchema = &hcl.BodySchema{ + Attributes: []hcl.AttributeSchema{ + { + Name: "condition", + Required: true, + }, + { + Name: "error_message", + Required: true, + }, + }, } var outputBlockSchema = &hcl.BodySchema{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go index d4cbc945c3..e8f94721d7 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go @@ -42,6 +42,12 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost file.CoreVersionConstraints, reqDiags = sniffCoreVersionRequirements(body) diags = append(diags, reqDiags...) + // We'll load the experiments first because other decoding logic in the + // loop below might depend on these experiments. + var expDiags hcl.Diagnostics + file.ActiveExperiments, expDiags = sniffActiveExperiments(body) + diags = append(diags, expDiags...) + content, contentDiags := body.Content(configFileSchema) diags = append(diags, contentDiags...) @@ -52,8 +58,9 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost content, contentDiags := block.Body.Content(terraformBlockSchema) diags = append(diags, contentDiags...) - // We ignore the "terraform_version" attribute here because - // sniffCoreVersionRequirements already dealt with that above. + // We ignore the "terraform_version" and "experiments" attributes + // here because sniffCoreVersionRequirements and + // sniffActiveExperiments already dealt with those above. for _, innerBlock := range content.Blocks { switch innerBlock.Type { @@ -68,7 +75,7 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost case "required_providers": reqs, reqsDiags := decodeRequiredProvidersBlock(innerBlock) diags = append(diags, reqsDiags...) - file.ProviderRequirements = append(file.ProviderRequirements, reqs...) + file.RequiredProviders = append(file.RequiredProviders, reqs...) default: // Should never happen because the above cases should be exhaustive @@ -148,7 +155,7 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost // able to find, but may return no constraints at all if the given body is // so invalid that it cannot be decoded at all. func sniffCoreVersionRequirements(body hcl.Body) ([]VersionConstraint, hcl.Diagnostics) { - rootContent, _, diags := body.PartialContent(configFileVersionSniffRootSchema) + rootContent, _, diags := body.PartialContent(configFileTerraformBlockSniffRootSchema) var constraints []VersionConstraint @@ -213,9 +220,8 @@ var configFileSchema = &hcl.BodySchema{ // a configuration file. var terraformBlockSchema = &hcl.BodySchema{ Attributes: []hcl.AttributeSchema{ - { - Name: "required_version", - }, + {Name: "required_version"}, + {Name: "experiments"}, }, Blocks: []hcl.BlockHeaderSchema{ { @@ -228,8 +234,9 @@ var terraformBlockSchema = &hcl.BodySchema{ }, } -// configFileVersionSniffRootSchema is a schema for sniffCoreVersionRequirements -var configFileVersionSniffRootSchema = &hcl.BodySchema{ +// configFileTerraformBlockSniffRootSchema is a schema for +// sniffCoreVersionRequirements and sniffActiveExperiments. +var configFileTerraformBlockSniffRootSchema = &hcl.BodySchema{ Blocks: []hcl.BlockHeaderSchema{ { Type: "terraform", @@ -245,3 +252,13 @@ var configFileVersionSniffBlockSchema = &hcl.BodySchema{ }, }, } + +// configFileExperimentsSniffBlockSchema is a schema for sniffActiveExperiments, +// to decode a single attribute from inside a "terraform" block. +var configFileExperimentsSniffBlockSchema = &hcl.BodySchema{ + Attributes: []hcl.AttributeSchema{ + { + Name: "experiments", + }, + }, +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go index afdd69833f..2923af93a0 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go @@ -154,9 +154,9 @@ func IsEmptyDir(path string) (bool, error) { } p := NewParser(nil) - fs, os, err := p.dirFiles(path) - if err != nil { - return false, err + fs, os, diags := p.dirFiles(path) + if diags.HasErrors() { + return false, diags } return len(fs) == 0 && len(os) == 0, nil diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go index 47b6567918..6f380860a8 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go @@ -50,6 +50,11 @@ func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { } } + // destroy provisioners can only refer to self + if pv.When == ProvisionerWhenDestroy { + diags = append(diags, onlySelfRefs(config)...) + } + if attr, exists := content.Attributes["on_failure"]; exists { expr, shimDiags := shimTraversalInString(attr.Expr, true) diags = append(diags, shimDiags...) @@ -85,8 +90,11 @@ func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { } seenConnection = block - //conn, connDiags := decodeConnectionBlock(block) - //diags = append(diags, connDiags...) + // destroy provisioners can only refer to self + if pv.When == ProvisionerWhenDestroy { + diags = append(diags, onlySelfRefs(block.Body)...) + } + pv.Connection = &Connection{ Config: block.Body, DeclRange: block.DefRange, @@ -107,6 +115,52 @@ func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { return pv, diags } +func onlySelfRefs(body hcl.Body) hcl.Diagnostics { + var diags hcl.Diagnostics + + // Provisioners currently do not use any blocks in their configuration. + // Blocks are likely to remain solely for meta parameters, but in the case + // that blocks are supported for provisioners, we will want to extend this + // to find variables in nested blocks. + attrs, _ := body.JustAttributes() + for _, attr := range attrs { + for _, v := range attr.Expr.Variables() { + valid := false + switch v.RootName() { + case "self", "path", "terraform": + valid = true + case "count": + // count must use "index" + if len(v) == 2 { + if t, ok := v[1].(hcl.TraverseAttr); ok && t.Name == "index" { + valid = true + } + } + + case "each": + if len(v) == 2 { + if t, ok := v[1].(hcl.TraverseAttr); ok && t.Name == "key" { + valid = true + } + } + } + + if !valid { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "External references from destroy provisioners are deprecated", + Detail: "Destroy-time provisioners and their connection configurations may only " + + "reference attributes of the related resource, via 'self', 'count.index', " + + "or 'each.key'.\n\nReferences to other resources during the destroy phase " + + "can cause dependency cycles and interact poorly with create_before_destroy.", + Subject: attr.Expr.Range().Ptr(), + }) + } + } + } + return diags +} + // Connection represents a "connection" block when used within either a // "resource" or "provisioner" block in a module or file. type Connection struct { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go index cd9991a389..323ce3627c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go @@ -70,12 +70,13 @@ func (r *Resource) ProviderConfigAddr() addrs.ProviderConfig { } return addrs.ProviderConfig{ - Type: r.ProviderConfigRef.Name, + Type: addrs.NewLegacyProvider(r.ProviderConfigRef.Name), Alias: r.ProviderConfigRef.Alias, } } func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { + var diags hcl.Diagnostics r := &Resource{ Mode: addrs.ManagedResourceMode, Type: block.Labels[0], @@ -85,7 +86,15 @@ func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { Managed: &ManagedResource{}, } - content, remain, diags := block.Body.PartialContent(resourceBlockSchema) + // Produce deprecation messages for any pre-0.12-style + // single-interpolation-only expressions. We do this up front here because + // then we can also catch instances inside special blocks like "connection", + // before PartialContent extracts them. + moreDiags := warnForDeprecatedInterpolationsInBody(block.Body) + diags = append(diags, moreDiags...) + + content, remain, moreDiags := block.Body.PartialContent(resourceBlockSchema) + diags = append(diags, moreDiags...) r.Config = remain if !hclsyntax.ValidIdentifier(r.Type) { @@ -264,6 +273,17 @@ func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { } } + // Now we can validate the connection block references if there are any destroy provisioners. + // TODO: should we eliminate standalone connection blocks? + if r.Managed.Connection != nil { + for _, p := range r.Managed.Provisioners { + if p.When == ProvisionerWhenDestroy { + diags = append(diags, onlySelfRefs(r.Managed.Connection.Config)...) + break + } + } + } + return r, diags } @@ -427,7 +447,7 @@ func decodeProviderConfigRef(expr hcl.Expression, argName string) (*ProviderConf // location information and keeping just the addressing information. func (r *ProviderConfigRef) Addr() addrs.ProviderConfig { return addrs.ProviderConfig{ - Type: r.Name, + Type: addrs.NewLegacyProvider(r.Name), Alias: r.Alias, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go index 5ddf8ef34c..95f3f926dd 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go @@ -15,7 +15,7 @@ import ( // been walked. If two vertices can be walked at the same time, they will be. // // Update can be called to update the graph. This can be called even during -// a walk, cahnging vertices/edges mid-walk. This should be done carefully. +// a walk, changing vertices/edges mid-walk. This should be done carefully. // If a vertex is removed but has already been executed, the result of that // execution (any error) is still returned by Wait. Changing or re-adding // a vertex that has already executed has no effect. Changing edges of diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go index e6898457b9..2ea4168757 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go @@ -940,7 +940,7 @@ var ReverseFunc = function.New(&function.Spec{ }, }) -// SetProductFunc calculates the cartesian product of two or more sets or +// SetProductFunc calculates the Cartesian product of two or more sets or // sequences. If the arguments are all lists then the result is a list of tuples, // preserving the ordering of all of the input lists. Otherwise the result is a // set of tuples. @@ -1179,7 +1179,6 @@ func sliceIndexes(args []cty.Value) (int, int, bool, error) { return startIndex, endIndex, startKnown && endKnown, nil } -// TransposeFunc contructs a function that takes a map of lists of strings and // TransposeFunc constructs a function that takes a map of lists of strings and // swaps the keys and values to produce a new map of lists of strings. var TransposeFunc = function.New(&function.Spec{ @@ -1226,6 +1225,10 @@ var TransposeFunc = function.New(&function.Spec{ outputMap[outKey] = cty.ListVal(values) } + if len(outputMap) == 0 { + return cty.MapValEmpty(cty.List(cty.String)), nil + } + return cty.MapVal(outputMap), nil }, }) @@ -1491,7 +1494,7 @@ func Reverse(list cty.Value) (cty.Value, error) { return ReverseFunc.Call([]cty.Value{list}) } -// SetProduct computes the cartesian product of sets or sequences. +// SetProduct computes the Cartesian product of sets or sequences. func SetProduct(sets ...cty.Value) (cty.Value, error) { return SetProductFunc.Call(sets) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go index c9ddf19e36..2e66be4512 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go @@ -71,7 +71,7 @@ var SortFunc = function.New(&function.Spec{ if !listVal.IsWhollyKnown() { // If some of the element values aren't known yet then we - // can't yet preduct the order of the result. + // can't yet predict the order of the result. return cty.UnknownVal(retType), nil } if listVal.LengthInt() == 0 { // Easy path @@ -123,7 +123,7 @@ var SplitFunc = function.New(&function.Spec{ }, }) -// ChompFunc constructions a function that removes newline characters at the end of a string. +// ChompFunc constructs a function that removes newline characters at the end of a string. var ChompFunc = function.New(&function.Spec{ Params: []function.Parameter{ { @@ -138,7 +138,7 @@ var ChompFunc = function.New(&function.Spec{ }, }) -// IndentFunc constructions a function that adds a given number of spaces to the +// IndentFunc constructs a function that adds a given number of spaces to the // beginnings of all but the first line in a given multi-line string. var IndentFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -163,7 +163,7 @@ var IndentFunc = function.New(&function.Spec{ }, }) -// ReplaceFunc constructions a function that searches a given string for another +// ReplaceFunc constructs a function that searches a given string for another // given substring, and replaces each occurence with a given replacement string. var ReplaceFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -201,7 +201,7 @@ var ReplaceFunc = function.New(&function.Spec{ }, }) -// TitleFunc constructions a function that converts the first letter of each word +// TitleFunc constructs a function that converts the first letter of each word // in the given string to uppercase. var TitleFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -216,7 +216,7 @@ var TitleFunc = function.New(&function.Spec{ }, }) -// TrimSpaceFunc constructions a function that removes any space characters from +// TrimSpaceFunc constructs a function that removes any space characters from // the start and end of the given string. var TrimSpaceFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -231,6 +231,69 @@ var TrimSpaceFunc = function.New(&function.Spec{ }, }) +// TrimFunc constructs a function that removes the specified characters from +// the start and end of the given string. +var TrimFunc = function.New(&function.Spec{ + Params: []function.Parameter{ + { + Name: "str", + Type: cty.String, + }, + { + Name: "cutset", + Type: cty.String, + }, + }, + Type: function.StaticReturnType(cty.String), + Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { + str := args[0].AsString() + cutset := args[1].AsString() + return cty.StringVal(strings.Trim(str, cutset)), nil + }, +}) + +// TrimPrefixFunc constructs a function that removes the specified characters from +// the start the given string. +var TrimPrefixFunc = function.New(&function.Spec{ + Params: []function.Parameter{ + { + Name: "str", + Type: cty.String, + }, + { + Name: "prefix", + Type: cty.String, + }, + }, + Type: function.StaticReturnType(cty.String), + Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { + str := args[0].AsString() + prefix := args[1].AsString() + return cty.StringVal(strings.TrimPrefix(str, prefix)), nil + }, +}) + +// TrimSuffixFunc constructs a function that removes the specified characters from +// the end of the given string. +var TrimSuffixFunc = function.New(&function.Spec{ + Params: []function.Parameter{ + { + Name: "str", + Type: cty.String, + }, + { + Name: "suffix", + Type: cty.String, + }, + }, + Type: function.StaticReturnType(cty.String), + Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { + str := args[0].AsString() + cutset := args[1].AsString() + return cty.StringVal(strings.TrimSuffix(str, cutset)), nil + }, +}) + // Join concatenates together the string elements of one or more lists with a // given separator. func Join(sep cty.Value, lists ...cty.Value) (cty.Value, error) { @@ -278,3 +341,18 @@ func Title(str cty.Value) (cty.Value, error) { func TrimSpace(str cty.Value) (cty.Value, error) { return TrimSpaceFunc.Call([]cty.Value{str}) } + +// Trim removes the specified characters from the start and end of the given string. +func Trim(str, cutset cty.Value) (cty.Value, error) { + return TrimFunc.Call([]cty.Value{str, cutset}) +} + +// TrimPrefix removes the specified prefix from the start of the given string. +func TrimPrefix(str, prefix cty.Value) (cty.Value, error) { + return TrimPrefixFunc.Call([]cty.Value{str, prefix}) +} + +// TrimSuffix removes the specified suffix from the end of the given string. +func TrimSuffix(str, suffix cty.Value) (cty.Value, error) { + return TrimSuffixFunc.Call([]cty.Value{str, suffix}) +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go index 2d45c8520e..863c504558 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go @@ -81,6 +81,11 @@ func ReadManifestSnapshot(r io.Reader) (Manifest, error) { return nil, fmt.Errorf("invalid version %q for %s: %s", record.VersionStr, record.Key, err) } } + + // Ensure Windows is using the proper modules path format after + // reading the modules manifest Dir records + record.Dir = filepath.FromSlash(record.Dir) + if _, exists := new[record.Key]; exists { // This should never happen in any valid file, so we'll catch it // and report it to avoid confusing/undefined behavior if the @@ -115,6 +120,10 @@ func (m Manifest) WriteSnapshot(w io.Writer) error { } else { record.VersionStr = "" } + + // Ensure Dir is written in a format that can be read by Linux and + // Windows nodes for remote and apply compatibility + record.Dir = filepath.ToSlash(record.Dir) write.Records = append(write.Records, record) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go index 0f48f2447d..74a5342c2e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go @@ -14,7 +14,7 @@ func AddressedTypes(providerAddrs []addrs.ProviderConfig) []string { } m := map[string]struct{}{} for _, addr := range providerAddrs { - m[addr.Type] = struct{}{} + m[addr.Type.LegacyString()] = struct{}{} } names := make([]string, 0, len(m)) @@ -34,7 +34,7 @@ func AddressedTypesAbs(providerAddrs []addrs.AbsProviderConfig) []string { } m := map[string]struct{}{} for _, addr := range providerAddrs { - m[addr.ProviderConfig.Type] = struct{}{} + m[addr.ProviderConfig.Type.LegacyString()] = struct{}{} } names := make([]string, 0, len(m)) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go index 3bb717d332..87312f929b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go @@ -29,12 +29,17 @@ type ResourceInstanceObject struct { // it was updated. Status ObjectStatus - // Dependencies is a set of other addresses in the same module which - // this instance depended on when the given attributes were evaluated. - // This is used to construct the dependency relationships for an object - // whose configuration is no longer available, such as if it has been - // removed from configuration altogether, or is now deposed. - Dependencies []addrs.Referenceable + // Dependencies is a set of absolute address to other resources this + // instance dependeded on when it was applied. This is used to construct + // the dependency relationships for an object whose configuration is no + // longer available, such as if it has been removed from configuration + // altogether, or is now deposed. + Dependencies []addrs.AbsResource + + // DependsOn corresponds to the deprecated `depends_on` field in the state. + // This field contained the configuration `depends_on` values, and some of + // the references from within a single module. + DependsOn []addrs.Referenceable } // ObjectStatus represents the status of a RemoteObject. diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go index 728ad80d12..99c0ec29e3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go @@ -53,7 +53,9 @@ type ResourceInstanceObjectSrc struct { // ResourceInstanceObject. Private []byte Status ObjectStatus - Dependencies []addrs.Referenceable + Dependencies []addrs.AbsResource + // deprecated + DependsOn []addrs.Referenceable } // Decode unmarshals the raw representation of the object attributes. Pass the @@ -86,6 +88,7 @@ func (os *ResourceInstanceObjectSrc) Decode(ty cty.Type) (*ResourceInstanceObjec Value: val, Status: os.Status, Dependencies: os.Dependencies, + DependsOn: os.DependsOn, Private: os.Private, }, nil } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go index 6b74cbfa6b..8c4c18a453 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go @@ -76,7 +76,7 @@ func (ms *Module) RemoveResource(addr addrs.Resource) { } // SetResourceInstanceCurrent saves the given instance object as the current -// generation of the resource instance with the given address, simulataneously +// generation of the resource instance with the given address, simultaneously // updating the recorded provider configuration address, dependencies, and // resource EachMode. // @@ -88,23 +88,58 @@ func (ms *Module) RemoveResource(addr addrs.Resource) { // are updated for all other instances of the same resource as a side-effect of // this call. func (ms *Module) SetResourceInstanceCurrent(addr addrs.ResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { - ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) - rs := ms.Resource(addr.Resource) - is := rs.EnsureInstance(addr.Key) - - is.Current = obj - - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) + // if the resource is nil and the object is nil, don't do anything! + // you'll probably just cause issues + if obj == nil && rs == nil { + return } - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - // Also clean up if we only expect to have one instance anyway - // and there are none. We leave the resource behind if an each mode - // is active because an empty list or map of instances is a valid state. - delete(ms.Resources, addr.Resource.String()) + if obj == nil && rs != nil { + // does the resource have any other objects? + // if not then delete the whole resource + // When deleting the resource, ensure that its EachMode is NoEach, + // as a resource with EachList or EachMap can have 0 instances and be valid + if rs.EachMode == NoEach && len(rs.Instances) == 0 { + delete(ms.Resources, addr.Resource.String()) + return + } + // check for an existing resource, now that we've ensured that rs.Instances is more than 0/not nil + is := rs.Instance(addr.Key) + if is == nil { + // if there is no instance on the resource with this address and obj is nil, return and change nothing + return + } + // if we have an instance, update the current + is.Current = obj + if !is.HasObjects() { + // If we have no objects at all then we'll clean up. + delete(rs.Instances, addr.Key) + // Delete the resource if it has no instances, but only if NoEach + if rs.EachMode == NoEach && len(rs.Instances) == 0 { + delete(ms.Resources, addr.Resource.String()) + return + } + } + // Nothing more to do here, so return! + return } + if rs == nil && obj != nil { + // We don't have have a resource so make one, which is a side effect of setResourceMeta + ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) + // now we have a resource! so update the rs value to point to it + rs = ms.Resource(addr.Resource) + } + // Get our instance from the resource; it could be there or not at this point + is := rs.Instance(addr.Key) + if is == nil { + // if we don't have a resource, create one and add to the instances + is = rs.CreateInstance(addr.Key) + // update the resource meta because we have a new instance, so EachMode may have changed + ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) + } + // Update the resource's ProviderConfig, in case the provider has updated + rs.ProviderConfig = provider + is.Current = obj } // SetResourceInstanceDeposed saves the given instance object as a deposed diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go index 32ea638acd..8f75040d4d 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go @@ -39,6 +39,13 @@ func (rs *Resource) Instance(key addrs.InstanceKey) *ResourceInstance { return rs.Instances[key] } +// CreateInstance creates an instance and adds it to the resource +func (rs *Resource) CreateInstance(key addrs.InstanceKey) *ResourceInstance { + is := NewResourceInstance() + rs.Instances[key] = is + return is +} + // EnsureInstance returns the state for the instance with the given key, // creating a new empty state for it if one doesn't already exist. // diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go index 6266aca79d..672eb393a9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go @@ -153,8 +153,17 @@ func (obj *ResourceInstanceObjectSrc) DeepCopy() *ResourceInstanceObjectSrc { // Some addrs.Referencable implementations are technically mutable, but // we treat them as immutable by convention and so we don't deep-copy here. - dependencies := make([]addrs.Referenceable, len(obj.Dependencies)) - copy(dependencies, obj.Dependencies) + var dependencies []addrs.AbsResource + if obj.Dependencies != nil { + dependencies = make([]addrs.AbsResource, len(obj.Dependencies)) + copy(dependencies, obj.Dependencies) + } + + var dependsOn []addrs.Referenceable + if obj.DependsOn != nil { + dependsOn = make([]addrs.Referenceable, len(obj.DependsOn)) + copy(dependsOn, obj.DependsOn) + } return &ResourceInstanceObjectSrc{ Status: obj.Status, @@ -163,6 +172,7 @@ func (obj *ResourceInstanceObjectSrc) DeepCopy() *ResourceInstanceObjectSrc { AttrsFlat: attrsFlat, AttrsJSON: attrsJSON, Dependencies: dependencies, + DependsOn: dependsOn, } } @@ -187,9 +197,9 @@ func (obj *ResourceInstanceObject) DeepCopy() *ResourceInstanceObject { // Some addrs.Referenceable implementations are technically mutable, but // we treat them as immutable by convention and so we don't deep-copy here. - var dependencies []addrs.Referenceable + var dependencies []addrs.AbsResource if obj.Dependencies != nil { - dependencies = make([]addrs.Referenceable, len(obj.Dependencies)) + dependencies = make([]addrs.AbsResource, len(obj.Dependencies)) copy(dependencies, obj.Dependencies) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go index 164b57f827..6315de8a69 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go @@ -181,7 +181,10 @@ func prepareStateV4(sV4 *stateV4) (*File, tfdiags.Diagnostics) { } { - depsRaw := isV4.Dependencies + // Allow both the deprecated `depends_on` and new + // `dependencies` to coexist for now so resources can be + // upgraded as they are refreshed. + depsRaw := isV4.DependsOn deps := make([]addrs.Referenceable, 0, len(depsRaw)) for _, depRaw := range depsRaw { ref, refDiags := addrs.ParseRefStr(depRaw) @@ -202,6 +205,20 @@ func prepareStateV4(sV4 *stateV4) (*File, tfdiags.Diagnostics) { } deps = append(deps, ref.Subject) } + obj.DependsOn = deps + } + + { + depsRaw := isV4.Dependencies + deps := make([]addrs.AbsResource, 0, len(depsRaw)) + for _, depRaw := range depsRaw { + addr, addrDiags := addrs.ParseAbsResourceStr(depRaw) + diags = diags.Append(addrDiags) + if addrDiags.HasErrors() { + continue + } + deps = append(deps, addr) + } obj.Dependencies = deps } @@ -466,6 +483,11 @@ func appendInstanceObjectStateV4(rs *states.Resource, is *states.ResourceInstanc deps[i] = depAddr.String() } + depOn := make([]string, len(obj.DependsOn)) + for i, depAddr := range obj.DependsOn { + depOn[i] = depAddr.String() + } + var rawKey interface{} switch tk := key.(type) { case addrs.IntKey: @@ -491,6 +513,7 @@ func appendInstanceObjectStateV4(rs *states.Resource, is *states.ResourceInstanc AttributesRaw: obj.AttrsJSON, PrivateRaw: privateRaw, Dependencies: deps, + DependsOn: depOn, }), diags } @@ -540,7 +563,8 @@ type instanceObjectStateV4 struct { PrivateRaw []byte `json:"private,omitempty"` - Dependencies []string `json:"depends_on,omitempty"` + Dependencies []string `json:"dependencies,omitempty"` + DependsOn []string `json:"depends_on,omitempty"` } // stateVersionV4 is a weird special type we use to produce our hard-coded diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go index 59c06b70b5..d55bc2f0ce 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go @@ -308,8 +308,8 @@ func hclRangeFromIndexStepAndAttribute(idxStep cty.IndexStep, attr *hcl.Attribut } stepKey := idxStep.Key.AsString() for _, kvPair := range pairs { - key, err := kvPair.Key.Value(nil) - if err != nil { + key, diags := kvPair.Key.Value(nil) + if diags.HasErrors() { return attr.Expr.Range() } if key.AsString() == stepKey { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go index 2d56dab696..d317e08261 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go @@ -11,7 +11,7 @@ import ( ) // The main version number that is being run at the moment. -var Version = "0.12.7" +var Version = "0.12.20" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go index 5a99e90064..27723faa49 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go @@ -9,6 +9,11 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" ) +// The TF_DISABLE_PLUGIN_TLS environment variable is intended only for use by +// the plugin SDK test framework. We do not recommend Terraform CLI end-users +// set this variable. +var enableAutoMTLS = os.Getenv("TF_DISABLE_PLUGIN_TLS") == "" + // ClientConfig returns a configuration object that can be used to instantiate // a client for the plugin described by the given metadata. func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig { @@ -25,7 +30,7 @@ func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig { Managed: true, Logger: logger, AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC}, - AutoMTLS: true, + AutoMTLS: enableAutoMTLS, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go index eb05c68ae3..2e31c0fc12 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go @@ -24,19 +24,12 @@ import ( type InputMode byte const ( - // InputModeVar asks for all variables - InputModeVar InputMode = 1 << iota - - // InputModeVarUnset asks for variables which are not set yet. - // InputModeVar must be set for this to have an effect. - InputModeVarUnset - // InputModeProvider asks for provider variables - InputModeProvider + InputModeProvider InputMode = 1 << iota // InputModeStd is the standard operating mode and asks for both variables // and providers. - InputModeStd = InputModeVar | InputModeProvider + InputModeStd = InputModeProvider ) // ContextOpts are the user-configurable options to create a context with @@ -154,7 +147,7 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { variables = variables.Override(opts.Variables) // Bind available provider plugins to the constraints in config - var providerFactories map[string]providers.Factory + var providerFactories map[addrs.Provider]providers.Factory if opts.ProviderResolver != nil { deps := ConfigTreeDependencies(opts.Config, state) reqd := deps.AllPluginRequirements() @@ -162,7 +155,6 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { reqd.LockExecutables(opts.ProviderSHA256s) } log.Printf("[TRACE] terraform.NewContext: resolving provider version selections") - var providerDiags tfdiags.Diagnostics providerFactories, providerDiags = resourceProviderFactories(opts.ProviderResolver, reqd) diags = diags.Append(providerDiags) @@ -171,7 +163,7 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { return nil, diags } } else { - providerFactories = make(map[string]providers.Factory) + providerFactories = make(map[addrs.Provider]providers.Factory) } components := &basicComponentFactory{ @@ -198,6 +190,18 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { log.Printf("[TRACE] terraform.NewContext: complete") + // By the time we get here, we should have values defined for all of + // the root module variables, even if some of them are "unknown". It's the + // caller's responsibility to have already handled the decoding of these + // from the various ways the CLI allows them to be set and to produce + // user-friendly error messages if they are not all present, and so + // the error message from checkInputVariables should never be seen and + // includes language asking the user to report a bug. + if config != nil { + varDiags := checkInputVariables(config.Module.Variables, variables) + diags = diags.Append(varDiags) + } + return &Context{ components: components, schemas: schemas, @@ -215,7 +219,7 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { providerInputConfig: make(map[string]map[string]cty.Value), providerSHA256s: opts.ProviderSHA256s, sh: sh, - }, nil + }, diags } func (c *Context) Schemas() *Schemas { @@ -646,14 +650,6 @@ func (c *Context) Validate() tfdiags.Diagnostics { var diags tfdiags.Diagnostics - // Validate input variables. We do this only for the values supplied - // by the root module, since child module calls are validated when we - // visit their graph nodes. - if c.config != nil { - varDiags := checkInputVariables(c.config.Module.Variables, c.variables) - diags = diags.Append(varDiags) - } - // If we have errors at this point then we probably won't be able to // construct a graph without producing redundant errors, so we'll halt early. if diags.HasErrors() { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go index b99f1afacf..c1ab94c9f7 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go @@ -2,7 +2,6 @@ package terraform import ( "context" - "fmt" "log" "sort" @@ -15,10 +14,22 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" ) -// Input asks for input to fill variables and provider configurations. +// Input asks for input to fill unset required arguments in provider +// configurations. +// // This modifies the configuration in-place, so asking for Input twice // may result in different UI output showing different current values. func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { + // This function used to be responsible for more than it is now, so its + // interface is more general than its current functionality requires. + // It now exists only to handle interactive prompts for provider + // configurations, with other prompts the responsibility of the CLI + // layer prior to calling in to this package. + // + // (Hopefully in future the remaining functionality here can move to the + // CLI layer too in order to avoid this odd situation where core code + // produces UI input prompts.) + var diags tfdiags.Diagnostics defer c.acquireRun("input")() @@ -29,85 +40,6 @@ func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { ctx := context.Background() - if mode&InputModeVar != 0 { - log.Printf("[TRACE] Context.Input: Prompting for variables") - - // Walk the variables first for the root module. We walk them in - // alphabetical order for UX reasons. - configs := c.config.Module.Variables - names := make([]string, 0, len(configs)) - for name := range configs { - names = append(names, name) - } - sort.Strings(names) - Variables: - for _, n := range names { - v := configs[n] - - // If we only care about unset variables, then we should set any - // variable that is already set. - if mode&InputModeVarUnset != 0 { - if _, isSet := c.variables[n]; isSet { - continue - } - } - - // this should only happen during tests - if c.uiInput == nil { - log.Println("[WARN] Context.uiInput is nil during input walk") - continue - } - - // Ask the user for a value for this variable - var rawValue string - retry := 0 - for { - var err error - rawValue, err = c.uiInput.Input(ctx, &InputOpts{ - Id: fmt.Sprintf("var.%s", n), - Query: fmt.Sprintf("var.%s", n), - Description: v.Description, - }) - if err != nil { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Failed to request interactive input", - fmt.Sprintf("Terraform attempted to request a value for var.%s interactively, but encountered an error: %s.", n, err), - )) - return diags - } - - if rawValue == "" && v.Default == cty.NilVal { - // Redo if it is required, but abort if we keep getting - // blank entries - if retry > 2 { - diags = diags.Append(tfdiags.Sourceless( - tfdiags.Error, - "Required variable not assigned", - fmt.Sprintf("The variable %q is required, so Terraform cannot proceed without a defined value for it.", n), - )) - continue Variables - } - retry++ - continue - } - - break - } - - val, valDiags := v.ParsingMode.Parse(n, rawValue) - diags = diags.Append(valDiags) - if diags.HasErrors() { - continue - } - - c.variables[n] = &InputValue{ - Value: val, - SourceType: ValueFromInput, - } - } - } - if mode&InputModeProvider != 0 { log.Printf("[TRACE] Context.Input: Prompting for provider arguments") @@ -164,7 +96,7 @@ func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { UIInput: c.uiInput, } - schema := c.schemas.ProviderConfig(pa.Type) + schema := c.schemas.ProviderConfig(pa.Type.LegacyString()) if schema == nil { // Could either be an incorrect config or just an incomplete // mock in tests. We'll let a later pass decide, and just diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go index 6beeaea984..05faee7813 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go @@ -24,7 +24,6 @@ import ( type EvalApply struct { Addr addrs.ResourceInstance Config *configs.Resource - Dependencies []addrs.Referenceable State **states.ResourceInstanceObject Change **plans.ResourceInstanceChange ProviderAddr addrs.AbsProviderConfig @@ -254,6 +253,8 @@ func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { } } + newStatus := states.ObjectReady + // Sometimes providers return a null value when an operation fails for some // reason, but we'd rather keep the prior state so that the error can be // corrected on a subsequent run. We must only do this for null new value @@ -266,15 +267,20 @@ func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { // If change.Action is Create then change.Before will also be null, // which is fine. newVal = change.Before + + // If we're recovering the previous state, we also want to restore the + // the tainted status of the object. + if state.Status == states.ObjectTainted { + newStatus = states.ObjectTainted + } } var newState *states.ResourceInstanceObject if !newVal.IsNull() { // null value indicates that the object is deleted, so we won't set a new state in that case newState = &states.ResourceInstanceObject{ - Status: states.ObjectReady, - Value: newVal, - Private: resp.Private, - Dependencies: n.Dependencies, // Should be populated by the caller from the StateDependencies method on the resource instance node + Status: newStatus, + Value: newVal, + Private: resp.Private, } } @@ -378,40 +384,39 @@ type EvalMaybeTainted struct { Change **plans.ResourceInstanceChange State **states.ResourceInstanceObject Error *error - - // If StateOutput is not nil, its referent will be assigned either the same - // pointer as State or a new object with its status set as Tainted, - // depending on whether an error is given and if this was a create action. - StateOutput **states.ResourceInstanceObject } -// TODO: test func (n *EvalMaybeTainted) Eval(ctx EvalContext) (interface{}, error) { + if n.State == nil || n.Change == nil || n.Error == nil { + return nil, nil + } + state := *n.State change := *n.Change err := *n.Error + // nothing to do if everything went as planned + if err == nil { + return nil, nil + } + if state != nil && state.Status == states.ObjectTainted { log.Printf("[TRACE] EvalMaybeTainted: %s was already tainted, so nothing to do", n.Addr.Absolute(ctx.Path())) return nil, nil } - if n.StateOutput != nil { - if err != nil && change.Action == plans.Create { - // If there are errors during a _create_ then the object is - // in an undefined state, and so we'll mark it as tainted so - // we can try again on the next run. - // - // We don't do this for other change actions because errors - // during updates will often not change the remote object at all. - // If there _were_ changes prior to the error, it's the provider's - // responsibility to record the effect of those changes in the - // object value it returned. - log.Printf("[TRACE] EvalMaybeTainted: %s encountered an error during creation, so it is now marked as tainted", n.Addr.Absolute(ctx.Path())) - *n.StateOutput = state.AsTainted() - } else { - *n.StateOutput = state - } + if change.Action == plans.Create { + // If there are errors during a _create_ then the object is + // in an undefined state, and so we'll mark it as tainted so + // we can try again on the next run. + // + // We don't do this for other change actions because errors + // during updates will often not change the remote object at all. + // If there _were_ changes prior to the error, it's the provider's + // responsibility to record the effect of those changes in the + // object value it returned. + log.Printf("[TRACE] EvalMaybeTainted: %s encountered an error during creation, so it is now marked as tainted", n.Addr.Absolute(ctx.Path())) + *n.State = state.AsTainted() } return nil, nil @@ -564,6 +569,11 @@ func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*configs.Provisio config, _, configDiags := ctx.EvaluateBlock(prov.Config, schema, instanceAddr, keyData) diags = diags.Append(configDiags) + // we can't apply the provisioner if the config has errors + if diags.HasErrors() { + return diags.Err() + } + // If the provisioner block contains a connection block of its own then // it can override the base connection configuration, if any. var localConn hcl.Body diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go index 7440cff7ad..26d68c175c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go @@ -125,7 +125,7 @@ type EvalGetProvider struct { } func (n *EvalGetProvider) Eval(ctx EvalContext) (interface{}, error) { - if n.Addr.ProviderConfig.Type == "" { + if n.Addr.ProviderConfig.Type.LegacyString() == "" { // Should never happen panic("EvalGetProvider used with uninitialized provider configuration address") } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go index 0b734b793f..913c41eebb 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go @@ -21,7 +21,6 @@ import ( type EvalReadData struct { Addr addrs.ResourceInstance Config *configs.Resource - Dependencies []addrs.Referenceable Provider *providers.Interface ProviderAddr addrs.AbsProviderConfig ProviderSchema **ProviderSchema @@ -161,9 +160,8 @@ func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { } if n.OutputState != nil { state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectPlanned, // because the partial value in the plan must be used for now - Dependencies: n.Dependencies, + Value: change.After, + Status: states.ObjectPlanned, // because the partial value in the plan must be used for now } *n.OutputState = state } @@ -275,9 +273,8 @@ func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { }, } state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectReady, // because we completed the read from the provider - Dependencies: n.Dependencies, + Value: change.After, + Status: states.ObjectReady, // because we completed the read from the provider } err = ctx.Hook(func(h Hook) (HookAction, error) { @@ -306,14 +303,13 @@ func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { // EvalReadDataApply is an EvalNode implementation that executes a data // resource's ReadDataApply method to read data from the data source. type EvalReadDataApply struct { - Addr addrs.ResourceInstance - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - Output **states.ResourceInstanceObject - Config *configs.Resource - Change **plans.ResourceInstanceChange - StateReferences []addrs.Referenceable + Addr addrs.ResourceInstance + Provider *providers.Interface + ProviderAddr addrs.AbsProviderConfig + ProviderSchema **ProviderSchema + Output **states.ResourceInstanceObject + Config *configs.Resource + Change **plans.ResourceInstanceChange } func (n *EvalReadDataApply) Eval(ctx EvalContext) (interface{}, error) { @@ -385,9 +381,8 @@ func (n *EvalReadDataApply) Eval(ctx EvalContext) (interface{}, error) { if n.Output != nil { *n.Output = &states.ResourceInstanceObject{ - Value: newVal, - Status: states.ObjectReady, - Dependencies: n.StateReferences, + Value: newVal, + Status: states.ObjectReady, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go index 6a834445c3..1f3e9810b2 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go @@ -89,6 +89,7 @@ func (n *EvalRefresh) Eval(ctx EvalContext) (interface{}, error) { newState := state.DeepCopy() newState.Value = resp.NewState newState.Private = resp.Private + newState.Dependencies = state.Dependencies // Call post-refresh hook err = ctx.Hook(func(h Hook) (HookAction, error) { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go index d4a8d3cf74..4187a8e4e9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go @@ -16,7 +16,7 @@ func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNo seq := make([]EvalNode, 0, 5) seq = append(seq, &EvalInitProvider{ - TypeName: relAddr.Type, + TypeName: relAddr.Type.LegacyString(), Addr: addr.ProviderConfig, }) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go index 2d3eabd488..de86805b34 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go @@ -184,6 +184,16 @@ func (d *evaluationStateData) GetForEachAttr(addr addrs.ForEachAttr, rng tfdiags returnVal = d.InstanceKeyData.EachKey case "value": returnVal = d.InstanceKeyData.EachValue + + if returnVal == cty.NilVal { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: `each.value cannot be used in this context`, + Detail: fmt.Sprintf(`A reference to "each.value" has been used in a context in which it unavailable, such as when the configuration no longer contains the value in its "for_each" expression. Remove this reference to each.value in your configuration to work around this error.`), + Subject: rng.ToHCL().Ptr(), + }) + return cty.UnknownVal(cty.DynamicPseudoType), diags + } default: diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, @@ -637,60 +647,59 @@ func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng t for i := 0; i < length; i++ { ty := schema.ImpliedType() key := addrs.IntKey(i) - is, exists := rs.Instances[key] - if exists && is.Current != nil { - instAddr := addr.Instance(key).Absolute(d.ModulePath) + is := rs.Instances[key] + if is == nil || is.Current == nil { + // There shouldn't normally be "gaps" in our list but we'll + // allow it under the assumption that we're in a weird situation + // where e.g. someone has run "terraform state mv" to reorder + // a list and left a hole behind. + vals[i] = cty.UnknownVal(schema.ImpliedType()) + continue + } - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - if is.Current.Status == states.ObjectPlanned { - if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[i] = val - continue - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. + instAddr := addr.Instance(key).Absolute(d.ModulePath) + + if is.Current.Status == states.ObjectPlanned { + if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { + val, err := change.After.Decode(ty) + if err != nil { diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), + Summary: "Invalid resource instance data in plan", + Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), Subject: &config.DeclRange, }) continue } - } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. + vals[i] = val + continue + } else { + // If the object is in planned status then we should not + // get here, since we should've found a pending value + // in the plan above instead. diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), + Summary: "Missing pending object in plan", + Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), Subject: &config.DeclRange, }) continue } - vals[i] = ios.Value - } else { - // There shouldn't normally be "gaps" in our list but we'll - // allow it under the assumption that we're in a weird situation - // where e.g. someone has run "terraform state mv" to reorder - // a list and left a hole behind. - vals[i] = cty.UnknownVal(schema.ImpliedType()) } + + ios, err := is.Current.Decode(ty) + if err != nil { + // This shouldn't happen, since by the time we get here + // we should've upgraded the state data already. + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid resource instance data in state", + Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), + Subject: &config.DeclRange, + }) + continue + } + vals[i] = ios.Value } // We use a tuple rather than a list here because resource schemas may @@ -704,12 +713,14 @@ func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng t vals := make(map[string]cty.Value, len(rs.Instances)) for k, is := range rs.Instances { if sk, ok := k.(addrs.StringKey); ok { + if is == nil || is.Current == nil { + // Assume we're dealing with an instance that hasn't been created yet. + vals[string(sk)] = cty.UnknownVal(schema.ImpliedType()) + continue + } + instAddr := addr.Instance(k).Absolute(d.ModulePath) - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. - // Prefer pending value in plan if present. See getResourceInstanceSingle - // comment for the rationale. if is.Current.Status == states.ObjectPlanned { if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { val, err := change.After.Decode(ty) @@ -767,7 +778,7 @@ func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng t } func (d *evaluationStateData) getResourceSchema(addr addrs.Resource, providerAddr addrs.AbsProviderConfig) *configschema.Block { - providerType := providerAddr.ProviderConfig.Type + providerType := providerAddr.ProviderConfig.Type.LegacyString() schemas := d.Evaluator.Schemas schema, _ := schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) return schema diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go index 35a8be0c96..36da5af65a 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go @@ -215,7 +215,7 @@ func (d *evaluationStateData) staticValidateResourceReference(modCfg *configs.Co // Normally accessing this directly is wrong because it doesn't take into // account provider inheritance, etc but it's okay here because we're only // paying attention to the type anyway. - providerType := cfg.ProviderConfigAddr().Type + providerType := cfg.ProviderConfigAddr().Type.LegacyString() schema, _ := d.Evaluator.Schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) if schema == nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go index 9189876106..1225d2fb4e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go @@ -155,6 +155,21 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { // Connect references so ordering is correct &ReferenceTransformer{}, + &AttachDependenciesTransformer{}, + + // Destruction ordering + &DestroyEdgeTransformer{ + Config: b.Config, + State: b.State, + Schemas: b.Schemas, + }, + + &CBDEdgeTransformer{ + Config: b.Config, + State: b.State, + Schemas: b.Schemas, + Destroy: b.Destroy, + }, // Destruction ordering &DestroyEdgeTransformer{ @@ -174,17 +189,20 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { // Reverse the edges from outputs and locals, so that // interpolations don't fail during destroy. // Create a destroy node for outputs to remove them from the state. - // Prune unreferenced values, which may have interpolations that can't - // be resolved. GraphTransformIf( func() bool { return b.Destroy }, GraphTransformMulti( &DestroyValueReferenceTransformer{}, &DestroyOutputTransformer{}, - &PruneUnusedValuesTransformer{}, ), ), + // Prune unreferenced values, which may have interpolations that can't + // be resolved. + &PruneUnusedValuesTransformer{ + Destroy: b.Destroy, + }, + // Add the node to fix the state count boundaries &CountBoundaryTransformer{ Config: b.Config, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go index fad7bf161f..970960387e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go @@ -165,6 +165,7 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { // Connect so that the references are ready for targeting. We'll // have to connect again later for providers and so on. &ReferenceTransformer{}, + &AttachDependenciesTransformer{}, // Target &TargetsTransformer{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go index f1434e6252..b62782f9da 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go @@ -58,9 +58,8 @@ func configTreeConfigDependencies(root *configs.Config, inheritProviders map[str // The main way to declare a provider dependency is explicitly inside // the "terraform" block, which allows declaring a requirement without // also creating a configuration. - for fullName, constraints := range module.ProviderRequirements { + for fullName, req := range module.ProviderRequirements { inst := moduledeps.ProviderInstance(fullName) - // The handling here is a bit fiddly because the moduledeps package // was designed around the legacy (pre-0.12) configuration model // and hasn't yet been revised to handle the new model. As a result, @@ -69,7 +68,7 @@ func configTreeConfigDependencies(root *configs.Config, inheritProviders map[str // can also retain the source location of each constraint, for // more informative output from the "terraform providers" command. var rawConstraints version.Constraints - for _, constraint := range constraints { + for _, constraint := range req.VersionConstraints { rawConstraints = append(rawConstraints, constraint.Required...) } discoConstraints := discovery.NewConstraints(rawConstraints) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go index 56283c0ac3..b363550264 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go @@ -169,7 +169,6 @@ func (n *NodeRefreshableDataResourceInstance) EvalTree() EvalNode { &EvalReadData{ Addr: addr.Resource, Config: n.Config, - Dependencies: n.StateReferences(), Provider: &provider, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go index 580e60cb7e..1e4daabb98 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go @@ -14,7 +14,7 @@ func (n *NodeEvalableProvider) EvalTree() EvalNode { relAddr := addr.ProviderConfig return &EvalInitProvider{ - TypeName: relAddr.Type, + TypeName: relAddr.Type.LegacyString(), Addr: addr.ProviderConfig, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go index acdda45e40..38dca73ab9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go @@ -28,12 +28,13 @@ type NodeApplyableResourceInstance struct { } var ( - _ GraphNodeResource = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeCreator = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeDeposer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeResource = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeResourceInstance = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeCreator = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeReferencer = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeDeposer = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeEvalable = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeAttachDependencies = (*NodeApplyableResourceInstance)(nil) ) // GraphNodeAttachDestroyer @@ -97,6 +98,11 @@ func (n *NodeApplyableResourceInstance) References() []*addrs.Reference { return ret } +// GraphNodeAttachDependencies +func (n *NodeApplyableResourceInstance) AttachDependencies(deps []addrs.AbsResource) { + n.Dependencies = deps +} + // GraphNodeEvalable func (n *NodeApplyableResourceInstance) EvalTree() EvalNode { addr := n.ResourceInstanceAddr() @@ -171,7 +177,6 @@ func (n *NodeApplyableResourceInstance) evalTreeDataResource(addr addrs.AbsResou &EvalReadData{ Addr: addr.Resource, Config: n.Config, - Dependencies: n.StateReferences(), Planned: &change, // setting this indicates that the result must be complete Provider: &provider, ProviderAddr: n.ResolvedProvider, @@ -341,7 +346,6 @@ func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsRe &EvalApply{ Addr: addr.Resource, Config: n.Config, - Dependencies: n.StateReferences(), State: &state, Change: &diffApply, Provider: &provider, @@ -352,17 +356,17 @@ func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsRe CreateNew: &createNew, }, &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, - StateOutput: &state, + Addr: addr.Resource, + State: &state, + Change: &diffApply, + Error: &err, }, &EvalWriteState{ Addr: addr.Resource, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, + Dependencies: &n.Dependencies, }, &EvalApplyProvisioners{ Addr: addr.Resource, @@ -373,25 +377,26 @@ func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsRe When: configs.ProvisionerWhenCreate, }, &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, - StateOutput: &state, + Addr: addr.Resource, + State: &state, + Change: &diffApply, + Error: &err, }, &EvalWriteState{ Addr: addr.Resource, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, + Dependencies: &n.Dependencies, }, &EvalIf{ If: func(ctx EvalContext) (bool, error) { return createBeforeDestroyEnabled && err != nil, nil }, Then: &EvalMaybeRestoreDeposedObject{ - Addr: addr.Resource, - Key: &deposedKey, + Addr: addr.Resource, + PlannedChange: &diffApply, + Key: &deposedKey, }, }, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go index 049e5e9907..a66c30d1dc 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go @@ -285,6 +285,13 @@ var ( _ GraphNodeReferenceable = (*NodeDestroyResource)(nil) _ GraphNodeReferencer = (*NodeDestroyResource)(nil) _ GraphNodeEvalable = (*NodeDestroyResource)(nil) + + // FIXME: this is here to document that this node is both + // GraphNodeProviderConsumer by virtue of the embedded + // NodeAbstractResource, but that behavior is not desired and we skip it by + // checking for GraphNodeNoProvider. + _ GraphNodeProviderConsumer = (*NodeDestroyResource)(nil) + _ GraphNodeNoProvider = (*NodeDestroyResource)(nil) ) func (n *NodeDestroyResource) Name() string { @@ -319,3 +326,23 @@ func (n *NodeDestroyResource) EvalTree() EvalNode { Addr: n.ResourceAddr().Resource, } } + +// GraphNodeResource +func (n *NodeDestroyResource) ResourceAddr() addrs.AbsResource { + return n.NodeAbstractResource.ResourceAddr() +} + +// GraphNodeSubpath +func (n *NodeDestroyResource) Path() addrs.ModuleInstance { + return n.NodeAbstractResource.Path() +} + +// GraphNodeNoProvider +// FIXME: this should be removed once the node can be separated from the +// Internal NodeAbstractResource behavior. +func (n *NodeDestroyResource) NoProvider() { +} + +type GraphNodeNoProvider interface { + NoProvider() +} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go index 269c798080..42ddb3fbe3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go @@ -178,7 +178,7 @@ var ( ) func (n *NodeDestroyDeposedResourceInstanceObject) Name() string { - return fmt.Sprintf("%s (destroy deposed %s)", n.Addr.String(), n.DeposedKey) + return fmt.Sprintf("%s (destroy deposed %s)", n.ResourceInstanceAddr(), n.DeposedKey) } func (n *NodeDestroyDeposedResourceInstanceObject) DeposedInstanceObjectKey() states.DeposedKey { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go index 2c3a7012b9..c29e4970db 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go @@ -47,7 +47,7 @@ func (n *NodePlanDestroyableResourceInstance) EvalTree() EvalNode { var change *plans.ResourceInstanceChange var state *states.ResourceInstanceObject - if n.ResolvedProvider.ProviderConfig.Type == "" { + if n.ResolvedProvider.ProviderConfig.Type.String() == "" { // Should never happen; indicates that the graph was not constructed // correctly since we didn't get our provider attached. panic(fmt.Sprintf("%T %q was not assigned a resolved provider", n, dag.VertexName(n))) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go index ac4b24cf22..3c742592b0 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go @@ -78,8 +78,8 @@ func (n *NodePlannableResourceInstance) evalTreeDataResource(addr addrs.AbsResou // Check and see if any of our dependencies have changes. changes := ctx.Changes() - for _, d := range n.StateReferences() { - ri, ok := d.(addrs.ResourceInstance) + for _, d := range n.References() { + ri, ok := d.Subject.(addrs.ResourceInstance) if !ok { continue } @@ -114,7 +114,6 @@ func (n *NodePlannableResourceInstance) evalTreeDataResource(addr addrs.AbsResou &EvalReadData{ Addr: addr.Resource, Config: n.Config, - Dependencies: n.StateReferences(), Provider: &provider, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go index dcab37270c..c4920ac5db 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go @@ -18,6 +18,10 @@ import ( // NodeRefreshableManagedResourceInstance. Resource count orphans are also added. type NodeRefreshableManagedResource struct { *NodeAbstractResource + + // We attach dependencies to the Resource during refresh, since the + // instances are instantiated during DynamicExpand. + Dependencies []addrs.AbsResource } var ( @@ -27,8 +31,14 @@ var ( _ GraphNodeReferencer = (*NodeRefreshableManagedResource)(nil) _ GraphNodeResource = (*NodeRefreshableManagedResource)(nil) _ GraphNodeAttachResourceConfig = (*NodeRefreshableManagedResource)(nil) + _ GraphNodeAttachDependencies = (*NodeRefreshableManagedResource)(nil) ) +// GraphNodeAttachDependencies +func (n *NodeRefreshableManagedResource) AttachDependencies(deps []addrs.AbsResource) { + n.Dependencies = deps +} + // GraphNodeDynamicExpandable func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, error) { var diags tfdiags.Diagnostics @@ -58,6 +68,7 @@ func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, // Add the config and state since we don't do that via transforms a.Config = n.Config a.ResolvedProvider = n.ResolvedProvider + a.Dependencies = n.Dependencies return &NodeRefreshableManagedResourceInstance{ NodeAbstractResourceInstance: a, @@ -203,6 +214,11 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalN Output: &state, }, + &EvalRefreshDependencies{ + State: &state, + Dependencies: &n.Dependencies, + }, + &EvalRefresh{ Addr: addr.Resource, ProviderAddr: n.ResolvedProvider, @@ -217,6 +233,7 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalN ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, + Dependencies: &n.Dependencies, }, }, } @@ -276,6 +293,7 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResourceNoState( ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, + Dependencies: &n.Dependencies, }, // We must also save the planned change, so that expressions in diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go index 844d060c9f..8c4101d601 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go @@ -32,6 +32,26 @@ func (n *NodeRootVariable) ReferenceableAddrs() []addrs.Referenceable { return []addrs.Referenceable{n.Addr} } +// GraphNodeEvalable +func (n *NodeRootVariable) EvalTree() EvalNode { + // We don't actually need to _evaluate_ a root module variable, because + // its value is always constant and already stashed away in our EvalContext. + // However, we might need to run some user-defined validation rules against + // the value. + + if n.Config == nil || len(n.Config.Validations) == 0 { + return &EvalSequence{} // nothing to do + } + + return &evalVariableValidations{ + Addr: addrs.RootModuleInstance.InputVariable(n.Addr.Name), + Config: n.Config, + Expr: nil, // not set for root module variables + + IgnoreDiagnostics: false, + } +} + // dag.GraphNodeDotter impl. func (n *NodeRootVariable) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { return &dag.DotNode{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go index 93b19be57d..0718fd09a4 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go @@ -120,7 +120,6 @@ func (p *MockProvisioner) ProvisionResource(r provisioners.ProvisionResourceRequ } if p.ProvisionResourceFn != nil { fn := p.ProvisionResourceFn - p.Unlock() return fn(r) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go index fee220b52b..e202990079 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go @@ -59,7 +59,7 @@ func (t *AttachSchemaTransformer) Transform(g *Graph) error { mode := addr.Resource.Mode typeName := addr.Resource.Type providerAddr, _ := tv.ProvidedBy() - providerType := providerAddr.ProviderConfig.Type + providerType := providerAddr.ProviderConfig.Type.LegacyString() schema, version := t.Schemas.ResourceTypeConfig(providerType, mode, typeName) if schema == nil { @@ -72,7 +72,7 @@ func (t *AttachSchemaTransformer) Transform(g *Graph) error { if tv, ok := v.(GraphNodeAttachProviderConfigSchema); ok { providerAddr := tv.ProviderAddr() - schema := t.Schemas.ProviderConfig(providerAddr.ProviderConfig.Type) + schema := t.Schemas.ProviderConfig(providerAddr.ProviderConfig.Type.LegacyString()) if schema == nil { log.Printf("[ERROR] AttachSchemaTransformer: No provider config schema available for %s", providerAddr) continue diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go index 1d211570fc..41e4205bd2 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go @@ -54,26 +54,39 @@ type DestroyEdgeTransformer struct { func (t *DestroyEdgeTransformer) Transform(g *Graph) error { // Build a map of what is being destroyed (by address string) to - // the list of destroyers. Usually there will be at most one destroyer - // per node, but we allow multiple if present for completeness. + // the list of destroyers. destroyers := make(map[string][]GraphNodeDestroyer) destroyerAddrs := make(map[string]addrs.AbsResourceInstance) + + // Record the creators, which will need to depend on the destroyers if they + // are only being updated. + creators := make(map[string]GraphNodeCreator) + + // destroyersByResource records each destroyer by the AbsResourceAddress. + // We use this because dependencies are only referenced as resources, but we + // will want to connect all the individual instances for correct ordering. + destroyersByResource := make(map[string][]GraphNodeDestroyer) for _, v := range g.Vertices() { - dn, ok := v.(GraphNodeDestroyer) - if !ok { - continue - } + switch n := v.(type) { + case GraphNodeDestroyer: + addrP := n.DestroyAddr() + if addrP == nil { + log.Printf("[WARN] DestroyEdgeTransformer: %q (%T) has no destroy address", dag.VertexName(n), v) + continue + } + addr := *addrP - addrP := dn.DestroyAddr() - if addrP == nil { - continue + key := addr.String() + log.Printf("[TRACE] DestroyEdgeTransformer: %q (%T) destroys %s", dag.VertexName(n), v, key) + destroyers[key] = append(destroyers[key], n) + destroyerAddrs[key] = addr + + resAddr := addr.Resource.Resource.Absolute(addr.Module).String() + destroyersByResource[resAddr] = append(destroyersByResource[resAddr], n) + case GraphNodeCreator: + addr := n.CreateAddr() + creators[addr.String()] = n } - addr := *addrP - - key := addr.String() - log.Printf("[TRACE] DestroyEdgeTransformer: %q (%T) destroys %s", dag.VertexName(dn), v, key) - destroyers[key] = append(destroyers[key], dn) - destroyerAddrs[key] = addr } // If we aren't destroying anything, there will be no edges to make @@ -82,6 +95,40 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { return nil } + // Connect destroy despendencies as stored in the state + for _, ds := range destroyers { + for _, des := range ds { + ri, ok := des.(GraphNodeResourceInstance) + if !ok { + continue + } + + for _, resAddr := range ri.StateDependencies() { + for _, desDep := range destroyersByResource[resAddr.String()] { + log.Printf("[TRACE] DestroyEdgeTransformer: %s has stored dependency of %s\n", dag.VertexName(desDep), dag.VertexName(des)) + g.Connect(dag.BasicEdge(desDep, des)) + + } + } + } + } + + // connect creators to any destroyers on which they may depend + for _, c := range creators { + ri, ok := c.(GraphNodeResourceInstance) + if !ok { + continue + } + + for _, resAddr := range ri.StateDependencies() { + for _, desDep := range destroyersByResource[resAddr.String()] { + log.Printf("[TRACE] DestroyEdgeTransformer: %s has stored dependency of %s\n", dag.VertexName(c), dag.VertexName(desDep)) + g.Connect(dag.BasicEdge(c, desDep)) + + } + } + } + // Go through and connect creators to destroyers. Going along with // our example, this makes: A_d => A for _, v := range g.Vertices() { @@ -95,13 +142,7 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { continue } - key := addr.String() - ds := destroyers[key] - if len(ds) == 0 { - continue - } - - for _, d := range ds { + for _, d := range destroyers[addr.String()] { // For illustrating our example a_d := d.(dag.Vertex) a := v diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go index 7dd2c4876d..b3c3fcaadf 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go @@ -20,7 +20,7 @@ func (t *ImportStateTransformer) Transform(g *Graph) error { // This will be populated if the targets come from the cli, but tests // may not specify implied provider addresses. providerAddr := target.ProviderAddr - if providerAddr.ProviderConfig.Type == "" { + if providerAddr.ProviderConfig.Type.Type == "" { providerAddr = target.Addr.Resource.Resource.DefaultProviderConfig().Absolute(target.Addr.Module) } diff --git a/vendor/github.com/hashicorp/terraform/addrs/provider.go b/vendor/github.com/hashicorp/terraform/addrs/provider.go new file mode 100644 index 0000000000..b73cfb5a7f --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/addrs/provider.go @@ -0,0 +1,49 @@ +package addrs + +import ( + svchost "github.com/hashicorp/terraform-svchost" +) + +// Provider encapsulates a single provider type. In the future this will be +// extended to include additional fields including Namespace and SourceHost +type Provider struct { + Type string + Namespace string + Hostname svchost.Hostname +} + +// String returns an FQN string, indended for use in output. +func (pt Provider) String() string { + return pt.Hostname.ForDisplay() + "/" + pt.Namespace + "/" + pt.Type +} + +// NewDefaultProvider returns the default address of a HashiCorp-maintained, +// Registry-hosted provider. +func NewDefaultProvider(name string) Provider { + return Provider{ + Type: name, + Namespace: "hashicorp", + Hostname: "registry.terraform.io", + } +} + +// NewLegacyProvider returns a mock address for a provider. +// This will be removed when ProviderType is fully integrated. +func NewLegacyProvider(name string) Provider { + return Provider{ + Type: name, + Namespace: "-", + Hostname: "registry.terraform.io", + } +} + +// LegacyString returns the provider type, which is frequently used +// interchangeably with provider name. This function can and should be removed +// when provider type is fully integrated. As a safeguard for future +// refactoring, this function panics if the Provider is not a legacy provider. +func (pt Provider) LegacyString() string { + if pt.Namespace != "-" { + panic("not a legacy Provider") + } + return pt.Type +} diff --git a/vendor/github.com/hashicorp/terraform/configs/experiments.go b/vendor/github.com/hashicorp/terraform/configs/experiments.go new file mode 100644 index 0000000000..435bac11d4 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/configs/experiments.go @@ -0,0 +1,156 @@ +package configs + +import ( + "fmt" + + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/terraform/experiments" +) + +// sniffActiveExperiments does minimal parsing of the given body for +// "terraform" blocks with "experiments" attributes, returning the +// experiments found. +// +// This is separate from other processing so that we can be sure that all of +// the experiments are known before we process the result of the module config, +// and thus we can take into account which experiments are active when deciding +// how to decode. +func sniffActiveExperiments(body hcl.Body) (experiments.Set, hcl.Diagnostics) { + rootContent, _, diags := body.PartialContent(configFileTerraformBlockSniffRootSchema) + + ret := experiments.NewSet() + + for _, block := range rootContent.Blocks { + content, _, blockDiags := block.Body.PartialContent(configFileExperimentsSniffBlockSchema) + diags = append(diags, blockDiags...) + + attr, exists := content.Attributes["experiments"] + if !exists { + continue + } + + exps, expDiags := decodeExperimentsAttr(attr) + diags = append(diags, expDiags...) + if !expDiags.HasErrors() { + ret = experiments.SetUnion(ret, exps) + } + } + + return ret, diags +} + +func decodeExperimentsAttr(attr *hcl.Attribute) (experiments.Set, hcl.Diagnostics) { + var diags hcl.Diagnostics + + exprs, moreDiags := hcl.ExprList(attr.Expr) + diags = append(diags, moreDiags...) + if moreDiags.HasErrors() { + return nil, diags + } + + var ret = experiments.NewSet() + for _, expr := range exprs { + kw := hcl.ExprAsKeyword(expr) + if kw == "" { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid experiment keyword", + Detail: "Elements of \"experiments\" must all be keywords representing active experiments.", + Subject: expr.Range().Ptr(), + }) + continue + } + + exp, err := experiments.GetCurrent(kw) + switch err := err.(type) { + case experiments.UnavailableError: + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Unknown experiment keyword", + Detail: fmt.Sprintf("There is no current experiment with the keyword %q.", kw), + Subject: expr.Range().Ptr(), + }) + case experiments.ConcludedError: + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Experiment has concluded", + Detail: fmt.Sprintf("Experiment %q is no longer available. %s", kw, err.Message), + Subject: expr.Range().Ptr(), + }) + case nil: + // No error at all means it's valid and current. + ret.Add(exp) + + // However, experimental features are subject to breaking changes + // in future releases, so we'll warn about them to help make sure + // folks aren't inadvertently using them in places where that'd be + // inappropriate, particularly if the experiment is active in a + // shared module they depend on. + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: fmt.Sprintf("Experimental feature %q is active", exp.Keyword()), + Detail: "Experimental features are subject to breaking changes in future minor or patch releases, based on feedback.\n\nIf you have feedback on the design of this feature, please open a GitHub issue to discuss it.", + Subject: expr.Range().Ptr(), + }) + + default: + // This should never happen, because GetCurrent is not documented + // to return any other error type, but we'll handle it to be robust. + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid experiment keyword", + Detail: fmt.Sprintf("Could not parse %q as an experiment keyword: %s.", kw, err.Error()), + Subject: expr.Range().Ptr(), + }) + } + } + return ret, diags +} + +func checkModuleExperiments(m *Module) hcl.Diagnostics { + var diags hcl.Diagnostics + + // When we have current experiments, this is a good place to check that + // the features in question can only be used when the experiments are + // active. Return error diagnostics if a feature is being used without + // opting in to the feature. For example: + /* + if !m.ActiveExperiments.Has(experiments.ResourceForEach) { + for _, rc := range m.ManagedResources { + if rc.ForEach != nil { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Resource for_each is experimental", + Detail: "This feature is currently an opt-in experiment, subject to change in future releases based on feedback.\n\nActivate the feature for this module by adding resource_for_each to the list of active experiments.", + Subject: rc.ForEach.Range().Ptr(), + }) + } + } + for _, rc := range m.DataResources { + if rc.ForEach != nil { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Resource for_each is experimental", + Detail: "This feature is currently an opt-in experiment, subject to change in future releases based on feedback.\n\nActivate the feature for this module by adding resource_for_each to the list of active experiments.", + Subject: rc.ForEach.Range().Ptr(), + }) + } + } + } + */ + + if !m.ActiveExperiments.Has(experiments.VariableValidation) { + for _, vc := range m.Variables { + if len(vc.Validations) != 0 { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Custom variable validation is experimental", + Detail: "This feature is currently an opt-in experiment, subject to change in future releases based on feedback.\n\nActivate the feature for this module by adding variable_validation to the list of active experiments.", + Subject: vc.Validations[0].DeclRange.Ptr(), + }) + } + } + } + + return diags +} diff --git a/vendor/github.com/hashicorp/terraform/configs/provider_requirements.go b/vendor/github.com/hashicorp/terraform/configs/provider_requirements.go new file mode 100644 index 0000000000..f2a78e501c --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/configs/provider_requirements.go @@ -0,0 +1,82 @@ +package configs + +import ( + version "github.com/hashicorp/go-version" + "github.com/hashicorp/hcl/v2" + "github.com/hashicorp/terraform/addrs" +) + +// RequiredProvider represents a declaration of a dependency on a particular +// provider version without actually configuring that provider. This is used in +// child modules that expect a provider to be passed in from their parent. +// +// TODO: "Source" is a placeholder for an attribute that is not yet supported. +type RequiredProvider struct { + Name string + Source string // TODO + Requirement VersionConstraint +} + +// ProviderRequirements represents merged provider version constraints. +// VersionConstraints come from terraform.require_providers blocks and provider +// blocks. +type ProviderRequirements struct { + Type addrs.Provider + VersionConstraints []VersionConstraint +} + +func decodeRequiredProvidersBlock(block *hcl.Block) ([]*RequiredProvider, hcl.Diagnostics) { + attrs, diags := block.Body.JustAttributes() + var reqs []*RequiredProvider + for name, attr := range attrs { + expr, err := attr.Expr.Value(nil) + if err != nil { + diags = append(diags, err...) + } + + switch { + case expr.Type().IsPrimitiveType(): + vc, reqDiags := decodeVersionConstraint(attr) + diags = append(diags, reqDiags...) + reqs = append(reqs, &RequiredProvider{ + Name: name, + Requirement: vc, + }) + case expr.Type().IsObjectType(): + if expr.Type().HasAttribute("version") { + vc := VersionConstraint{ + DeclRange: attr.Range, + } + constraintStr := expr.GetAttr("version").AsString() + constraints, err := version.NewConstraint(constraintStr) + if err != nil { + // NewConstraint doesn't return user-friendly errors, so we'll just + // ignore the provided error and produce our own generic one. + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid version constraint", + Detail: "This string does not use correct version constraint syntax.", + Subject: attr.Expr.Range().Ptr(), + }) + reqs = append(reqs, &RequiredProvider{Name: name}) + return reqs, diags + } + vc.Required = constraints + reqs = append(reqs, &RequiredProvider{Name: name, Requirement: vc}) + } + // No version + reqs = append(reqs, &RequiredProvider{Name: name}) + default: + // should not happen + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid provider_requirements syntax", + Detail: "provider_requirements entries must be strings or objects.", + Subject: attr.Expr.Range().Ptr(), + }) + reqs = append(reqs, &RequiredProvider{Name: name}) + return reqs, diags + } + } + return reqs, diags +} diff --git a/vendor/github.com/hashicorp/terraform/experiments/doc.go b/vendor/github.com/hashicorp/terraform/experiments/doc.go new file mode 100644 index 0000000000..5538d739c9 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/experiments/doc.go @@ -0,0 +1,9 @@ +// Package experiments contains the models and logic for opt-in experiments +// that can be activated for a particular Terraform module. +// +// We use experiments to get feedback on new configuration language features +// in a way that permits breaking changes without waiting for a future minor +// release. Any feature behind an experiment flag is subject to change in any +// way in even a patch release, until we have enough confidence about the +// design of the feature to make compatibility commitments about it. +package experiments diff --git a/vendor/github.com/hashicorp/terraform/experiments/errors.go b/vendor/github.com/hashicorp/terraform/experiments/errors.go new file mode 100644 index 0000000000..a1fdc6f5c4 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/experiments/errors.go @@ -0,0 +1,26 @@ +package experiments + +import ( + "fmt" +) + +// UnavailableError is the error type returned by GetCurrent when the requested +// experiment is not recognized at all. +type UnavailableError struct { + ExperimentName string +} + +func (e UnavailableError) Error() string { + return fmt.Sprintf("no current experiment is named %q", e.ExperimentName) +} + +// ConcludedError is the error type returned by GetCurrent when the requested +// experiment is recognized as concluded. +type ConcludedError struct { + ExperimentName string + Message string +} + +func (e ConcludedError) Error() string { + return fmt.Sprintf("experiment %q has concluded: %s", e.ExperimentName, e.Message) +} diff --git a/vendor/github.com/hashicorp/terraform/experiments/experiment.go b/vendor/github.com/hashicorp/terraform/experiments/experiment.go new file mode 100644 index 0000000000..037b34e732 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/experiments/experiment.go @@ -0,0 +1,93 @@ +package experiments + +// Experiment represents a particular experiment, which can be activated +// independently of all other experiments. +type Experiment string + +// All active and defunct experiments must be represented by constants whose +// internal string values are unique. +// +// Each of these declared constants must also be registered as either a +// current or a defunct experiment in the init() function below. +// +// Each experiment is represented by a string that must be a valid HCL +// identifier so that it can be specified in configuration. +const ( + VariableValidation = Experiment("variable_validation") +) + +func init() { + // Each experiment constant defined above must be registered here as either + // a current or a concluded experiment. + registerCurrentExperiment(VariableValidation) +} + +// GetCurrent takes an experiment name and returns the experiment value +// representing that expression if and only if it is a current experiment. +// +// If the selected experiment is concluded, GetCurrent will return an +// error of type ConcludedError whose message hopefully includes some guidance +// for users of the experiment on how to migrate to a stable feature that +// succeeded it. +// +// If the selected experiment is not known at all, GetCurrent will return an +// error of type UnavailableError. +func GetCurrent(name string) (Experiment, error) { + exp := Experiment(name) + if currentExperiments.Has(exp) { + return exp, nil + } + + if msg, concluded := concludedExperiments[exp]; concluded { + return Experiment(""), ConcludedError{ExperimentName: name, Message: msg} + } + + return Experiment(""), UnavailableError{ExperimentName: name} +} + +// Keyword returns the keyword that would be used to activate this experiment +// in the configuration. +func (e Experiment) Keyword() string { + return string(e) +} + +// IsCurrent returns true if the receiver is considered a currently-selectable +// experiment. +func (e Experiment) IsCurrent() bool { + return currentExperiments.Has(e) +} + +// IsConcluded returns true if the receiver is a concluded experiment. +func (e Experiment) IsConcluded() bool { + _, exists := concludedExperiments[e] + return exists +} + +// currentExperiments are those which are available to activate in the current +// version of Terraform. +// +// Members of this set are registered in the init function above. +var currentExperiments = make(Set) + +// concludedExperiments are those which were available to activate in an earlier +// version of Terraform but are no longer available, either because the feature +// in question has been implemented or because the experiment failed and the +// feature was abandoned. Each experiment maps to a message describing the +// outcome, so we can give users feedback about what they might do in modules +// using concluded experiments. +// +// After an experiment has been concluded for a whole major release span it can +// be removed, since we expect users to perform upgrades one major release at +// at time without skipping and thus they will see the concludedness error +// message as they upgrade through a prior major version. +// +// Members of this map are registered in the init function above. +var concludedExperiments = make(map[Experiment]string) + +func registerCurrentExperiment(exp Experiment) { + currentExperiments.Add(exp) +} + +func registerConcludedExperiment(exp Experiment, message string) { + concludedExperiments[exp] = message +} diff --git a/vendor/github.com/hashicorp/terraform/experiments/set.go b/vendor/github.com/hashicorp/terraform/experiments/set.go new file mode 100644 index 0000000000..8247e212b5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/experiments/set.go @@ -0,0 +1,46 @@ +package experiments + +// Set is a collection of experiments where every experiment is either a member +// or not. +type Set map[Experiment]struct{} + +// NewSet constructs a new Set with the given experiments as its initial members. +func NewSet(exps ...Experiment) Set { + ret := make(Set) + for _, exp := range exps { + ret.Add(exp) + } + return ret +} + +// SetUnion constructs a new Set containing the members of all of the given +// sets. +func SetUnion(sets ...Set) Set { + ret := make(Set) + for _, set := range sets { + for exp := range set { + ret.Add(exp) + } + } + return ret +} + +// Add inserts the given experiment into the set. +// +// If the given experiment is already present then this is a no-op. +func (s Set) Add(exp Experiment) { + s[exp] = struct{}{} +} + +// Remove takes the given experiment out of the set. +// +// If the given experiment not already present then this is a no-op. +func (s Set) Remove(exp Experiment) { + delete(s, exp) +} + +// Has tests whether the given experiment is in the receiving set. +func (s Set) Has(exp Experiment) bool { + _, ok := s[exp] + return ok +} diff --git a/vendor/github.com/hashicorp/terraform/experiments/testing.go b/vendor/github.com/hashicorp/terraform/experiments/testing.go new file mode 100644 index 0000000000..54ff2dfdee --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/experiments/testing.go @@ -0,0 +1,33 @@ +package experiments + +import ( + "testing" +) + +// OverrideForTesting temporarily overrides the global tables +// of experiments in order to allow for a predictable set when unit testing +// the experiments infrastructure code. +// +// The correct way to use this function is to defer a call to its result so +// that the original tables can be restored at the conclusion of the calling +// test: +// +// defer experiments.OverrideForTesting(t, current, concluded)() +// +// This function modifies global variables that are normally fixed throughout +// our execution, so this function must not be called from non-test code and +// any test using it cannot safely run concurrently with other tests. +func OverrideForTesting(t *testing.T, current Set, concluded map[Experiment]string) func() { + // We're not currently using the given *testing.T in here, but we're + // requiring it anyway in case we might need it in future, and because + // it hopefully reinforces that only test code should be calling this. + + realCurrents := currentExperiments + realConcludeds := concludedExperiments + currentExperiments = current + concludedExperiments = concluded + return func() { + currentExperiments = realCurrents + concludedExperiments = realConcludeds + } +} diff --git a/vendor/github.com/hashicorp/terraform/helper/logging/indent.go b/vendor/github.com/hashicorp/terraform/helper/logging/indent.go new file mode 100644 index 0000000000..e0da0d7c73 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/helper/logging/indent.go @@ -0,0 +1,23 @@ +package logging + +import ( + "strings" +) + +// Indent adds two spaces to the beginning of each line of the given string, +// with the goal of making the log level filter understand it as a line +// continuation rather than possibly as new log lines. +func Indent(s string) string { + var b strings.Builder + for len(s) > 0 { + end := strings.IndexByte(s, '\n') + if end == -1 { + end = len(s) - 1 + } + var l string + l, s = s[:end+1], s[end+1:] + b.WriteString(" ") + b.WriteString(l) + } + return b.String() +} diff --git a/vendor/github.com/hashicorp/terraform/helper/logging/level.go b/vendor/github.com/hashicorp/terraform/helper/logging/level.go new file mode 100644 index 0000000000..0dc4dfe8d5 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/helper/logging/level.go @@ -0,0 +1,159 @@ +package logging + +import ( + "bytes" + "io" + "sync" +) + +// LogLevel is a special string, conventionally written all in uppercase, that +// can be used to mark a log line for filtering and to specify filtering +// levels in the LevelFilter type. +type LogLevel string + +// LevelFilter is an io.Writer that can be used with a logger that +// will attempt to filter out log messages that aren't at least a certain +// level. +// +// This filtering is HEURISTIC-BASED, and so will not be 100% reliable. The +// assumptions it makes are: +// +// - Individual log messages are never split across multiple calls to the +// Write method. +// +// - Messages that carry levels are marked by a sequence starting with "[", +// then the level name string, and then "]". Any message without a sequence +// like this is an un-levelled message, and is not subject to filtering. +// +// - Each \n-delimited line in a write is a separate log message, unless a +// line starts with at least one space in which case it is interpreted +// as a continuation of the previous line. +// +// - If a log line starts with a non-whitespace character that isn't a digit +// then it's recognized as a degenerate continuation, because "real" log +// lines should start with a date/time and thus always have a leading +// digit. (This also cleans up after some situations where the assumptuion +// that messages arrive atomically aren't met, which is sadly sometimes +// true for longer messages that trip over some buffering behavior in +// panicwrap.) +// +// Because logging is a cross-cutting concern and not fully under the control +// of Terraform itself, there will certainly be cases where the above +// heuristics will fail. For example, it is likely that LevelFilter will +// occasionally misinterpret a continuation line as a new message because the +// code generating it doesn't know about our indentation convention. +// +// Our goal here is just to make a best effort to reduce the log volume, +// accepting that the results will not be 100% correct. +// +// Logging calls within Terraform Core should follow the above conventions so +// that the log output is broadly correct, however. +// +// Once the filter is in use somewhere, it is not safe to modify +// the structure. +type LevelFilter struct { + // Levels is the list of log levels, in increasing order of + // severity. Example might be: {"DEBUG", "WARN", "ERROR"}. + Levels []LogLevel + + // MinLevel is the minimum level allowed through + MinLevel LogLevel + + // The underlying io.Writer where log messages that pass the filter + // will be set. + Writer io.Writer + + badLevels map[LogLevel]struct{} + show bool + once sync.Once +} + +// Check will check a given line if it would be included in the level +// filter. +func (f *LevelFilter) Check(line []byte) bool { + f.once.Do(f.init) + + // Check for a log level + var level LogLevel + x := bytes.IndexByte(line, '[') + if x >= 0 { + y := bytes.IndexByte(line[x:], ']') + if y >= 0 { + level = LogLevel(line[x+1 : x+y]) + } + } + + //return level == "" + + _, ok := f.badLevels[level] + return !ok +} + +// Write is a specialized implementation of io.Writer suitable for being +// the output of a logger from the "log" package. +// +// This Writer implementation assumes that it will only recieve byte slices +// containing one or more entire lines of log output, each one terminated by +// a newline. This is compatible with the behavior of the "log" package +// directly, and is also tolerant of intermediaries that might buffer multiple +// separate writes together, as long as no individual log line is ever +// split into multiple slices. +// +// Behavior is undefined if any log line is split across multiple writes or +// written without a trailing '\n' delimiter. +func (f *LevelFilter) Write(p []byte) (n int, err error) { + for len(p) > 0 { + // Split at the first \n, inclusive + idx := bytes.IndexByte(p, '\n') + if idx == -1 { + // Invalid, undelimited write. We'll tolerate it assuming that + // our assumptions are being violated, but the results may be + // non-ideal. + idx = len(p) - 1 + break + } + var l []byte + l, p = p[:idx+1], p[idx+1:] + // Lines starting with characters other than decimal digits (including + // whitespace) are assumed to be continuations lines. This is an + // imprecise heuristic, but experimentally it seems to generate + // "good enough" results from Terraform Core's own logging. Its mileage + // may vary with output from other systems. + if l[0] >= '0' && l[0] <= '9' { + f.show = f.Check(l) + } + if f.show { + _, err = f.Writer.Write(l) + if err != nil { + // Technically it's not correct to say we've written the whole + // buffer, but for our purposes here it's good enough as we're + // only implementing io.Writer enough to satisfy logging + // use-cases. + return len(p), err + } + } + } + + // We always behave as if we wrote the whole of the buffer, even if + // we actually skipped some lines. We're only implementiong io.Writer + // enough to satisfy logging use-cases. + return len(p), nil +} + +// SetMinLevel is used to update the minimum log level +func (f *LevelFilter) SetMinLevel(min LogLevel) { + f.MinLevel = min + f.init() +} + +func (f *LevelFilter) init() { + badLevels := make(map[LogLevel]struct{}) + for _, level := range f.Levels { + if level == f.MinLevel { + break + } + badLevels[level] = struct{}{} + } + f.badLevels = badLevels + f.show = true +} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go b/vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go new file mode 100644 index 0000000000..06f3d52cc0 --- /dev/null +++ b/vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go @@ -0,0 +1,146 @@ +package tfdiags + +import "fmt" + +// ConsolidateWarnings checks if there is an unreasonable amount of warnings +// with the same summary in the receiver and, if so, returns a new diagnostics +// with some of those warnings consolidated into a single warning in order +// to reduce the verbosity of the output. +// +// This mechanism is here primarily for diagnostics printed out at the CLI. In +// other contexts it is likely better to just return the warnings directly, +// particularly if they are going to be interpreted by software rather than +// by a human reader. +// +// The returned slice always has a separate backing array from the reciever, +// but some diagnostic values themselves might be shared. +// +// The definition of "unreasonable" is given as the threshold argument. At most +// that many warnings with the same summary will be shown. +func (diags Diagnostics) ConsolidateWarnings(threshold int) Diagnostics { + if len(diags) == 0 { + return nil + } + + newDiags := make(Diagnostics, 0, len(diags)) + + // We'll track how many times we've seen each warning summary so we can + // decide when to start consolidating. Once we _have_ started consolidating, + // we'll also track the object representing the consolidated warning + // so we can continue appending to it. + warningStats := make(map[string]int) + warningGroups := make(map[string]*warningGroup) + + for _, diag := range diags { + severity := diag.Severity() + if severity != Warning || diag.Source().Subject == nil { + // Only warnings can get special treatment, and we only + // consolidate warnings that have source locations because + // our primary goal here is to deal with the situation where + // some configuration language feature is producing a warning + // each time it's used across a potentially-large config. + newDiags = newDiags.Append(diag) + continue + } + + desc := diag.Description() + summary := desc.Summary + if g, ok := warningGroups[summary]; ok { + // We're already grouping this one, so we'll just continue it. + g.Append(diag) + continue + } + + warningStats[summary]++ + if warningStats[summary] == threshold { + // Initially creating the group doesn't really change anything + // visibly in the result, since a group with only one warning + // is just a passthrough anyway, but once we do this any additional + // warnings with the same summary will get appended to this group. + g := &warningGroup{} + newDiags = newDiags.Append(g) + warningGroups[summary] = g + g.Append(diag) + continue + } + + // If this warning is not consolidating yet then we'll just append + // it directly. + newDiags = newDiags.Append(diag) + } + + return newDiags +} + +// A warningGroup is one or more warning diagnostics grouped together for +// UI consolidation purposes. +// +// A warningGroup with only one diagnostic in it is just a passthrough for +// that one diagnostic. If it has more than one then it will behave mostly +// like the first one but its detail message will include an additional +// sentence mentioning the consolidation. A warningGroup with no diagnostics +// at all is invalid and will panic when used. +type warningGroup struct { + Warnings Diagnostics +} + +var _ Diagnostic = (*warningGroup)(nil) + +func (wg *warningGroup) Severity() Severity { + return wg.Warnings[0].Severity() +} + +func (wg *warningGroup) Description() Description { + desc := wg.Warnings[0].Description() + if len(wg.Warnings) < 2 { + return desc + } + extraCount := len(wg.Warnings) - 1 + var msg string + switch extraCount { + case 1: + msg = "(and one more similar warning elsewhere)" + default: + msg = fmt.Sprintf("(and %d more similar warnings elsewhere)", extraCount) + } + if desc.Detail != "" { + desc.Detail = desc.Detail + "\n\n" + msg + } else { + desc.Detail = msg + } + return desc +} + +func (wg *warningGroup) Source() Source { + return wg.Warnings[0].Source() +} + +func (wg *warningGroup) FromExpr() *FromExpr { + return wg.Warnings[0].FromExpr() +} + +func (wg *warningGroup) Append(diag Diagnostic) { + if diag.Severity() != Warning { + panic("can't append a non-warning diagnostic to a warningGroup") + } + wg.Warnings = append(wg.Warnings, diag) +} + +// WarningGroupSourceRanges can be used in conjunction with +// Diagnostics.ConsolidateWarnings to recover the full set of original source +// locations from a consolidated warning. +// +// For convenience, this function accepts any diagnostic and will just return +// the single Source value from any diagnostic that isn't a warning group. +func WarningGroupSourceRanges(diag Diagnostic) []Source { + wg, ok := diag.(*warningGroup) + if !ok { + return []Source{diag.Source()} + } + + ret := make([]Source, len(wg.Warnings)) + for i, wrappedDiag := range wg.Warnings { + ret[i] = wrappedDiag.Source() + } + return ret +} diff --git a/website/docs/index.html.markdown b/website/docs/index.html.markdown index 28e932241a..923be2536e 100644 --- a/website/docs/index.html.markdown +++ b/website/docs/index.html.markdown @@ -60,3 +60,6 @@ The following arguments are supported in the `provider` block: * `anonymous`: (Optional) Authenticate without a token. When `anonymous` is true, the provider will not be able to access resources that require authentication. Setting to true will lead the GitHub provider to work in an anonymous mode with the corresponding API [rate limits](https://developer.github.com/v3/#rate-limiting). Defaults to `false`. + +* `id`: (Computed) This is the ID of the target GitHub organization which is being managed. The value of this is set by + provider based on the name specified in `organization`. From a50a64543ad37dc4692933688f5d27553bc29f97 Mon Sep 17 00:00:00 2001 From: Ben F Date: Fri, 28 Feb 2020 11:49:44 +0000 Subject: [PATCH 3/7] Revert go1.13 addition --- go.mod | 1 - 1 file changed, 1 deletion(-) diff --git a/go.mod b/go.mod index 046acce866..95b0971714 100644 --- a/go.mod +++ b/go.mod @@ -8,4 +8,3 @@ require ( golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d ) -go 1.13 From 080c49f6094e4505e6a31ab001e68a4977767da2 Mon Sep 17 00:00:00 2001 From: Ben F Date: Fri, 28 Feb 2020 13:13:07 +0000 Subject: [PATCH 4/7] Cleaning deps of tf 0.12.20 --- go.mod | 1 - 1 file changed, 1 deletion(-) diff --git a/go.mod b/go.mod index 95b0971714..27fd4940fa 100644 --- a/go.mod +++ b/go.mod @@ -7,4 +7,3 @@ require ( github.com/terraform-providers/terraform-provider-tls v1.2.0 golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d ) - From 7346fb67090fc6c6bdf21880301b7250816041e9 Mon Sep 17 00:00:00 2001 From: Ben F Date: Fri, 6 Mar 2020 08:52:46 +0000 Subject: [PATCH 5/7] Cleanup following rebase --- go.mod | 4 +- .../github.com/bmatcuk/doublestar/.travis.yml | 15 - vendor/github.com/bmatcuk/doublestar/LICENSE | 22 - .../github.com/bmatcuk/doublestar/README.md | 109 ---- .../bmatcuk/doublestar/doublestar.go | 476 ------------------ vendor/github.com/bmatcuk/doublestar/go.mod | 3 - .../hashicorp/go-getter/.travis.yml | 24 + .../github.com/hashicorp/go-getter/README.md | 8 +- .../github.com/hashicorp/go-getter/client.go | 2 +- .../github.com/hashicorp/go-getter/get_git.go | 28 +- .../hashicorp/go-getter/get_http.go | 24 +- .../github.com/hashicorp/hcl/v2/appveyor.yml | 13 - .../hcl/v2/ext/customdecode/README.md | 209 -------- .../hcl/v2/ext/customdecode/customdecode.go | 56 --- .../v2/ext/customdecode/expression_type.go | 146 ------ .../hashicorp/hcl/v2/ext/tryfunc/README.md | 44 -- .../hashicorp/hcl/v2/ext/tryfunc/tryfunc.go | 150 ------ .../hcl/v2/ext/typeexpr/type_type.go | 118 ----- .../hashicorp/hcl/v2/gohcl/decode.go | 26 +- .../hashicorp/hcl/v2/hclsyntax/parser.go | 11 +- .../hcl/v2/hclwrite/ast_expression.go | 23 - .../hashicorp/hcl/v2/hclwrite/generate.go | 8 +- .../logutils}/.gitignore | 10 - vendor/github.com/hashicorp/logutils/LICENSE | 354 +++++++++++++ .../github.com/hashicorp/logutils/README.md | 36 ++ vendor/github.com/hashicorp/logutils/go.mod | 1 + vendor/github.com/hashicorp/logutils/level.go | 81 +++ .../terraform-config-inspect/tfconfig/load.go | 4 +- .../tfconfig/load_legacy.go | 10 +- .../tfconfig/module.go | 6 +- .../tfconfig/provider_ref.go | 76 --- .../helper/logging/logging.go | 31 +- .../helper/resource/testing_import_state.go | 5 +- .../internal/addrs/input_variable.go | 2 +- .../internal/addrs/module_instance.go | 2 +- .../internal/addrs/resource.go | 3 +- .../internal/command/format/diff.go | 66 +-- .../internal/command/format/state.go | 2 +- .../internal/configs/compat_shim.go | 92 +--- .../internal/configs/configload/copy_dir.go | 10 + .../internal/configs/module_merge.go | 5 +- .../internal/configs/named_values.go | 212 +------- .../internal/configs/parser_config.go | 35 +- .../internal/configs/parser_config_dir.go | 6 +- .../internal/configs/provisioner.go | 58 +-- .../internal/configs/resource.go | 26 +- .../terraform-plugin-sdk/internal/dag/walk.go | 2 +- .../internal/lang/funcs/collection.go | 9 +- .../internal/lang/funcs/string.go | 90 +--- .../internal/modsdir/manifest.go | 9 - .../internal/providers/addressed_types.go | 4 +- .../internal/states/instance_object.go | 17 +- .../internal/states/instance_object_src.go | 5 +- .../internal/states/module.go | 65 +-- .../internal/states/resource.go | 7 - .../internal/states/state_deepcopy.go | 18 +- .../internal/states/statefile/version4.go | 28 +- .../internal/tfdiags/contextual.go | 4 +- .../internal/version/version.go | 2 +- .../terraform-plugin-sdk/plugin/client.go | 7 +- .../terraform-plugin-sdk/terraform/context.go | 38 +- .../terraform/context_input.go | 96 +++- .../terraform/eval_apply.go | 64 +-- .../terraform/eval_provider.go | 2 +- .../terraform/eval_read_data.go | 31 +- .../terraform/eval_refresh.go | 1 - .../terraform/evaltree_provider.go | 2 +- .../terraform/evaluate.go | 101 ++-- .../terraform/evaluate_valid.go | 2 +- .../terraform/graph_builder_apply.go | 24 +- .../terraform/graph_builder_refresh.go | 1 - .../terraform/module_dependencies.go | 5 +- .../terraform/node_data_refresh.go | 1 + .../terraform/node_provider_eval.go | 2 +- .../terraform/node_resource_apply_instance.go | 45 +- .../terraform/node_resource_destroy.go | 27 - .../node_resource_destroy_deposed.go | 2 +- .../terraform/node_resource_plan_destroy.go | 2 +- .../terraform/node_resource_plan_instance.go | 5 +- .../terraform/node_resource_refresh.go | 18 - .../terraform/node_root_variable.go | 20 - .../terraform/provisioner_mock.go | 1 + .../terraform/transform_attach_schema.go | 4 +- .../terraform/transform_destroy_edge.go | 85 +--- .../terraform/transform_import_state.go | 2 +- .../hashicorp/terraform/addrs/provider.go | 49 -- .../terraform/configs/experiments.go | 156 ------ .../configs/provider_requirements.go | 82 --- .../hashicorp/terraform/experiments/doc.go | 9 - .../hashicorp/terraform/experiments/errors.go | 26 - .../terraform/experiments/experiment.go | 93 ---- .../hashicorp/terraform/experiments/set.go | 46 -- .../terraform/experiments/testing.go | 33 -- .../terraform/helper/logging/indent.go | 23 - .../terraform/helper/logging/level.go | 159 ------ .../terraform/tfdiags/consolidate_warnings.go | 146 ------ vendor/modules.txt | 2 +- 97 files changed, 929 insertions(+), 3395 deletions(-) delete mode 100644 vendor/github.com/bmatcuk/doublestar/.travis.yml delete mode 100644 vendor/github.com/bmatcuk/doublestar/LICENSE delete mode 100644 vendor/github.com/bmatcuk/doublestar/README.md delete mode 100644 vendor/github.com/bmatcuk/doublestar/doublestar.go delete mode 100644 vendor/github.com/bmatcuk/doublestar/go.mod create mode 100644 vendor/github.com/hashicorp/go-getter/.travis.yml delete mode 100644 vendor/github.com/hashicorp/hcl/v2/appveyor.yml delete mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md delete mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go delete mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go delete mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md delete mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go delete mode 100644 vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go rename vendor/github.com/{bmatcuk/doublestar => hashicorp/logutils}/.gitignore (81%) create mode 100644 vendor/github.com/hashicorp/logutils/LICENSE create mode 100644 vendor/github.com/hashicorp/logutils/README.md create mode 100644 vendor/github.com/hashicorp/logutils/go.mod create mode 100644 vendor/github.com/hashicorp/logutils/level.go delete mode 100644 vendor/github.com/hashicorp/terraform/addrs/provider.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/experiments.go delete mode 100644 vendor/github.com/hashicorp/terraform/configs/provider_requirements.go delete mode 100644 vendor/github.com/hashicorp/terraform/experiments/doc.go delete mode 100644 vendor/github.com/hashicorp/terraform/experiments/errors.go delete mode 100644 vendor/github.com/hashicorp/terraform/experiments/experiment.go delete mode 100644 vendor/github.com/hashicorp/terraform/experiments/set.go delete mode 100644 vendor/github.com/hashicorp/terraform/experiments/testing.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/logging/indent.go delete mode 100644 vendor/github.com/hashicorp/terraform/helper/logging/level.go delete mode 100644 vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go diff --git a/go.mod b/go.mod index 27fd4940fa..2f0fad1c11 100644 --- a/go.mod +++ b/go.mod @@ -4,6 +4,8 @@ require ( github.com/google/go-github/v29 v29.0.3 github.com/hashicorp/terraform-plugin-sdk v1.7.0 github.com/kylelemons/godebug v1.1.0 - github.com/terraform-providers/terraform-provider-tls v1.2.0 + github.com/terraform-providers/terraform-provider-tls v1.2.0 // indirect golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d ) + +go 1.13 diff --git a/vendor/github.com/bmatcuk/doublestar/.travis.yml b/vendor/github.com/bmatcuk/doublestar/.travis.yml deleted file mode 100644 index ec4fee8896..0000000000 --- a/vendor/github.com/bmatcuk/doublestar/.travis.yml +++ /dev/null @@ -1,15 +0,0 @@ -language: go - -go: - - 1.11 - - 1.12 - -before_install: - - go get -t -v ./... - -script: - - go test -race -coverprofile=coverage.txt -covermode=atomic - -after_success: - - bash <(curl -s https://codecov.io/bash) - diff --git a/vendor/github.com/bmatcuk/doublestar/LICENSE b/vendor/github.com/bmatcuk/doublestar/LICENSE deleted file mode 100644 index 309c9d1d11..0000000000 --- a/vendor/github.com/bmatcuk/doublestar/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -The MIT License (MIT) - -Copyright (c) 2014 Bob Matcuk - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. - diff --git a/vendor/github.com/bmatcuk/doublestar/README.md b/vendor/github.com/bmatcuk/doublestar/README.md deleted file mode 100644 index 8e365c5e3f..0000000000 --- a/vendor/github.com/bmatcuk/doublestar/README.md +++ /dev/null @@ -1,109 +0,0 @@ -![Release](https://img.shields.io/github/release/bmatcuk/doublestar.svg?branch=master) -[![Build Status](https://travis-ci.org/bmatcuk/doublestar.svg?branch=master)](https://travis-ci.org/bmatcuk/doublestar) -[![codecov.io](https://img.shields.io/codecov/c/github/bmatcuk/doublestar.svg?branch=master)](https://codecov.io/github/bmatcuk/doublestar?branch=master) - -# doublestar - -**doublestar** is a [golang](http://golang.org/) implementation of path pattern -matching and globbing with support for "doublestar" (aka globstar: `**`) -patterns. - -doublestar patterns match files and directories recursively. For example, if -you had the following directory structure: - -``` -grandparent -`-- parent - |-- child1 - `-- child2 -``` - -You could find the children with patterns such as: `**/child*`, -`grandparent/**/child?`, `**/parent/*`, or even just `**` by itself (which will -return all files and directories recursively). - -Bash's globstar is doublestar's inspiration and, as such, works similarly. -Note that the doublestar must appear as a path component by itself. A pattern -such as `/path**` is invalid and will be treated the same as `/path*`, but -`/path*/**` should achieve the desired result. Additionally, `/path/**` will -match all directories and files under the path directory, but `/path/**/` will -only match directories. - -## Installation - -**doublestar** can be installed via `go get`: - -```bash -go get github.com/bmatcuk/doublestar -``` - -To use it in your code, you must import it: - -```go -import "github.com/bmatcuk/doublestar" -``` - -## Functions - -### Match -```go -func Match(pattern, name string) (bool, error) -``` - -Match returns true if `name` matches the file name `pattern` -([see below](#patterns)). `name` and `pattern` are split on forward slash (`/`) -characters and may be relative or absolute. - -Note: `Match()` is meant to be a drop-in replacement for `path.Match()`. As -such, it always uses `/` as the path separator. If you are writing code that -will run on systems where `/` is not the path separator (such as Windows), you -want to use `PathMatch()` (below) instead. - - -### PathMatch -```go -func PathMatch(pattern, name string) (bool, error) -``` - -PathMatch returns true if `name` matches the file name `pattern` -([see below](#patterns)). The difference between Match and PathMatch is that -PathMatch will automatically use your system's path separator to split `name` -and `pattern`. - -`PathMatch()` is meant to be a drop-in replacement for `filepath.Match()`. - -### Glob -```go -func Glob(pattern string) ([]string, error) -``` - -Glob finds all files and directories in the filesystem that match `pattern` -([see below](#patterns)). `pattern` may be relative (to the current working -directory), or absolute. - -`Glob()` is meant to be a drop-in replacement for `filepath.Glob()`. - -## Patterns - -**doublestar** supports the following special terms in the patterns: - -Special Terms | Meaning -------------- | ------- -`*` | matches any sequence of non-path-separators -`**` | matches any sequence of characters, including path separators -`?` | matches any single non-path-separator character -`[class]` | matches any single non-path-separator character against a class of characters ([see below](#character-classes)) -`{alt1,...}` | matches a sequence of characters if one of the comma-separated alternatives matches - -Any character with a special meaning can be escaped with a backslash (`\`). - -### Character Classes - -Character classes support the following: - -Class | Meaning ----------- | ------- -`[abc]` | matches any single character within the set -`[a-z]` | matches any single character in the range -`[^class]` | matches any single character which does *not* match the class - diff --git a/vendor/github.com/bmatcuk/doublestar/doublestar.go b/vendor/github.com/bmatcuk/doublestar/doublestar.go deleted file mode 100644 index 0044dfa831..0000000000 --- a/vendor/github.com/bmatcuk/doublestar/doublestar.go +++ /dev/null @@ -1,476 +0,0 @@ -package doublestar - -import ( - "fmt" - "os" - "path" - "path/filepath" - "strings" - "unicode/utf8" -) - -// ErrBadPattern indicates a pattern was malformed. -var ErrBadPattern = path.ErrBadPattern - -// Split a path on the given separator, respecting escaping. -func splitPathOnSeparator(path string, separator rune) (ret []string) { - idx := 0 - if separator == '\\' { - // if the separator is '\\', then we can just split... - ret = strings.Split(path, string(separator)) - idx = len(ret) - } else { - // otherwise, we need to be careful of situations where the separator was escaped - cnt := strings.Count(path, string(separator)) - if cnt == 0 { - return []string{path} - } - - ret = make([]string, cnt+1) - pathlen := len(path) - separatorLen := utf8.RuneLen(separator) - emptyEnd := false - for start := 0; start < pathlen; { - end := indexRuneWithEscaping(path[start:], separator) - if end == -1 { - emptyEnd = false - end = pathlen - } else { - emptyEnd = true - end += start - } - ret[idx] = path[start:end] - start = end + separatorLen - idx++ - } - - // If the last rune is a path separator, we need to append an empty string to - // represent the last, empty path component. By default, the strings from - // make([]string, ...) will be empty, so we just need to icrement the count - if emptyEnd { - idx++ - } - } - - return ret[:idx] -} - -// Find the first index of a rune in a string, -// ignoring any times the rune is escaped using "\". -func indexRuneWithEscaping(s string, r rune) int { - end := strings.IndexRune(s, r) - if end == -1 { - return -1 - } - if end > 0 && s[end-1] == '\\' { - start := end + utf8.RuneLen(r) - end = indexRuneWithEscaping(s[start:], r) - if end != -1 { - end += start - } - } - return end -} - -// Match returns true if name matches the shell file name pattern. -// The pattern syntax is: -// -// pattern: -// { term } -// term: -// '*' matches any sequence of non-path-separators -// '**' matches any sequence of characters, including -// path separators. -// '?' matches any single non-path-separator character -// '[' [ '^' ] { character-range } ']' -// character class (must be non-empty) -// '{' { term } [ ',' { term } ... ] '}' -// c matches character c (c != '*', '?', '\\', '[') -// '\\' c matches character c -// -// character-range: -// c matches character c (c != '\\', '-', ']') -// '\\' c matches character c -// lo '-' hi matches character c for lo <= c <= hi -// -// Match requires pattern to match all of name, not just a substring. -// The path-separator defaults to the '/' character. The only possible -// returned error is ErrBadPattern, when pattern is malformed. -// -// Note: this is meant as a drop-in replacement for path.Match() which -// always uses '/' as the path separator. If you want to support systems -// which use a different path separator (such as Windows), what you want -// is the PathMatch() function below. -// -func Match(pattern, name string) (bool, error) { - return matchWithSeparator(pattern, name, '/') -} - -// PathMatch is like Match except that it uses your system's path separator. -// For most systems, this will be '/'. However, for Windows, it would be '\\'. -// Note that for systems where the path separator is '\\', escaping is -// disabled. -// -// Note: this is meant as a drop-in replacement for filepath.Match(). -// -func PathMatch(pattern, name string) (bool, error) { - return matchWithSeparator(pattern, name, os.PathSeparator) -} - -// Match returns true if name matches the shell file name pattern. -// The pattern syntax is: -// -// pattern: -// { term } -// term: -// '*' matches any sequence of non-path-separators -// '**' matches any sequence of characters, including -// path separators. -// '?' matches any single non-path-separator character -// '[' [ '^' ] { character-range } ']' -// character class (must be non-empty) -// '{' { term } [ ',' { term } ... ] '}' -// c matches character c (c != '*', '?', '\\', '[') -// '\\' c matches character c -// -// character-range: -// c matches character c (c != '\\', '-', ']') -// '\\' c matches character c, unless separator is '\\' -// lo '-' hi matches character c for lo <= c <= hi -// -// Match requires pattern to match all of name, not just a substring. -// The only possible returned error is ErrBadPattern, when pattern -// is malformed. -// -func matchWithSeparator(pattern, name string, separator rune) (bool, error) { - patternComponents := splitPathOnSeparator(pattern, separator) - nameComponents := splitPathOnSeparator(name, separator) - return doMatching(patternComponents, nameComponents) -} - -func doMatching(patternComponents, nameComponents []string) (matched bool, err error) { - // check for some base-cases - patternLen, nameLen := len(patternComponents), len(nameComponents) - if patternLen == 0 && nameLen == 0 { - return true, nil - } - if patternLen == 0 || nameLen == 0 { - return false, nil - } - - patIdx, nameIdx := 0, 0 - for patIdx < patternLen && nameIdx < nameLen { - if patternComponents[patIdx] == "**" { - // if our last pattern component is a doublestar, we're done - - // doublestar will match any remaining name components, if any. - if patIdx++; patIdx >= patternLen { - return true, nil - } - - // otherwise, try matching remaining components - for ; nameIdx < nameLen; nameIdx++ { - if m, _ := doMatching(patternComponents[patIdx:], nameComponents[nameIdx:]); m { - return true, nil - } - } - return false, nil - } - - // try matching components - matched, err = matchComponent(patternComponents[patIdx], nameComponents[nameIdx]) - if !matched || err != nil { - return - } - - patIdx++ - nameIdx++ - } - return patIdx >= patternLen && nameIdx >= nameLen, nil -} - -// Glob returns the names of all files matching pattern or nil -// if there is no matching file. The syntax of pattern is the same -// as in Match. The pattern may describe hierarchical names such as -// /usr/*/bin/ed (assuming the Separator is '/'). -// -// Glob ignores file system errors such as I/O errors reading directories. -// The only possible returned error is ErrBadPattern, when pattern -// is malformed. -// -// Your system path separator is automatically used. This means on -// systems where the separator is '\\' (Windows), escaping will be -// disabled. -// -// Note: this is meant as a drop-in replacement for filepath.Glob(). -// -func Glob(pattern string) (matches []string, err error) { - patternComponents := splitPathOnSeparator(filepath.ToSlash(pattern), '/') - if len(patternComponents) == 0 { - return nil, nil - } - - // On Windows systems, this will return the drive name ('C:') for filesystem - // paths, or \\\ for UNC paths. On other systems, it will - // return an empty string. Since absolute paths on non-Windows systems start - // with a slash, patternComponent[0] == volumeName will return true for both - // absolute Windows paths and absolute non-Windows paths, but we need a - // separate check for UNC paths. - volumeName := filepath.VolumeName(pattern) - isWindowsUNC := strings.HasPrefix(pattern, `\\`) - if isWindowsUNC || patternComponents[0] == volumeName { - startComponentIndex := 1 - if isWindowsUNC { - startComponentIndex = 4 - } - return doGlob(fmt.Sprintf("%s%s", volumeName, string(os.PathSeparator)), patternComponents[startComponentIndex:], matches) - } - - // otherwise, it's a relative pattern - return doGlob(".", patternComponents, matches) -} - -// Perform a glob -func doGlob(basedir string, components, matches []string) (m []string, e error) { - m = matches - e = nil - - // figure out how many components we don't need to glob because they're - // just names without patterns - we'll use os.Lstat below to check if that - // path actually exists - patLen := len(components) - patIdx := 0 - for ; patIdx < patLen; patIdx++ { - if strings.IndexAny(components[patIdx], "*?[{\\") >= 0 { - break - } - } - if patIdx > 0 { - basedir = filepath.Join(basedir, filepath.Join(components[0:patIdx]...)) - } - - // Lstat will return an error if the file/directory doesn't exist - fi, err := os.Lstat(basedir) - if err != nil { - return - } - - // if there are no more components, we've found a match - if patIdx >= patLen { - m = append(m, basedir) - return - } - - // otherwise, we need to check each item in the directory... - // first, if basedir is a symlink, follow it... - if (fi.Mode() & os.ModeSymlink) != 0 { - fi, err = os.Stat(basedir) - if err != nil { - return - } - } - - // confirm it's a directory... - if !fi.IsDir() { - return - } - - // read directory - dir, err := os.Open(basedir) - if err != nil { - return - } - defer dir.Close() - - files, _ := dir.Readdir(-1) - lastComponent := (patIdx + 1) >= patLen - if components[patIdx] == "**" { - // if the current component is a doublestar, we'll try depth-first - for _, file := range files { - // if symlink, we may want to follow - if (file.Mode() & os.ModeSymlink) != 0 { - file, err = os.Stat(filepath.Join(basedir, file.Name())) - if err != nil { - continue - } - } - - if file.IsDir() { - // recurse into directories - if lastComponent { - m = append(m, filepath.Join(basedir, file.Name())) - } - m, e = doGlob(filepath.Join(basedir, file.Name()), components[patIdx:], m) - } else if lastComponent { - // if the pattern's last component is a doublestar, we match filenames, too - m = append(m, filepath.Join(basedir, file.Name())) - } - } - if lastComponent { - return // we're done - } - patIdx++ - lastComponent = (patIdx + 1) >= patLen - } - - // check items in current directory and recurse - var match bool - for _, file := range files { - match, e = matchComponent(components[patIdx], file.Name()) - if e != nil { - return - } - if match { - if lastComponent { - m = append(m, filepath.Join(basedir, file.Name())) - } else { - m, e = doGlob(filepath.Join(basedir, file.Name()), components[patIdx+1:], m) - } - } - } - return -} - -// Attempt to match a single pattern component with a path component -func matchComponent(pattern, name string) (bool, error) { - // check some base cases - patternLen, nameLen := len(pattern), len(name) - if patternLen == 0 && nameLen == 0 { - return true, nil - } - if patternLen == 0 { - return false, nil - } - if nameLen == 0 && pattern != "*" { - return false, nil - } - - // check for matches one rune at a time - patIdx, nameIdx := 0, 0 - for patIdx < patternLen && nameIdx < nameLen { - patRune, patAdj := utf8.DecodeRuneInString(pattern[patIdx:]) - nameRune, nameAdj := utf8.DecodeRuneInString(name[nameIdx:]) - if patRune == '\\' { - // handle escaped runes - patIdx += patAdj - patRune, patAdj = utf8.DecodeRuneInString(pattern[patIdx:]) - if patRune == utf8.RuneError { - return false, ErrBadPattern - } else if patRune == nameRune { - patIdx += patAdj - nameIdx += nameAdj - } else { - return false, nil - } - } else if patRune == '*' { - // handle stars - if patIdx += patAdj; patIdx >= patternLen { - // a star at the end of a pattern will always - // match the rest of the path - return true, nil - } - - // check if we can make any matches - for ; nameIdx < nameLen; nameIdx += nameAdj { - if m, _ := matchComponent(pattern[patIdx:], name[nameIdx:]); m { - return true, nil - } - } - return false, nil - } else if patRune == '[' { - // handle character sets - patIdx += patAdj - endClass := indexRuneWithEscaping(pattern[patIdx:], ']') - if endClass == -1 { - return false, ErrBadPattern - } - endClass += patIdx - classRunes := []rune(pattern[patIdx:endClass]) - classRunesLen := len(classRunes) - if classRunesLen > 0 { - classIdx := 0 - matchClass := false - if classRunes[0] == '^' { - classIdx++ - } - for classIdx < classRunesLen { - low := classRunes[classIdx] - if low == '-' { - return false, ErrBadPattern - } - classIdx++ - if low == '\\' { - if classIdx < classRunesLen { - low = classRunes[classIdx] - classIdx++ - } else { - return false, ErrBadPattern - } - } - high := low - if classIdx < classRunesLen && classRunes[classIdx] == '-' { - // we have a range of runes - if classIdx++; classIdx >= classRunesLen { - return false, ErrBadPattern - } - high = classRunes[classIdx] - if high == '-' { - return false, ErrBadPattern - } - classIdx++ - if high == '\\' { - if classIdx < classRunesLen { - high = classRunes[classIdx] - classIdx++ - } else { - return false, ErrBadPattern - } - } - } - if low <= nameRune && nameRune <= high { - matchClass = true - } - } - if matchClass == (classRunes[0] == '^') { - return false, nil - } - } else { - return false, ErrBadPattern - } - patIdx = endClass + 1 - nameIdx += nameAdj - } else if patRune == '{' { - // handle alternatives such as {alt1,alt2,...} - patIdx += patAdj - endOptions := indexRuneWithEscaping(pattern[patIdx:], '}') - if endOptions == -1 { - return false, ErrBadPattern - } - endOptions += patIdx - options := splitPathOnSeparator(pattern[patIdx:endOptions], ',') - patIdx = endOptions + 1 - for _, o := range options { - m, e := matchComponent(o+pattern[patIdx:], name[nameIdx:]) - if e != nil { - return false, e - } - if m { - return true, nil - } - } - return false, nil - } else if patRune == '?' || patRune == nameRune { - // handle single-rune wildcard - patIdx += patAdj - nameIdx += nameAdj - } else { - return false, nil - } - } - if patIdx >= patternLen && nameIdx >= nameLen { - return true, nil - } - if nameIdx >= nameLen && pattern[patIdx:] == "*" || pattern[patIdx:] == "**" { - return true, nil - } - return false, nil -} diff --git a/vendor/github.com/bmatcuk/doublestar/go.mod b/vendor/github.com/bmatcuk/doublestar/go.mod deleted file mode 100644 index ce1688f730..0000000000 --- a/vendor/github.com/bmatcuk/doublestar/go.mod +++ /dev/null @@ -1,3 +0,0 @@ -module github.com/bmatcuk/doublestar - -go 1.12 diff --git a/vendor/github.com/hashicorp/go-getter/.travis.yml b/vendor/github.com/hashicorp/go-getter/.travis.yml new file mode 100644 index 0000000000..4fe9176aab --- /dev/null +++ b/vendor/github.com/hashicorp/go-getter/.travis.yml @@ -0,0 +1,24 @@ +sudo: false + +addons: + apt: + sources: + - sourceline: 'ppa:git-core/ppa' + packages: + - git + +language: go + +os: + - linux + - osx + +go: + - "1.11.x" + +before_script: + - go build ./cmd/go-getter + +branches: + only: + - master diff --git a/vendor/github.com/hashicorp/go-getter/README.md b/vendor/github.com/hashicorp/go-getter/README.md index bbcd15de96..3de23c7094 100644 --- a/vendor/github.com/hashicorp/go-getter/README.md +++ b/vendor/github.com/hashicorp/go-getter/README.md @@ -1,10 +1,10 @@ # go-getter -[![CircleCI](https://circleci.com/gh/hashicorp/go-getter/tree/master.svg?style=svg)][circleci] +[![Build Status](http://img.shields.io/travis/hashicorp/go-getter.svg?style=flat-square)][travis] [![Build status](https://ci.appveyor.com/api/projects/status/ulq3qr43n62croyq/branch/master?svg=true)][appveyor] [![Go Documentation](http://img.shields.io/badge/go-documentation-blue.svg?style=flat-square)][godocs] -[circleci]: https://circleci.com/gh/hashicorp/go-getter/tree/master +[travis]: http://travis-ci.org/hashicorp/go-getter [godocs]: http://godoc.org/github.com/hashicorp/go-getter [appveyor]: https://ci.appveyor.com/project/hashicorp/go-getter/branch/master @@ -356,7 +356,3 @@ In order to access to GCS, authentication credentials should be provided. More i - gcs::https://www.googleapis.com/storage/v1/bucket - gcs::https://www.googleapis.com/storage/v1/bucket/foo.zip - www.googleapis.com/storage/v1/bucket/foo - -#### GCS Testing - -The tests for `get_gcs.go` require you to have GCP credentials set in your environment. These credentials can have any level of permissions to any project, they just need to exist. This means setting `GOOGLE_APPLICATION_CREDENTIALS="~/path/to/credentials.json"` or `GOOGLE_CREDENTIALS="{stringified-credentials-json}"`. Due to this configuration, `get_gcs_test.go` will fail for external contributors in CircleCI. diff --git a/vendor/github.com/hashicorp/go-getter/client.go b/vendor/github.com/hashicorp/go-getter/client.go index 38fb43b8f5..007a78ba7c 100644 --- a/vendor/github.com/hashicorp/go-getter/client.go +++ b/vendor/github.com/hashicorp/go-getter/client.go @@ -19,7 +19,7 @@ import ( // Using a client directly allows more fine-grained control over how downloading // is done, as well as customizing the protocols supported. type Client struct { - // Ctx for cancellation + // Ctx for cancellation Ctx context.Context // Src is the source URL to get. diff --git a/vendor/github.com/hashicorp/go-getter/get_git.go b/vendor/github.com/hashicorp/go-getter/get_git.go index 1b9f4be819..bb1ec316d3 100644 --- a/vendor/github.com/hashicorp/go-getter/get_git.go +++ b/vendor/github.com/hashicorp/go-getter/get_git.go @@ -1,7 +1,6 @@ package getter import ( - "bytes" "context" "encoding/base64" "fmt" @@ -10,7 +9,6 @@ import ( "os" "os/exec" "path/filepath" - "regexp" "runtime" "strconv" "strings" @@ -26,8 +24,6 @@ type GitGetter struct { getter } -var defaultBranchRegexp = regexp.MustCompile(`\s->\sorigin/(.*)`) - func (g *GitGetter) ClientMode(_ *url.URL) (ClientMode, error) { return ClientModeDir, nil } @@ -186,10 +182,10 @@ func (g *GitGetter) update(ctx context.Context, dst, sshKeyFile, ref string, dep cmd.Dir = dst if getRunCommand(cmd) != nil { - // Not a branch, switch to default branch. This will also catch - // non-existent branches, in which case we want to switch to default - // and then checkout the proper branch later. - ref = findDefaultBranch(dst) + // Not a branch, switch to master. This will also catch non-existent + // branches, in which case we want to switch to master and then + // checkout the proper branch later. + ref = "master" } // We have to be on a branch to pull @@ -220,22 +216,6 @@ func (g *GitGetter) fetchSubmodules(ctx context.Context, dst, sshKeyFile string, return getRunCommand(cmd) } -// findDefaultBranch checks the repo's origin remote for its default branch -// (generally "master"). "master" is returned if an origin default branch -// can't be determined. -func findDefaultBranch(dst string) string { - var stdoutbuf bytes.Buffer - cmd := exec.Command("git", "branch", "-r", "--points-at", "refs/remotes/origin/HEAD") - cmd.Dir = dst - cmd.Stdout = &stdoutbuf - err := cmd.Run() - matches := defaultBranchRegexp.FindStringSubmatch(stdoutbuf.String()) - if err != nil || matches == nil { - return "master" - } - return matches[len(matches)-1] -} - // setupGitEnv sets up the environment for the given command. This is used to // pass configuration data to git and ssh and enables advanced cloning methods. func setupGitEnv(cmd *exec.Cmd, sshKeyFile string) { diff --git a/vendor/github.com/hashicorp/go-getter/get_http.go b/vendor/github.com/hashicorp/go-getter/get_http.go index 9ffdba78a5..7c4541c6e9 100644 --- a/vendor/github.com/hashicorp/go-getter/get_http.go +++ b/vendor/github.com/hashicorp/go-getter/get_http.go @@ -9,6 +9,7 @@ import ( "net/url" "os" "path/filepath" + "strconv" "strings" safetemp "github.com/hashicorp/go-safetemp" @@ -87,10 +88,7 @@ func (g *HttpGetter) Get(dst string, u *url.URL) error { return err } - if g.Header != nil { - req.Header = g.Header - } - + req.Header = g.Header resp, err := g.Client.Do(req) if err != nil { return err @@ -130,12 +128,6 @@ func (g *HttpGetter) Get(dst string, u *url.URL) error { return g.getSubdir(ctx, dst, source, subDir) } -// GetFile fetches the file from src and stores it at dst. -// If the server supports Accept-Range, HttpGetter will attempt a range -// request. This means it is the caller's responsibility to ensure that an -// older version of the destination file does not exist, else it will be either -// falsely identified as being replaced, or corrupted with extra bytes -// appended. func (g *HttpGetter) GetFile(dst string, src *url.URL) error { ctx := g.Context() if g.Netrc { @@ -144,6 +136,7 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { return err } } + // Create all the parent directories if needed if err := os.MkdirAll(filepath.Dir(dst), 0755); err != nil { return err @@ -172,17 +165,18 @@ func (g *HttpGetter) GetFile(dst string, src *url.URL) error { req.Header = g.Header } headResp, err := g.Client.Do(req) - if err == nil { + if err == nil && headResp != nil { headResp.Body.Close() if headResp.StatusCode == 200 { // If the HEAD request succeeded, then attempt to set the range // query if we can. - if headResp.Header.Get("Accept-Ranges") == "bytes" && headResp.ContentLength >= 0 { + if headResp.Header.Get("Accept-Ranges") == "bytes" { if fi, err := f.Stat(); err == nil { - if _, err = f.Seek(0, io.SeekEnd); err == nil { + if _, err = f.Seek(0, os.SEEK_END); err == nil { + req.Header.Set("Range", fmt.Sprintf("bytes=%d-", fi.Size())) currentFileSize = fi.Size() - req.Header.Set("Range", fmt.Sprintf("bytes=%d-", currentFileSize)) - if currentFileSize >= headResp.ContentLength { + totalFileSize, _ := strconv.ParseInt(headResp.Header.Get("Content-Length"), 10, 64) + if currentFileSize >= totalFileSize { // file already present return nil } diff --git a/vendor/github.com/hashicorp/hcl/v2/appveyor.yml b/vendor/github.com/hashicorp/hcl/v2/appveyor.yml deleted file mode 100644 index e382f8f571..0000000000 --- a/vendor/github.com/hashicorp/hcl/v2/appveyor.yml +++ /dev/null @@ -1,13 +0,0 @@ -build: off - -clone_folder: c:\gopath\src\github.com\hashicorp\hcl - -environment: - GOPATH: c:\gopath - GO111MODULE: on - GOPROXY: https://goproxy.io - -stack: go 1.12 - -test_script: - - go test ./... diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md deleted file mode 100644 index 1636f577a0..0000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/README.md +++ /dev/null @@ -1,209 +0,0 @@ -# HCL Custom Static Decoding Extension - -This HCL extension provides a mechanism for defining arguments in an HCL-based -language whose values are derived using custom decoding rules against the -HCL expression syntax, overriding the usual behavior of normal expression -evaluation. - -"Arguments", for the purpose of this extension, currently includes the -following two contexts: - -* For applications using `hcldec` for dynamic decoding, a `hcldec.AttrSpec` - or `hcldec.BlockAttrsSpec` can be given a special type constraint that - opts in to custom decoding behavior for the attribute(s) that are selected - by that specification. - -* When working with the HCL native expression syntax, a function given in - the `hcl.EvalContext` during evaluation can have parameters with special - type constraints that opt in to custom decoding behavior for the argument - expression associated with that parameter in any call. - -The above use-cases are rather abstract, so we'll consider a motivating -real-world example: sometimes we (language designers) need to allow users -to specify type constraints directly in the language itself, such as in -[Terraform's Input Variables](https://www.terraform.io/docs/configuration/variables.html). -Terraform's `variable` blocks include an argument called `type` which takes -a type constraint given using HCL expression building-blocks as defined by -[the HCL `typeexpr` extension](../typeexpr/README.md). - -A "type constraint expression" of that sort is not an expression intended to -be evaluated in the usual way. Instead, the physical expression is -deconstructed using [the static analysis operations](../../spec.md#static-analysis) -to produce a `cty.Type` as the result, rather than a `cty.Value`. - -The purpose of this Custom Static Decoding Extension, then, is to provide a -bridge to allow that sort of custom decoding to be used via mechanisms that -normally deal in `cty.Value`, such as `hcldec` and native syntax function -calls as listed above. - -(Note: [`gohcl`](https://pkg.go.dev/github.com/hashicorp/hcl/v2/gohcl) has -its own mechanism to support this use case, exploiting the fact that it is -working directly with "normal" Go types. Decoding into a struct field of -type `hcl.Expression` obtains the expression directly without evaluating it -first. The Custom Static Decoding Extension is not necessary for that `gohcl` -technique. You can also implement custom decoding by working directly with -the lowest-level HCL API, which separates extraction of and evaluation of -expressions into two steps.) - -## Custom Decoding Types - -This extension relies on a convention implemented in terms of -[_Capsule Types_ in the underlying `cty` type system](https://github.com/zclconf/go-cty/blob/master/docs/types.md#capsule-types). `cty` allows a capsule type to carry arbitrary -extension metadata values as an aid to creating higher-level abstractions like -this extension. - -A custom argument decoding mode, then, is implemented by creating a new `cty` -capsule type that implements the `ExtensionData` custom operation to return -a decoding function when requested. For example: - -```go -var keywordType cty.Type -keywordType = cty.CapsuleWithOps("keyword", reflect.TypeOf(""), &cty.CapsuleOps{ - ExtensionData: func(key interface{}) interface{} { - switch key { - case customdecode.CustomExpressionDecoder: - return customdecode.CustomExpressionDecoderFunc( - func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - var diags hcl.Diagnostics - kw := hcl.ExprAsKeyword(expr) - if kw == "" { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid keyword", - Detail: "A keyword is required", - Subject: expr.Range().Ptr(), - }) - return cty.UnkownVal(keywordType), diags - } - return cty.CapsuleVal(keywordType, &kw) - }, - ) - default: - return nil - } - }, -}) -``` - -The boilerplate here is a bit fussy, but the important part for our purposes -is the `case customdecode.CustomExpressionDecoder:` clause, which uses -a custom extension key type defined in this package to recognize when a -component implementing this extension is checking to see if a target type -has a custom decode implementation. - -In the above case we've defined a type that decodes expressions as static -keywords, so a keyword like `foo` would decode as an encapsulated `"foo"` -string, while any other sort of expression like `"baz"` or `1 + 1` would -return an error. - -We could then use `keywordType` as a type constraint either for a function -parameter or a `hcldec` attribute specification, which would require the -argument for that function parameter or the expression for the matching -attributes to be a static keyword, rather than an arbitrary expression. -For example, in a `hcldec.AttrSpec`: - -```go -keywordSpec := &hcldec.AttrSpec{ - Name: "keyword", - Type: keywordType, -} -``` - -The above would accept input like the following and would set its result to -a `cty.Value` of `keywordType`, after decoding: - -```hcl -keyword = foo -``` - -## The Expression and Expression Closure `cty` types - -Building on the above, this package also includes two capsule types that use -the above mechanism to allow calling applications to capture expressions -directly and thus defer analysis to a later step, after initial decoding. - -The `customdecode.ExpressionType` type encapsulates an `hcl.Expression` alone, -for situations like our type constraint expression example above where it's -the static structure of the expression we want to inspect, and thus any -variables and functions defined in the evaluation context are irrelevant. - -The `customdecode.ExpressionClosureType` type encapsulates a -`*customdecode.ExpressionClosure` value, which binds the given expression to -the `hcl.EvalContext` it was asked to evaluate against and thus allows the -receiver of that result to later perform normal evaluation of the expression -with all the same variables and functions that would've been available to it -naturally. - -Both of these types can be used as type constraints either for `hcldec` -attribute specifications or for function arguments. Here's an example of -`ExpressionClosureType` to implement a function that can evaluate -an expression with some additional variables defined locally, which we'll -call the `with(...)` function: - -```go -var WithFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "variables", - Type: cty.DynamicPseudoType, - }, - { - Name: "expression", - Type: customdecode.ExpressionClosureType, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - varsVal := args[0] - exprVal := args[1] - if !varsVal.Type().IsObjectType() { - return cty.NilVal, function.NewArgErrorf(0, "must be an object defining local variables") - } - if !varsVal.IsKnown() { - // We can't predict our result type until the variables object - // is known. - return cty.DynamicPseudoType, nil - } - vars := varsVal.AsValueMap() - closure := customdecode.ExpressionClosureFromVal(exprVal) - result, err := evalWithLocals(vars, closure) - if err != nil { - return cty.NilVal, err - } - return result.Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - varsVal := args[0] - exprVal := args[1] - vars := varsVal.AsValueMap() - closure := customdecode.ExpressionClosureFromVal(exprVal) - return evalWithLocals(vars, closure) - }, -}) - -func evalWithLocals(locals map[string]cty.Value, closure *customdecode.ExpressionClosure) (cty.Value, error) { - childCtx := closure.EvalContext.NewChild() - childCtx.Variables = locals - val, diags := closure.Expression.Value(childCtx) - if diags.HasErrors() { - return cty.NilVal, function.NewArgErrorf(1, "couldn't evaluate expression: %s", diags.Error()) - } - return val, nil -} -``` - -If the above function were placed into an `hcl.EvalContext` as `with`, it -could be used in a native syntax call to that function as follows: - -```hcl - foo = with({name = "Cory"}, "${greeting}, ${name}!") -``` - -The above assumes a variable in the main context called `greeting`, to which -the `with` function adds `name` before evaluating the expression given in -its second argument. This makes that second argument context-sensitive -- it -would behave differently if the user wrote the same thing somewhere else -- so -this capability should be used with care to make sure it doesn't cause confusion -for the end-users of your language. - -There are some other examples of this capability to evaluate expressions in -unusual ways in the `tryfunc` directory that is a sibling of this one. diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go deleted file mode 100644 index c9d7a1efb2..0000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/customdecode.go +++ /dev/null @@ -1,56 +0,0 @@ -// Package customdecode contains a HCL extension that allows, in certain -// contexts, expression evaluation to be overridden by custom static analysis. -// -// This mechanism is only supported in certain specific contexts where -// expressions are decoded with a specific target type in mind. For more -// information, see the documentation on CustomExpressionDecoder. -package customdecode - -import ( - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -type customDecoderImpl int - -// CustomExpressionDecoder is a value intended to be used as a cty capsule -// type ExtensionData key for capsule types whose values are to be obtained -// by static analysis of an expression rather than normal evaluation of that -// expression. -// -// When a cooperating capsule type is asked for ExtensionData with this key, -// it must return a non-nil CustomExpressionDecoderFunc value. -// -// This mechanism is not universally supported; instead, it's handled in a few -// specific places where expressions are evaluated with the intent of producing -// a cty.Value of a type given by the calling application. -// -// Specifically, this currently works for type constraints given in -// hcldec.AttrSpec and hcldec.BlockAttrsSpec, and it works for arguments to -// function calls in the HCL native syntax. HCL extensions implemented outside -// of the main HCL module may also implement this; consult their own -// documentation for details. -const CustomExpressionDecoder = customDecoderImpl(1) - -// CustomExpressionDecoderFunc is the type of value that must be returned by -// a capsule type handling the key CustomExpressionDecoder in its ExtensionData -// implementation. -// -// If no error diagnostics are returned, the result value MUST be of the -// capsule type that the decoder function was derived from. If the returned -// error diagnostics prevent producing a value at all, return cty.NilVal. -type CustomExpressionDecoderFunc func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) - -// CustomExpressionDecoderForType takes any cty type and returns its -// custom expression decoder implementation if it has one. If it is not a -// capsule type or it does not implement a custom expression decoder, this -// function returns nil. -func CustomExpressionDecoderForType(ty cty.Type) CustomExpressionDecoderFunc { - if !ty.IsCapsuleType() { - return nil - } - if fn, ok := ty.CapsuleExtensionData(CustomExpressionDecoder).(CustomExpressionDecoderFunc); ok { - return fn - } - return nil -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go b/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go deleted file mode 100644 index af7c66c235..0000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/customdecode/expression_type.go +++ /dev/null @@ -1,146 +0,0 @@ -package customdecode - -import ( - "fmt" - "reflect" - - "github.com/hashicorp/hcl/v2" - "github.com/zclconf/go-cty/cty" -) - -// ExpressionType is a cty capsule type that carries hcl.Expression values. -// -// This type implements custom decoding in the most general way possible: it -// just captures whatever expression is given to it, with no further processing -// whatsoever. It could therefore be useful in situations where an application -// must defer processing of the expression content until a later step. -// -// ExpressionType only captures the expression, not the evaluation context it -// was destined to be evaluated in. That means this type can be fine for -// situations where the recipient of the value only intends to do static -// analysis, but ExpressionClosureType is more appropriate in situations where -// the recipient will eventually evaluate the given expression. -var ExpressionType cty.Type - -// ExpressionVal returns a new cty value of type ExpressionType, wrapping the -// given expression. -func ExpressionVal(expr hcl.Expression) cty.Value { - return cty.CapsuleVal(ExpressionType, &expr) -} - -// ExpressionFromVal returns the expression encapsulated in the given value, or -// panics if the value is not a known value of ExpressionType. -func ExpressionFromVal(v cty.Value) hcl.Expression { - if !v.Type().Equals(ExpressionType) { - panic("value is not of ExpressionType") - } - ptr := v.EncapsulatedValue().(*hcl.Expression) - return *ptr -} - -// ExpressionClosureType is a cty capsule type that carries hcl.Expression -// values along with their original evaluation contexts. -// -// This is similar to ExpressionType except that during custom decoding it -// also captures the hcl.EvalContext that was provided, allowing callers to -// evaluate the expression later in the same context where it would originally -// have been evaluated, or a context derived from that one. -var ExpressionClosureType cty.Type - -// ExpressionClosure is the type encapsulated in ExpressionClosureType -type ExpressionClosure struct { - Expression hcl.Expression - EvalContext *hcl.EvalContext -} - -// ExpressionClosureVal returns a new cty value of type ExpressionClosureType, -// wrapping the given expression closure. -func ExpressionClosureVal(closure *ExpressionClosure) cty.Value { - return cty.CapsuleVal(ExpressionClosureType, closure) -} - -// Value evaluates the closure's expression using the closure's EvalContext, -// returning the result. -func (c *ExpressionClosure) Value() (cty.Value, hcl.Diagnostics) { - return c.Expression.Value(c.EvalContext) -} - -// ExpressionClosureFromVal returns the expression closure encapsulated in the -// given value, or panics if the value is not a known value of -// ExpressionClosureType. -// -// The caller MUST NOT modify the returned closure or the EvalContext inside -// it. To derive a new EvalContext, either create a child context or make -// a copy. -func ExpressionClosureFromVal(v cty.Value) *ExpressionClosure { - if !v.Type().Equals(ExpressionClosureType) { - panic("value is not of ExpressionClosureType") - } - return v.EncapsulatedValue().(*ExpressionClosure) -} - -func init() { - // Getting hold of a reflect.Type for hcl.Expression is a bit tricky because - // it's an interface type, but we can do it with some indirection. - goExpressionType := reflect.TypeOf((*hcl.Expression)(nil)).Elem() - - ExpressionType = cty.CapsuleWithOps("expression", goExpressionType, &cty.CapsuleOps{ - ExtensionData: func(key interface{}) interface{} { - switch key { - case CustomExpressionDecoder: - return CustomExpressionDecoderFunc( - func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - return ExpressionVal(expr), nil - }, - ) - default: - return nil - } - }, - TypeGoString: func(_ reflect.Type) string { - return "customdecode.ExpressionType" - }, - GoString: func(raw interface{}) string { - exprPtr := raw.(*hcl.Expression) - return fmt.Sprintf("customdecode.ExpressionVal(%#v)", *exprPtr) - }, - RawEquals: func(a, b interface{}) bool { - aPtr := a.(*hcl.Expression) - bPtr := b.(*hcl.Expression) - return reflect.DeepEqual(*aPtr, *bPtr) - }, - }) - ExpressionClosureType = cty.CapsuleWithOps("expression closure", reflect.TypeOf(ExpressionClosure{}), &cty.CapsuleOps{ - ExtensionData: func(key interface{}) interface{} { - switch key { - case CustomExpressionDecoder: - return CustomExpressionDecoderFunc( - func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - return ExpressionClosureVal(&ExpressionClosure{ - Expression: expr, - EvalContext: ctx, - }), nil - }, - ) - default: - return nil - } - }, - TypeGoString: func(_ reflect.Type) string { - return "customdecode.ExpressionClosureType" - }, - GoString: func(raw interface{}) string { - closure := raw.(*ExpressionClosure) - return fmt.Sprintf("customdecode.ExpressionClosureVal(%#v)", closure) - }, - RawEquals: func(a, b interface{}) bool { - closureA := a.(*ExpressionClosure) - closureB := b.(*ExpressionClosure) - // The expression itself compares by deep equality, but EvalContexts - // conventionally compare by pointer identity, so we'll comply - // with both conventions here by testing them separately. - return closureA.EvalContext == closureB.EvalContext && - reflect.DeepEqual(closureA.Expression, closureB.Expression) - }, - }) -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md b/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md deleted file mode 100644 index 5d56eeca83..0000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/README.md +++ /dev/null @@ -1,44 +0,0 @@ -# "Try" and "can" functions - -This Go package contains two `cty` functions intended for use in an -`hcl.EvalContext` when evaluating HCL native syntax expressions. - -The first function `try` attempts to evaluate each of its argument expressions -in order until one produces a result without any errors. - -```hcl -try(non_existent_variable, 2) # returns 2 -``` - -If none of the expressions succeed, the function call fails with all of the -errors it encountered. - -The second function `can` is similar except that it ignores the result of -the given expression altogether and simply returns `true` if the expression -produced a successful result or `false` if it produced errors. - -Both of these are primarily intended for working with deep data structures -which might not have a dependable shape. For example, we can use `try` to -attempt to fetch a value from deep inside a data structure but produce a -default value if any step of the traversal fails: - -```hcl -result = try(foo.deep[0].lots.of["traversals"], null) -``` - -The final result to `try` should generally be some sort of constant value that -will always evaluate successfully. - -## Using these functions - -Languages built on HCL can make `try` and `can` available to user code by -exporting them in the `hcl.EvalContext` used for expression evaluation: - -```go -ctx := &hcl.EvalContext{ - Functions: map[string]function.Function{ - "try": tryfunc.TryFunc, - "can": tryfunc.CanFunc, - }, -} -``` diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go b/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go deleted file mode 100644 index 2f4862f4a3..0000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/tryfunc/tryfunc.go +++ /dev/null @@ -1,150 +0,0 @@ -// Package tryfunc contains some optional functions that can be exposed in -// HCL-based languages to allow authors to test whether a particular expression -// can succeed and take dynamic action based on that result. -// -// These functions are implemented in terms of the customdecode extension from -// the sibling directory "customdecode", and so they are only useful when -// used within an HCL EvalContext. Other systems using cty functions are -// unlikely to support the HCL-specific "customdecode" extension. -package tryfunc - -import ( - "errors" - "fmt" - "strings" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/ext/customdecode" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/function" -) - -// TryFunc is a variadic function that tries to evaluate all of is arguments -// in sequence until one succeeds, in which case it returns that result, or -// returns an error if none of them succeed. -var TryFunc function.Function - -// CanFunc tries to evaluate the expression given in its first argument. -var CanFunc function.Function - -func init() { - TryFunc = function.New(&function.Spec{ - VarParam: &function.Parameter{ - Name: "expressions", - Type: customdecode.ExpressionClosureType, - }, - Type: func(args []cty.Value) (cty.Type, error) { - v, err := try(args) - if err != nil { - return cty.NilType, err - } - return v.Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return try(args) - }, - }) - CanFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "expression", - Type: customdecode.ExpressionClosureType, - }, - }, - Type: function.StaticReturnType(cty.Bool), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - return can(args[0]) - }, - }) -} - -func try(args []cty.Value) (cty.Value, error) { - if len(args) == 0 { - return cty.NilVal, errors.New("at least one argument is required") - } - - // We'll collect up all of the diagnostics we encounter along the way - // and report them all if none of the expressions succeed, so that the - // user might get some hints on how to make at least one succeed. - var diags hcl.Diagnostics - for _, arg := range args { - closure := customdecode.ExpressionClosureFromVal(arg) - if dependsOnUnknowns(closure.Expression, closure.EvalContext) { - // We can't safely decide if this expression will succeed yet, - // and so our entire result must be unknown until we have - // more information. - return cty.DynamicVal, nil - } - - v, moreDiags := closure.Value() - diags = append(diags, moreDiags...) - if moreDiags.HasErrors() { - continue // try the next one, if there is one to try - } - return v, nil // ignore any accumulated diagnostics if one succeeds - } - - // If we fall out here then none of the expressions succeeded, and so - // we must have at least one diagnostic and we'll return all of them - // so that the user can see the errors related to whichever one they - // were expecting to have succeeded in this case. - // - // Because our function must return a single error value rather than - // diagnostics, we'll construct a suitable error message string - // that will make sense in the context of the function call failure - // diagnostic HCL will eventually wrap this in. - var buf strings.Builder - buf.WriteString("no expression succeeded:\n") - for _, diag := range diags { - if diag.Subject != nil { - buf.WriteString(fmt.Sprintf("- %s (at %s)\n %s\n", diag.Summary, diag.Subject, diag.Detail)) - } else { - buf.WriteString(fmt.Sprintf("- %s\n %s\n", diag.Summary, diag.Detail)) - } - } - buf.WriteString("\nAt least one expression must produce a successful result") - return cty.NilVal, errors.New(buf.String()) -} - -func can(arg cty.Value) (cty.Value, error) { - closure := customdecode.ExpressionClosureFromVal(arg) - if dependsOnUnknowns(closure.Expression, closure.EvalContext) { - // Can't decide yet, then. - return cty.UnknownVal(cty.Bool), nil - } - - _, diags := closure.Value() - if diags.HasErrors() { - return cty.False, nil - } - return cty.True, nil -} - -// dependsOnUnknowns returns true if any of the variables that the given -// expression might access are unknown values or contain unknown values. -// -// This is a conservative result that prefers to return true if there's any -// chance that the expression might derive from an unknown value during its -// evaluation; it is likely to produce false-positives for more complex -// expressions involving deep data structures. -func dependsOnUnknowns(expr hcl.Expression, ctx *hcl.EvalContext) bool { - for _, traversal := range expr.Variables() { - val, diags := traversal.TraverseAbs(ctx) - if diags.HasErrors() { - // If the traversal returned a definitive error then it must - // not traverse through any unknowns. - continue - } - if !val.IsWhollyKnown() { - // The value will be unknown if either it refers directly to - // an unknown value or if the traversal moves through an unknown - // collection. We're using IsWhollyKnown, so this also catches - // situations where the traversal refers to a compound data - // structure that contains any unknown values. That's important, - // because during evaluation the expression might evaluate more - // deeply into this structure and encounter the unknowns. - return true - } - } - return false -} diff --git a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go b/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go deleted file mode 100644 index 5462d82c3c..0000000000 --- a/vendor/github.com/hashicorp/hcl/v2/ext/typeexpr/type_type.go +++ /dev/null @@ -1,118 +0,0 @@ -package typeexpr - -import ( - "fmt" - "reflect" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/ext/customdecode" - "github.com/zclconf/go-cty/cty" - "github.com/zclconf/go-cty/cty/convert" - "github.com/zclconf/go-cty/cty/function" -) - -// TypeConstraintType is a cty capsule type that allows cty type constraints to -// be used as values. -// -// If TypeConstraintType is used in a context supporting the -// customdecode.CustomExpressionDecoder extension then it will implement -// expression decoding using the TypeConstraint function, thus allowing -// type expressions to be used in contexts where value expressions might -// normally be expected, such as in arguments to function calls. -var TypeConstraintType cty.Type - -// TypeConstraintVal constructs a cty.Value whose type is -// TypeConstraintType. -func TypeConstraintVal(ty cty.Type) cty.Value { - return cty.CapsuleVal(TypeConstraintType, &ty) -} - -// TypeConstraintFromVal extracts the type from a cty.Value of -// TypeConstraintType that was previously constructed using TypeConstraintVal. -// -// If the given value isn't a known, non-null value of TypeConstraintType -// then this function will panic. -func TypeConstraintFromVal(v cty.Value) cty.Type { - if !v.Type().Equals(TypeConstraintType) { - panic("value is not of TypeConstraintType") - } - ptr := v.EncapsulatedValue().(*cty.Type) - return *ptr -} - -// ConvertFunc is a cty function that implements type conversions. -// -// Its signature is as follows: -// convert(value, type_constraint) -// -// ...where type_constraint is a type constraint expression as defined by -// typeexpr.TypeConstraint. -// -// It relies on HCL's customdecode extension and so it's not suitable for use -// in non-HCL contexts or if you are using a HCL syntax implementation that -// does not support customdecode for function arguments. However, it _is_ -// supported for function calls in the HCL native expression syntax. -var ConvertFunc function.Function - -func init() { - TypeConstraintType = cty.CapsuleWithOps("type constraint", reflect.TypeOf(cty.Type{}), &cty.CapsuleOps{ - ExtensionData: func(key interface{}) interface{} { - switch key { - case customdecode.CustomExpressionDecoder: - return customdecode.CustomExpressionDecoderFunc( - func(expr hcl.Expression, ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) { - ty, diags := TypeConstraint(expr) - if diags.HasErrors() { - return cty.NilVal, diags - } - return TypeConstraintVal(ty), nil - }, - ) - default: - return nil - } - }, - TypeGoString: func(_ reflect.Type) string { - return "typeexpr.TypeConstraintType" - }, - GoString: func(raw interface{}) string { - tyPtr := raw.(*cty.Type) - return fmt.Sprintf("typeexpr.TypeConstraintVal(%#v)", *tyPtr) - }, - RawEquals: func(a, b interface{}) bool { - aPtr := a.(*cty.Type) - bPtr := b.(*cty.Type) - return (*aPtr).Equals(*bPtr) - }, - }) - - ConvertFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "value", - Type: cty.DynamicPseudoType, - AllowNull: true, - AllowDynamicType: true, - }, - { - Name: "type", - Type: TypeConstraintType, - }, - }, - Type: func(args []cty.Value) (cty.Type, error) { - wantTypePtr := args[1].EncapsulatedValue().(*cty.Type) - got, err := convert.Convert(args[0], *wantTypePtr) - if err != nil { - return cty.NilType, function.NewArgError(0, err) - } - return got.Type(), nil - }, - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - v, err := convert.Convert(args[0], retType) - if err != nil { - return cty.NilVal, function.NewArgError(0, err) - } - return v, nil - }, - }) -} diff --git a/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go b/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go index f0d589d777..7ba08eee00 100644 --- a/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go +++ b/vendor/github.com/hashicorp/hcl/v2/gohcl/decode.go @@ -147,9 +147,7 @@ func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) if len(blocks) == 0 { if isSlice || isPtr { - if val.Field(fieldIdx).IsNil() { - val.Field(fieldIdx).Set(reflect.Zero(field.Type)) - } + val.Field(fieldIdx).Set(reflect.Zero(field.Type)) } else { diags = append(diags, &hcl.Diagnostic{ Severity: hcl.DiagError, @@ -168,20 +166,11 @@ func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) if isPtr { elemType = reflect.PtrTo(ty) } - sli := val.Field(fieldIdx) - if sli.IsNil() { - sli = reflect.MakeSlice(reflect.SliceOf(elemType), len(blocks), len(blocks)) - } + sli := reflect.MakeSlice(reflect.SliceOf(elemType), len(blocks), len(blocks)) for i, block := range blocks { if isPtr { - if i >= sli.Len() { - sli = reflect.Append(sli, reflect.New(ty)) - } - v := sli.Index(i) - if v.IsNil() { - v = reflect.New(ty) - } + v := reflect.New(ty) diags = append(diags, decodeBlockToValue(block, ctx, v.Elem())...) sli.Index(i).Set(v) } else { @@ -189,19 +178,12 @@ func decodeBodyToStruct(body hcl.Body, ctx *hcl.EvalContext, val reflect.Value) } } - if sli.Len() > len(blocks) { - sli.SetLen(len(blocks)) - } - val.Field(fieldIdx).Set(sli) default: block := blocks[0] if isPtr { - v := val.Field(fieldIdx) - if v.IsNil() { - v = reflect.New(ty) - } + v := reflect.New(ty) diags = append(diags, decodeBlockToValue(block, ctx, v.Elem())...) val.Field(fieldIdx).Set(v) } else { diff --git a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go index f67d989e54..6fb284a8f7 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclsyntax/parser.go @@ -760,7 +760,7 @@ Traversal: Each: travExpr, Item: itemExpr, - SrcRange: hcl.RangeBetween(from.Range(), lastRange), + SrcRange: hcl.RangeBetween(dot.Range, lastRange), MarkerRange: hcl.RangeBetween(dot.Range, marker.Range), } @@ -819,7 +819,7 @@ Traversal: Each: travExpr, Item: itemExpr, - SrcRange: hcl.RangeBetween(from.Range(), travExpr.Range()), + SrcRange: hcl.RangeBetween(open.Range, travExpr.Range()), MarkerRange: hcl.RangeBetween(open.Range, close.Range), } @@ -867,9 +867,8 @@ Traversal: Collection: ret, Key: keyExpr, - SrcRange: hcl.RangeBetween(from.Range(), rng), - OpenRange: open.Range, - BracketRange: rng, + SrcRange: rng, + OpenRange: open.Range, } } } @@ -900,7 +899,7 @@ func makeRelativeTraversal(expr Expression, next hcl.Traverser, rng hcl.Range) E return &RelativeTraversalExpr{ Source: expr, Traversal: hcl.Traversal{next}, - SrcRange: hcl.RangeBetween(expr.Range(), rng), + SrcRange: rng, } } } diff --git a/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go b/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go index 073c30871e..854e71690b 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclwrite/ast_expression.go @@ -21,29 +21,6 @@ func newExpression() *Expression { } } -// NewExpressionRaw constructs an expression containing the given raw tokens. -// -// There is no automatic validation that the given tokens produce a valid -// expression. Callers of thus function must take care to produce invalid -// expression tokens. Where possible, use the higher-level functions -// NewExpressionLiteral or NewExpressionAbsTraversal instead. -// -// Because NewExpressionRaw does not interpret the given tokens in any way, -// an expression created by NewExpressionRaw will produce an empty result -// for calls to its method Variables, even if the given token sequence -// contains a subslice that would normally be interpreted as a traversal under -// parsing. -func NewExpressionRaw(tokens Tokens) *Expression { - expr := newExpression() - // We copy the tokens here in order to make sure that later mutations - // by the caller don't inadvertently cause our expression to become - // invalid. - copyTokens := make(Tokens, len(tokens)) - copy(copyTokens, tokens) - expr.children.AppendUnstructuredTokens(copyTokens) - return expr -} - // NewExpressionLiteral constructs an an expression that represents the given // literal value. // diff --git a/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go b/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go index 4d439acd7a..289a30d684 100644 --- a/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go +++ b/vendor/github.com/hashicorp/hcl/v2/hclwrite/generate.go @@ -159,12 +159,12 @@ func appendTokensForValue(val cty.Value, toks Tokens) Tokens { func appendTokensForTraversal(traversal hcl.Traversal, toks Tokens) Tokens { for _, step := range traversal { - toks = appendTokensForTraversalStep(step, toks) + appendTokensForTraversalStep(step, toks) } return toks } -func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) Tokens { +func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) { switch ts := step.(type) { case hcl.TraverseRoot: toks = append(toks, &Token{ @@ -188,7 +188,7 @@ func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) Tokens { Type: hclsyntax.TokenOBrack, Bytes: []byte{'['}, }) - toks = appendTokensForValue(ts.Key, toks) + appendTokensForValue(ts.Key, toks) toks = append(toks, &Token{ Type: hclsyntax.TokenCBrack, Bytes: []byte{']'}, @@ -196,8 +196,6 @@ func appendTokensForTraversalStep(step hcl.Traverser, toks Tokens) Tokens { default: panic(fmt.Sprintf("unsupported traversal step type %T", step)) } - - return toks } func escapeQuotedStringLit(s string) []byte { diff --git a/vendor/github.com/bmatcuk/doublestar/.gitignore b/vendor/github.com/hashicorp/logutils/.gitignore similarity index 81% rename from vendor/github.com/bmatcuk/doublestar/.gitignore rename to vendor/github.com/hashicorp/logutils/.gitignore index af212ecc28..00268614f0 100644 --- a/vendor/github.com/bmatcuk/doublestar/.gitignore +++ b/vendor/github.com/hashicorp/logutils/.gitignore @@ -1,8 +1,3 @@ -# vi -*~ -*.swp -*.swo - # Compiled Object files, Static and Dynamic libs (Shared Objects) *.o *.a @@ -25,8 +20,3 @@ _cgo_export.* _testmain.go *.exe -*.test -*.prof - -# test directory -test/ diff --git a/vendor/github.com/hashicorp/logutils/LICENSE b/vendor/github.com/hashicorp/logutils/LICENSE new file mode 100644 index 0000000000..c33dcc7c92 --- /dev/null +++ b/vendor/github.com/hashicorp/logutils/LICENSE @@ -0,0 +1,354 @@ +Mozilla Public License, version 2.0 + +1. Definitions + +1.1. “Contributor” + + means each individual or legal entity that creates, contributes to the + creation of, or owns Covered Software. + +1.2. “Contributor Version” + + means the combination of the Contributions of others (if any) used by a + Contributor and that particular Contributor’s Contribution. + +1.3. “Contribution” + + means Covered Software of a particular Contributor. + +1.4. “Covered Software” + + means Source Code Form to which the initial Contributor has attached the + notice in Exhibit A, the Executable Form of such Source Code Form, and + Modifications of such Source Code Form, in each case including portions + thereof. + +1.5. “Incompatible With Secondary Licenses” + means + + a. that the initial Contributor has attached the notice described in + Exhibit B to the Covered Software; or + + b. that the Covered Software was made available under the terms of version + 1.1 or earlier of the License, but not also under the terms of a + Secondary License. + +1.6. “Executable Form” + + means any form of the work other than Source Code Form. + +1.7. “Larger Work” + + means a work that combines Covered Software with other material, in a separate + file or files, that is not Covered Software. + +1.8. “License” + + means this document. + +1.9. “Licensable” + + means having the right to grant, to the maximum extent possible, whether at the + time of the initial grant or subsequently, any and all of the rights conveyed by + this License. + +1.10. “Modifications” + + means any of the following: + + a. any file in Source Code Form that results from an addition to, deletion + from, or modification of the contents of Covered Software; or + + b. any new file in Source Code Form that contains any Covered Software. + +1.11. “Patent Claims” of a Contributor + + means any patent claim(s), including without limitation, method, process, + and apparatus claims, in any patent Licensable by such Contributor that + would be infringed, but for the grant of the License, by the making, + using, selling, offering for sale, having made, import, or transfer of + either its Contributions or its Contributor Version. + +1.12. “Secondary License” + + means either the GNU General Public License, Version 2.0, the GNU Lesser + General Public License, Version 2.1, the GNU Affero General Public + License, Version 3.0, or any later versions of those licenses. + +1.13. “Source Code Form” + + means the form of the work preferred for making modifications. + +1.14. “You” (or “Your”) + + means an individual or a legal entity exercising rights under this + License. For legal entities, “You” includes any entity that controls, is + controlled by, or is under common control with You. For purposes of this + definition, “control” means (a) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (b) ownership of more than fifty percent (50%) of the + outstanding shares or beneficial ownership of such entity. + + +2. License Grants and Conditions + +2.1. Grants + + Each Contributor hereby grants You a world-wide, royalty-free, + non-exclusive license: + + a. under intellectual property rights (other than patent or trademark) + Licensable by such Contributor to use, reproduce, make available, + modify, display, perform, distribute, and otherwise exploit its + Contributions, either on an unmodified basis, with Modifications, or as + part of a Larger Work; and + + b. under Patent Claims of such Contributor to make, use, sell, offer for + sale, have made, import, and otherwise transfer either its Contributions + or its Contributor Version. + +2.2. Effective Date + + The licenses granted in Section 2.1 with respect to any Contribution become + effective for each Contribution on the date the Contributor first distributes + such Contribution. + +2.3. Limitations on Grant Scope + + The licenses granted in this Section 2 are the only rights granted under this + License. No additional rights or licenses will be implied from the distribution + or licensing of Covered Software under this License. Notwithstanding Section + 2.1(b) above, no patent license is granted by a Contributor: + + a. for any code that a Contributor has removed from Covered Software; or + + b. for infringements caused by: (i) Your and any other third party’s + modifications of Covered Software, or (ii) the combination of its + Contributions with other software (except as part of its Contributor + Version); or + + c. under Patent Claims infringed by Covered Software in the absence of its + Contributions. + + This License does not grant any rights in the trademarks, service marks, or + logos of any Contributor (except as may be necessary to comply with the + notice requirements in Section 3.4). + +2.4. Subsequent Licenses + + No Contributor makes additional grants as a result of Your choice to + distribute the Covered Software under a subsequent version of this License + (see Section 10.2) or under the terms of a Secondary License (if permitted + under the terms of Section 3.3). + +2.5. Representation + + Each Contributor represents that the Contributor believes its Contributions + are its original creation(s) or it has sufficient rights to grant the + rights to its Contributions conveyed by this License. + +2.6. Fair Use + + This License is not intended to limit any rights You have under applicable + copyright doctrines of fair use, fair dealing, or other equivalents. + +2.7. Conditions + + Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in + Section 2.1. + + +3. Responsibilities + +3.1. Distribution of Source Form + + All distribution of Covered Software in Source Code Form, including any + Modifications that You create or to which You contribute, must be under the + terms of this License. You must inform recipients that the Source Code Form + of the Covered Software is governed by the terms of this License, and how + they can obtain a copy of this License. You may not attempt to alter or + restrict the recipients’ rights in the Source Code Form. + +3.2. Distribution of Executable Form + + If You distribute Covered Software in Executable Form then: + + a. such Covered Software must also be made available in Source Code Form, + as described in Section 3.1, and You must inform recipients of the + Executable Form how they can obtain a copy of such Source Code Form by + reasonable means in a timely manner, at a charge no more than the cost + of distribution to the recipient; and + + b. You may distribute such Executable Form under the terms of this License, + or sublicense it under different terms, provided that the license for + the Executable Form does not attempt to limit or alter the recipients’ + rights in the Source Code Form under this License. + +3.3. Distribution of a Larger Work + + You may create and distribute a Larger Work under terms of Your choice, + provided that You also comply with the requirements of this License for the + Covered Software. If the Larger Work is a combination of Covered Software + with a work governed by one or more Secondary Licenses, and the Covered + Software is not Incompatible With Secondary Licenses, this License permits + You to additionally distribute such Covered Software under the terms of + such Secondary License(s), so that the recipient of the Larger Work may, at + their option, further distribute the Covered Software under the terms of + either this License or such Secondary License(s). + +3.4. Notices + + You may not remove or alter the substance of any license notices (including + copyright notices, patent notices, disclaimers of warranty, or limitations + of liability) contained within the Source Code Form of the Covered + Software, except that You may alter any license notices to the extent + required to remedy known factual inaccuracies. + +3.5. Application of Additional Terms + + You may choose to offer, and to charge a fee for, warranty, support, + indemnity or liability obligations to one or more recipients of Covered + Software. However, You may do so only on Your own behalf, and not on behalf + of any Contributor. You must make it absolutely clear that any such + warranty, support, indemnity, or liability obligation is offered by You + alone, and You hereby agree to indemnify every Contributor for any + liability incurred by such Contributor as a result of warranty, support, + indemnity or liability terms You offer. You may include additional + disclaimers of warranty and limitations of liability specific to any + jurisdiction. + +4. Inability to Comply Due to Statute or Regulation + + If it is impossible for You to comply with any of the terms of this License + with respect to some or all of the Covered Software due to statute, judicial + order, or regulation then You must: (a) comply with the terms of this License + to the maximum extent possible; and (b) describe the limitations and the code + they affect. Such description must be placed in a text file included with all + distributions of the Covered Software under this License. Except to the + extent prohibited by statute or regulation, such description must be + sufficiently detailed for a recipient of ordinary skill to be able to + understand it. + +5. Termination + +5.1. The rights granted under this License will terminate automatically if You + fail to comply with any of its terms. However, if You become compliant, + then the rights granted under this License from a particular Contributor + are reinstated (a) provisionally, unless and until such Contributor + explicitly and finally terminates Your grants, and (b) on an ongoing basis, + if such Contributor fails to notify You of the non-compliance by some + reasonable means prior to 60 days after You have come back into compliance. + Moreover, Your grants from a particular Contributor are reinstated on an + ongoing basis if such Contributor notifies You of the non-compliance by + some reasonable means, this is the first time You have received notice of + non-compliance with this License from such Contributor, and You become + compliant prior to 30 days after Your receipt of the notice. + +5.2. If You initiate litigation against any entity by asserting a patent + infringement claim (excluding declaratory judgment actions, counter-claims, + and cross-claims) alleging that a Contributor Version directly or + indirectly infringes any patent, then the rights granted to You by any and + all Contributors for the Covered Software under Section 2.1 of this License + shall terminate. + +5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user + license agreements (excluding distributors and resellers) which have been + validly granted by You or Your distributors under this License prior to + termination shall survive termination. + +6. Disclaimer of Warranty + + Covered Software is provided under this License on an “as is” basis, without + warranty of any kind, either expressed, implied, or statutory, including, + without limitation, warranties that the Covered Software is free of defects, + merchantable, fit for a particular purpose or non-infringing. The entire + risk as to the quality and performance of the Covered Software is with You. + Should any Covered Software prove defective in any respect, You (not any + Contributor) assume the cost of any necessary servicing, repair, or + correction. This disclaimer of warranty constitutes an essential part of this + License. No use of any Covered Software is authorized under this License + except under this disclaimer. + +7. Limitation of Liability + + Under no circumstances and under no legal theory, whether tort (including + negligence), contract, or otherwise, shall any Contributor, or anyone who + distributes Covered Software as permitted above, be liable to You for any + direct, indirect, special, incidental, or consequential damages of any + character including, without limitation, damages for lost profits, loss of + goodwill, work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses, even if such party shall have been + informed of the possibility of such damages. This limitation of liability + shall not apply to liability for death or personal injury resulting from such + party’s negligence to the extent applicable law prohibits such limitation. + Some jurisdictions do not allow the exclusion or limitation of incidental or + consequential damages, so this exclusion and limitation may not apply to You. + +8. Litigation + + Any litigation relating to this License may be brought only in the courts of + a jurisdiction where the defendant maintains its principal place of business + and such litigation shall be governed by laws of that jurisdiction, without + reference to its conflict-of-law provisions. Nothing in this Section shall + prevent a party’s ability to bring cross-claims or counter-claims. + +9. Miscellaneous + + This License represents the complete agreement concerning the subject matter + hereof. If any provision of this License is held to be unenforceable, such + provision shall be reformed only to the extent necessary to make it + enforceable. Any law or regulation which provides that the language of a + contract shall be construed against the drafter shall not be used to construe + this License against a Contributor. + + +10. Versions of the License + +10.1. New Versions + + Mozilla Foundation is the license steward. Except as provided in Section + 10.3, no one other than the license steward has the right to modify or + publish new versions of this License. Each version will be given a + distinguishing version number. + +10.2. Effect of New Versions + + You may distribute the Covered Software under the terms of the version of + the License under which You originally received the Covered Software, or + under the terms of any subsequent version published by the license + steward. + +10.3. Modified Versions + + If you create software not governed by this License, and you want to + create a new license for such software, you may create and use a modified + version of this License if you rename the license and remove any + references to the name of the license steward (except to note that such + modified license differs from this License). + +10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses + If You choose to distribute Source Code Form that is Incompatible With + Secondary Licenses under the terms of this version of the License, the + notice described in Exhibit B of this License must be attached. + +Exhibit A - Source Code Form License Notice + + This Source Code Form is subject to the + terms of the Mozilla Public License, v. + 2.0. If a copy of the MPL was not + distributed with this file, You can + obtain one at + http://mozilla.org/MPL/2.0/. + +If it is not possible or desirable to put the notice in a particular file, then +You may include the notice in a location (such as a LICENSE file in a relevant +directory) where a recipient would be likely to look for such a notice. + +You may add additional accurate notices of copyright ownership. + +Exhibit B - “Incompatible With Secondary Licenses” Notice + + This Source Code Form is “Incompatible + With Secondary Licenses”, as defined by + the Mozilla Public License, v. 2.0. + diff --git a/vendor/github.com/hashicorp/logutils/README.md b/vendor/github.com/hashicorp/logutils/README.md new file mode 100644 index 0000000000..49490eaeb6 --- /dev/null +++ b/vendor/github.com/hashicorp/logutils/README.md @@ -0,0 +1,36 @@ +# logutils + +logutils is a Go package that augments the standard library "log" package +to make logging a bit more modern, without fragmenting the Go ecosystem +with new logging packages. + +## The simplest thing that could possibly work + +Presumably your application already uses the default `log` package. To switch, you'll want your code to look like the following: + +```go +package main + +import ( + "log" + "os" + + "github.com/hashicorp/logutils" +) + +func main() { + filter := &logutils.LevelFilter{ + Levels: []logutils.LogLevel{"DEBUG", "WARN", "ERROR"}, + MinLevel: logutils.LogLevel("WARN"), + Writer: os.Stderr, + } + log.SetOutput(filter) + + log.Print("[DEBUG] Debugging") // this will not print + log.Print("[WARN] Warning") // this will + log.Print("[ERROR] Erring") // and so will this + log.Print("Message I haven't updated") // and so will this +} +``` + +This logs to standard error exactly like go's standard logger. Any log messages you haven't converted to have a level will continue to print as before. diff --git a/vendor/github.com/hashicorp/logutils/go.mod b/vendor/github.com/hashicorp/logutils/go.mod new file mode 100644 index 0000000000..ba38a45764 --- /dev/null +++ b/vendor/github.com/hashicorp/logutils/go.mod @@ -0,0 +1 @@ +module github.com/hashicorp/logutils diff --git a/vendor/github.com/hashicorp/logutils/level.go b/vendor/github.com/hashicorp/logutils/level.go new file mode 100644 index 0000000000..6381bf1629 --- /dev/null +++ b/vendor/github.com/hashicorp/logutils/level.go @@ -0,0 +1,81 @@ +// Package logutils augments the standard log package with levels. +package logutils + +import ( + "bytes" + "io" + "sync" +) + +type LogLevel string + +// LevelFilter is an io.Writer that can be used with a logger that +// will filter out log messages that aren't at least a certain level. +// +// Once the filter is in use somewhere, it is not safe to modify +// the structure. +type LevelFilter struct { + // Levels is the list of log levels, in increasing order of + // severity. Example might be: {"DEBUG", "WARN", "ERROR"}. + Levels []LogLevel + + // MinLevel is the minimum level allowed through + MinLevel LogLevel + + // The underlying io.Writer where log messages that pass the filter + // will be set. + Writer io.Writer + + badLevels map[LogLevel]struct{} + once sync.Once +} + +// Check will check a given line if it would be included in the level +// filter. +func (f *LevelFilter) Check(line []byte) bool { + f.once.Do(f.init) + + // Check for a log level + var level LogLevel + x := bytes.IndexByte(line, '[') + if x >= 0 { + y := bytes.IndexByte(line[x:], ']') + if y >= 0 { + level = LogLevel(line[x+1 : x+y]) + } + } + + _, ok := f.badLevels[level] + return !ok +} + +func (f *LevelFilter) Write(p []byte) (n int, err error) { + // Note in general that io.Writer can receive any byte sequence + // to write, but the "log" package always guarantees that we only + // get a single line. We use that as a slight optimization within + // this method, assuming we're dealing with a single, complete line + // of log data. + + if !f.Check(p) { + return len(p), nil + } + + return f.Writer.Write(p) +} + +// SetMinLevel is used to update the minimum log level +func (f *LevelFilter) SetMinLevel(min LogLevel) { + f.MinLevel = min + f.init() +} + +func (f *LevelFilter) init() { + badLevels := make(map[LogLevel]struct{}) + for _, level := range f.Levels { + if level == f.MinLevel { + break + } + badLevels[level] = struct{}{} + } + f.badLevels = badLevels +} diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go index a070f76e04..faa93ed6fb 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load.go @@ -52,12 +52,12 @@ func (m *Module) init(diags Diagnostics) { // case so callers can easily recognize it. for _, r := range m.ManagedResources { if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = &ProviderRequirement{} + m.RequiredProviders[r.Provider.Name] = []string{} } } for _, r := range m.DataResources { if _, exists := m.RequiredProviders[r.Provider.Name]; !exists { - m.RequiredProviders[r.Provider.Name] = &ProviderRequirement{} + m.RequiredProviders[r.Provider.Name] = []string{} } } diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go index c79b033b6b..86ffdf11dd 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/load_legacy.go @@ -267,15 +267,17 @@ func loadModuleLegacyHCL(dir string) (*Module, Diagnostics) { if err != nil { return nil, diagnosticsErrorf("invalid provider block at %s: %s", item.Pos(), err) } + + if block.Version != "" { + mod.RequiredProviders[name] = append(mod.RequiredProviders[name], block.Version) + } + // Even if there wasn't an explicit version required, we still // need an entry in our map to signal the unversioned dependency. if _, exists := mod.RequiredProviders[name]; !exists { - mod.RequiredProviders[name] = &ProviderRequirement{} + mod.RequiredProviders[name] = []string{} } - if block.Version != "" { - mod.RequiredProviders[name].VersionConstraints = append(mod.RequiredProviders[name].VersionConstraints, block.Version) - } } } } diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go index 63027d1841..65ddb23073 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/module.go @@ -9,8 +9,8 @@ type Module struct { Variables map[string]*Variable `json:"variables"` Outputs map[string]*Output `json:"outputs"` - RequiredCore []string `json:"required_core,omitempty"` - RequiredProviders map[string]*ProviderRequirement `json:"required_providers"` + RequiredCore []string `json:"required_core,omitempty"` + RequiredProviders map[string][]string `json:"required_providers"` ManagedResources map[string]*Resource `json:"managed_resources"` DataResources map[string]*Resource `json:"data_resources"` @@ -27,7 +27,7 @@ func newModule(path string) *Module { Path: path, Variables: make(map[string]*Variable), Outputs: make(map[string]*Output), - RequiredProviders: make(map[string]*ProviderRequirement), + RequiredProviders: make(map[string][]string), ManagedResources: make(map[string]*Resource), DataResources: make(map[string]*Resource), ModuleCalls: make(map[string]*ModuleCall), diff --git a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go index 157c8c2c15..d924837785 100644 --- a/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go +++ b/vendor/github.com/hashicorp/terraform-config-inspect/tfconfig/provider_ref.go @@ -1,11 +1,5 @@ package tfconfig -import ( - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/hcl/v2/gohcl" - "github.com/zclconf/go-cty/cty/gocty" -) - // ProviderRef is a reference to a provider configuration within a module. // It represents the contents of a "provider" argument in a resource, or // a value in the "providers" map for a module call. @@ -13,73 +7,3 @@ type ProviderRef struct { Name string `json:"name"` Alias string `json:"alias,omitempty"` // Empty if the default provider configuration is referenced } - -type ProviderRequirement struct { - Source string `json:"source,omitempty"` - VersionConstraints []string `json:"version_constraints,omitempty"` -} - -func decodeRequiredProvidersBlock(block *hcl.Block) (map[string]*ProviderRequirement, hcl.Diagnostics) { - attrs, diags := block.Body.JustAttributes() - reqs := make(map[string]*ProviderRequirement) - for name, attr := range attrs { - expr, err := attr.Expr.Value(nil) - if err != nil { - diags = append(diags, err...) - } - - switch { - case expr.Type().IsPrimitiveType(): - var version string - valDiags := gohcl.DecodeExpression(attr.Expr, nil, &version) - diags = append(diags, valDiags...) - if !valDiags.HasErrors() { - reqs[name] = &ProviderRequirement{ - VersionConstraints: []string{version}, - } - } - - case expr.Type().IsObjectType(): - var pr ProviderRequirement - if expr.Type().HasAttribute("version") { - var version string - err := gocty.FromCtyValue(expr.GetAttr("version"), &version) - if err == nil { - pr.VersionConstraints = append(pr.VersionConstraints, version) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsuitable value type", - Detail: "Unsuitable value: string required", - Subject: attr.Expr.Range().Ptr(), - }) - } - } - if expr.Type().HasAttribute("source") { - var source string - err := gocty.FromCtyValue(expr.GetAttr("source"), &source) - if err == nil { - pr.Source = source - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsuitable value type", - Detail: "Unsuitable value: string required", - Subject: attr.Expr.Range().Ptr(), - }) - } - } - reqs[name] = &pr - - default: - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unsuitable value type", - Detail: "Unsuitable value: string required", - Subject: attr.Expr.Range().Ptr(), - }) - } - } - - return reqs, diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go index 75627cf02e..6bd92f7778 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/logging/logging.go @@ -7,6 +7,8 @@ import ( "os" "strings" "syscall" + + "github.com/hashicorp/logutils" ) // These are the environmental variables that determine if we log, and if @@ -16,14 +18,13 @@ const ( EnvLogFile = "TF_LOG_PATH" // Set to a file ) -// ValidLevels are the log level names that Terraform recognizes. -var ValidLevels = []LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} +var ValidLevels = []logutils.LogLevel{"TRACE", "DEBUG", "INFO", "WARN", "ERROR"} // LogOutput determines where we should send logs (if anywhere) and the log level. func LogOutput() (logOutput io.Writer, err error) { logOutput = ioutil.Discard - logLevel := CurrentLogLevel() + logLevel := LogLevel() if logLevel == "" { return } @@ -37,21 +38,14 @@ func LogOutput() (logOutput io.Writer, err error) { } } - if logLevel == "TRACE" { - // Just pass through logs directly then, without any level filtering at all. - return logOutput, nil - } - - // Otherwise we'll use our level filter, which is a heuristic-based - // best effort thing that is not totally reliable but helps to reduce - // the volume of logs in some cases. - logOutput = &LevelFilter{ + // This was the default since the beginning + logOutput = &logutils.LevelFilter{ Levels: ValidLevels, - MinLevel: LogLevel(logLevel), + MinLevel: logutils.LogLevel(logLevel), Writer: logOutput, } - return logOutput, nil + return } // SetOutput checks for a log destination with LogOutput, and calls @@ -70,8 +64,8 @@ func SetOutput() { log.SetOutput(out) } -// CurrentLogLevel returns the current log level string based the environment vars -func CurrentLogLevel() string { +// LogLevel returns the current log level string based the environment vars +func LogLevel() string { envLevel := os.Getenv(EnvLog) if envLevel == "" { return "" @@ -85,16 +79,13 @@ func CurrentLogLevel() string { log.Printf("[WARN] Invalid log level: %q. Defaulting to level: TRACE. Valid levels are: %+v", envLevel, ValidLevels) } - if logLevel != "TRACE" { - log.Printf("[WARN] Log levels other than TRACE are currently unreliable, and are supported only for backward compatibility.\n Use TF_LOG=TRACE to see Terraform's internal logs.\n ----") - } return logLevel } // IsDebugOrHigher returns whether or not the current log level is debug or trace func IsDebugOrHigher() bool { - level := string(CurrentLogLevel()) + level := string(LogLevel()) return level == "DEBUG" || level == "TRACE" } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go index 5b74edd069..561873dea1 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/helper/resource/testing_import_state.go @@ -16,7 +16,7 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/terraform" ) -// testStepImportState runs an import state test step +// testStepImportState runs an imort state test step func testStepImportState( opts terraform.ContextOpts, state *terraform.State, @@ -96,6 +96,7 @@ func testStepImportState( if err != nil { return nil, err } + // Go through the new state and verify if step.ImportStateCheck != nil { var states []*terraform.InstanceState @@ -137,7 +138,7 @@ func testStepImportState( // this shouldn't happen in any reasonable case. var rsrcSchema *schema.Resource if providerAddr, diags := addrs.ParseAbsProviderConfigStr(r.Provider); !diags.HasErrors() { - providerType := providerAddr.ProviderConfig.Type.LegacyString() + providerType := providerAddr.ProviderConfig.Type if provider, ok := step.providers[providerType]; ok { if provider, ok := provider.(*schema.Provider); ok { rsrcSchema = provider.ResourcesMap[r.Type] diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go index 79829f969a..d2c046c111 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/input_variable.go @@ -34,7 +34,7 @@ func (m ModuleInstance) InputVariable(name string) AbsInputVariableInstance { func (v AbsInputVariableInstance) String() string { if len(v.Module) == 0 { - return v.Variable.String() + return v.String() } return fmt.Sprintf("%s.%s", v.Module.String(), v.Variable.String()) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go index 7b1f4e4e12..bb0901a26c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/module_instance.go @@ -57,7 +57,7 @@ func ParseModuleInstance(traversal hcl.Traversal) (ModuleInstance, tfdiags.Diagn // If a reference string is coming from a source that should be identified in // error messages then the caller should instead parse it directly using a // suitable function from the HCL API and pass the traversal itself to -// ParseModuleInstance. +// ParseProviderConfigCompact. // // Error diagnostics are returned if either the parsing fails or the analysis // of the traversal fails. There is no way for the caller to distinguish the diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go index 108a45059f..103f8a28c3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/addrs/resource.go @@ -61,9 +61,8 @@ func (r Resource) DefaultProviderConfig() ProviderConfig { if under := strings.Index(typeName, "_"); under != -1 { typeName = typeName[:under] } - return ProviderConfig{ - Type: NewLegacyProvider(typeName), + Type: typeName, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go index 70c86bdfea..0a2aa7d02e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/diff.go @@ -70,7 +70,22 @@ func ResourceChange( } buf.WriteString(color.Color("[reset]\n")) - buf.WriteString(color.Color(DiffActionSymbol(change.Action)) + " ") + switch change.Action { + case plans.Create: + buf.WriteString(color.Color("[green] +[reset] ")) + case plans.Read: + buf.WriteString(color.Color("[cyan] <=[reset] ")) + case plans.Update: + buf.WriteString(color.Color("[yellow] ~[reset] ")) + case plans.DeleteThenCreate: + buf.WriteString(color.Color("[red]-[reset]/[green]+[reset] ")) + case plans.CreateThenDelete: + buf.WriteString(color.Color("[green]+[reset]/[red]-[reset] ")) + case plans.Delete: + buf.WriteString(color.Color("[red] -[reset] ")) + default: + buf.WriteString(color.Color("??? ")) + } switch addr.Resource.Resource.Mode { case addrs.ManagedResourceMode: @@ -487,7 +502,7 @@ func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, in ty, err := ctyjson.ImpliedType(src) // check for the special case of "null", which decodes to nil, // and just allow it to be printed out directly - if err == nil && !ty.IsPrimitiveType() && strings.TrimSpace(val.AsString()) != "null" { + if err == nil && !ty.IsPrimitiveType() && val.AsString() != "null" { jv, err := ctyjson.Unmarshal(src, ty) if err == nil { p.buf.WriteString("jsonencode(") @@ -505,21 +520,6 @@ func (p *blockBodyDiffPrinter) writeValue(val cty.Value, action plans.Action, in } } } - - if strings.Contains(val.AsString(), "\n") { - // It's a multi-line string, so we want to use the multi-line - // rendering so it'll be readable. Rather than re-implement - // that here, we'll just re-use the multi-line string diff - // printer with no changes, which ends up producing the - // result we want here. - // The path argument is nil because we don't track path - // information into strings and we know that a string can't - // have any indices or attributes that might need to be marked - // as (requires replacement), which is what that argument is for. - p.writeValueDiff(val, val, indent, nil) - break - } - fmt.Fprintf(p.buf, "%q", val.AsString()) case cty.Bool: if val.True() { @@ -1014,9 +1014,8 @@ func (p *blockBodyDiffPrinter) writeActionSymbol(action plans.Action) { } func (p *blockBodyDiffPrinter) pathForcesNewResource(path cty.Path) bool { - if !p.action.IsReplace() || p.requiredReplace.Empty() { - // "requiredReplace" only applies when the instance is being replaced, - // and we should only inspect that set if it is not empty + if !p.action.IsReplace() { + // "requiredReplace" only applies when the instance is being replaced return false } return p.requiredReplace.Has(path) @@ -1072,8 +1071,8 @@ func ctySequenceDiff(old, new []cty.Value) []*plans.Change { var oldI, newI, lcsI int for oldI < len(old) || newI < len(new) || lcsI < len(lcs) { for oldI < len(old) && (lcsI >= len(lcs) || !old[oldI].RawEquals(lcs[lcsI])) { - isObjectDiff := old[oldI].Type().IsObjectType() && newI < len(new) && new[newI].Type().IsObjectType() && (lcsI >= len(lcs) || !new[newI].RawEquals(lcs[lcsI])) - if isObjectDiff { + isObjectDiff := old[oldI].Type().IsObjectType() && (newI >= len(new) || new[newI].Type().IsObjectType()) + if isObjectDiff && newI < len(new) { ret = append(ret, &plans.Change{ Action: plans.Update, Before: old[oldI], @@ -1191,26 +1190,3 @@ func ctyNullBlockSetAsEmpty(in cty.Value) cty.Value { // sets, so our result here is always a set. return cty.SetValEmpty(in.Type().ElementType()) } - -// DiffActionSymbol returns a string that, once passed through a -// colorstring.Colorize, will produce a result that can be written -// to a terminal to produce a symbol made of three printable -// characters, possibly interspersed with VT100 color codes. -func DiffActionSymbol(action plans.Action) string { - switch action { - case plans.DeleteThenCreate: - return "[red]-[reset]/[green]+[reset]" - case plans.CreateThenDelete: - return "[green]+[reset]/[red]-[reset]" - case plans.Create: - return " [green]+[reset]" - case plans.Delete: - return " [red]-[reset]" - case plans.Read: - return " [cyan]<=[reset]" - case plans.Update: - return " [yellow]~[reset]" - default: - return " ?" - } -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go index 9566a3dcab..14869ad3ca 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/command/format/state.go @@ -138,7 +138,7 @@ func formatStateModule(p blockBodyDiffPrinter, m *states.Module, schemas *terraf } var schema *configschema.Block - provider := addr.DefaultProviderConfig().Absolute(m.Addr).ProviderConfig.StringCompact() + provider := m.Resources[key].ProviderConfig.ProviderConfig.StringCompact() if _, exists := schemas.Providers[provider]; !exists { // This should never happen in normal use because we should've // loaded all of the schemas and checked things prior to this diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go index b645ac8906..e594ebd40f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/compat_shim.go @@ -69,21 +69,28 @@ func shimTraversalInString(expr hcl.Expression, wantKeyword bool) (hcl.Expressio ) diags = append(diags, tDiags...) - if wantKeyword { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted keywords are deprecated", - Detail: "In this context, keywords are expected literally rather than in quotes. Terraform 0.11 and earlier required quotes, but quoted keywords are now deprecated and will be removed in a future version of Terraform. Remove the quotes surrounding this keyword to silence this warning.", - Subject: &srcRange, - }) - } else { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted references are deprecated", - Detail: "In this context, references are expected literally rather than in quotes. Terraform 0.11 and earlier required quotes, but quoted references are now deprecated and will be removed in a future version of Terraform. Remove the quotes surrounding this reference to silence this warning.", - Subject: &srcRange, - }) - } + // For initial release our deprecation warnings are disabled to allow + // a period where modules can be compatible with both old and new + // conventions. + // FIXME: Re-enable these deprecation warnings in a release prior to + // Terraform 0.13 and then remove the shims altogether for 0.13. + /* + if wantKeyword { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Quoted keywords are deprecated", + Detail: "In this context, keywords are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this keyword to silence this warning.", + Subject: &srcRange, + }) + } else { + diags = append(diags, &hcl.Diagnostic{ + Severity: hcl.DiagWarning, + Summary: "Quoted references are deprecated", + Detail: "In this context, references are expected literally rather than in quotes. Previous versions of Terraform required quotes, but that usage is now deprecated. Remove the quotes surrounding this reference to silence this warning.", + Subject: &srcRange, + }) + } + */ return &hclsyntax.ScopeTraversalExpr{ Traversal: traversal, @@ -107,58 +114,3 @@ func shimIsIgnoreChangesStar(expr hcl.Expression) bool { } return val.AsString() == "*" } - -// warnForDeprecatedInterpolations returns warning diagnostics if the given -// body can be proven to contain attributes whose expressions are native -// syntax expressions consisting entirely of a single template interpolation, -// which is a deprecated way to include a non-literal value in configuration. -// -// This is a best-effort sort of thing which relies on the physical HCL native -// syntax AST, so it might not catch everything. The main goal is to catch the -// "obvious" cases in order to help spread awareness that this old form is -// deprecated, when folks copy it from older examples they've found on the -// internet that were written for Terraform 0.11 or earlier. -func warnForDeprecatedInterpolationsInBody(body hcl.Body) hcl.Diagnostics { - var diags hcl.Diagnostics - - nativeBody, ok := body.(*hclsyntax.Body) - if !ok { - // If it's not native syntax then we've nothing to do here. - return diags - } - - for _, attr := range nativeBody.Attributes { - moreDiags := warnForDeprecatedInterpolationsInExpr(attr.Expr) - diags = append(diags, moreDiags...) - } - - for _, block := range nativeBody.Blocks { - // We'll also go hunting in nested blocks - moreDiags := warnForDeprecatedInterpolationsInBody(block.Body) - diags = append(diags, moreDiags...) - } - - return diags -} - -func warnForDeprecatedInterpolationsInExpr(expr hcl.Expression) hcl.Diagnostics { - var diags hcl.Diagnostics - - if _, ok := expr.(*hclsyntax.TemplateWrapExpr); !ok { - // We're only interested in TemplateWrapExpr, because that's how - // the HCL native syntax parser represents the case of a template - // that consists entirely of a single interpolation expression, which - // is therefore subject to the special case of passing through the - // inner value without conversion to string. - return diags - } - - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Interpolation-only expressions are deprecated", - Detail: "Terraform 0.11 and earlier required all non-constant expressions to be provided via interpolation syntax, but this pattern is now deprecated. To silence this warning, remove the \"${ sequence from the start and the }\" sequence from the end of this expression, leaving just the inner expression.\n\nTemplate interpolation syntax is still used to construct strings from expressions when the template includes multiple interpolation sequences or a mixture of literal strings and interpolations. This deprecation applies only to templates that consist entirely of a single interpolation sequence.", - Subject: expr.Range().Ptr(), - }) - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go index 840a7aa975..ebbeb3b629 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/configload/copy_dir.go @@ -4,6 +4,7 @@ import ( "io" "os" "path/filepath" + "strings" ) // copyDir copies the src directory contents into dst. Both directories @@ -23,6 +24,15 @@ func copyDir(dst, src string) error { return nil } + if strings.HasPrefix(filepath.Base(path), ".") { + // Skip any dot files + if info.IsDir() { + return filepath.SkipDir + } else { + return nil + } + } + // The "path" has the src prefixed to it. We need to join our // destination with the path without the src on it. dstPath := filepath.Join(dst, path[len(src):]) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go index 3a5e19e807..6fb82acfbd 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/module_merge.go @@ -35,7 +35,7 @@ func (p *Provider) merge(op *Provider) hcl.Diagnostics { return diags } -func mergeProviderVersionConstraints(recv map[string]ProviderRequirements, ovrd []*RequiredProvider) { +func mergeProviderVersionConstraints(recv map[string][]VersionConstraint, ovrd []*ProviderRequirement) { // Any provider name that's mentioned in the override gets nilled out in // our map so that we'll rebuild it below. Any provider not mentioned is // left unchanged. @@ -43,8 +43,7 @@ func mergeProviderVersionConstraints(recv map[string]ProviderRequirements, ovrd delete(recv, reqd.Name) } for _, reqd := range ovrd { - fqn := addrs.NewLegacyProvider(reqd.Name) - recv[reqd.Name] = ProviderRequirements{Type: fqn, VersionConstraints: []VersionConstraint{reqd.Requirement}} + recv[reqd.Name] = append(recv[reqd.Name], reqd.Requirement) } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go index 6b471bc7f9..8c8398e0b7 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/named_values.go @@ -2,7 +2,6 @@ package configs import ( "fmt" - "unicode" "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/ext/typeexpr" @@ -13,7 +12,7 @@ import ( ) // A consistent detail message for all "not a valid identifier" diagnostics. -const badIdentifierDetail = "A name must start with a letter or underscore and may contain only letters, digits, underscores, and dashes." +const badIdentifierDetail = "A name must start with a letter and may contain only letters, digits, underscores, and dashes." // Variable represents a "variable" block in a module or file. type Variable struct { @@ -22,7 +21,6 @@ type Variable struct { Default cty.Value Type cty.Type ParsingMode VariableParsingMode - Validations []*VariableValidation DescriptionSet bool @@ -119,21 +117,6 @@ func decodeVariableBlock(block *hcl.Block, override bool) (*Variable, hcl.Diagno v.Default = val } - for _, block := range content.Blocks { - switch block.Type { - - case "validation": - vv, moreDiags := decodeVariableValidationBlock(v.Name, block, override) - diags = append(diags, moreDiags...) - v.Validations = append(v.Validations, vv) - - default: - // The above cases should be exhaustive for all block types - // defined in variableBlockSchema - panic(fmt.Sprintf("unhandled block type %q", block.Type)) - } - } - return v, diags } @@ -153,28 +136,10 @@ func decodeVariableType(expr hcl.Expression) (cty.Type, VariableParsingMode, hcl str := val.AsString() switch str { case "string": - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted type constraints are deprecated", - Detail: "Terraform 0.11 and earlier required type constraints to be given in quotes, but that form is now deprecated and will be removed in a future version of Terraform. To silence this warning, remove the quotes around \"string\".", - Subject: expr.Range().Ptr(), - }) return cty.String, VariableParseLiteral, diags case "list": - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted type constraints are deprecated", - Detail: "Terraform 0.11 and earlier required type constraints to be given in quotes, but that form is now deprecated and will be removed in a future version of Terraform. To silence this warning, remove the quotes around \"list\" and write list(string) instead to explicitly indicate that the list elements are strings.", - Subject: expr.Range().Ptr(), - }) return cty.List(cty.DynamicPseudoType), VariableParseHCL, diags case "map": - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "Quoted type constraints are deprecated", - Detail: "Terraform 0.11 and earlier required type constraints to be given in quotes, but that form is now deprecated and will be removed in a future version of Terraform. To silence this warning, remove the quotes around \"map\" and write map(string) instead to explicitly indicate that the map elements are strings.", - Subject: expr.Range().Ptr(), - }) return cty.Map(cty.DynamicPseudoType), VariableParseHCL, diags default: return cty.DynamicPseudoType, VariableParseHCL, hcl.Diagnostics{{ @@ -212,12 +177,6 @@ func decodeVariableType(expr hcl.Expression) (cty.Type, VariableParsingMode, hcl } } -// Required returns true if this variable is required to be set by the caller, -// or false if there is a default value that will be used when it isn't set. -func (v *Variable) Required() bool { - return v.Default == cty.NilVal -} - // VariableParsingMode defines how values of a particular variable given by // text-only mechanisms (command line arguments and environment variables) // should be parsed to produce the final value. @@ -265,157 +224,6 @@ func (m VariableParsingMode) Parse(name, value string) (cty.Value, hcl.Diagnosti } } -// VariableValidation represents a configuration-defined validation rule -// for a particular input variable, given as a "validation" block inside -// a "variable" block. -type VariableValidation struct { - // Condition is an expression that refers to the variable being tested - // and contains no other references. The expression must return true - // to indicate that the value is valid or false to indicate that it is - // invalid. If the expression produces an error, that's considered a bug - // in the module defining the validation rule, not an error in the caller. - Condition hcl.Expression - - // ErrorMessage is one or more full sentences, which would need to be in - // English for consistency with the rest of the error message output but - // can in practice be in any language as long as it ends with a period. - // The message should describe what is required for the condition to return - // true in a way that would make sense to a caller of the module. - ErrorMessage string - - DeclRange hcl.Range -} - -func decodeVariableValidationBlock(varName string, block *hcl.Block, override bool) (*VariableValidation, hcl.Diagnostics) { - var diags hcl.Diagnostics - vv := &VariableValidation{ - DeclRange: block.DefRange, - } - - if override { - // For now we'll just forbid overriding validation blocks, to simplify - // the initial design. If we can find a clear use-case for overriding - // validations in override files and there's a way to define it that - // isn't confusing then we could relax this. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Can't override variable validation rules", - Detail: "Variable \"validation\" blocks cannot be used in override files.", - Subject: vv.DeclRange.Ptr(), - }) - return vv, diags - } - - content, moreDiags := block.Body.Content(variableValidationBlockSchema) - diags = append(diags, moreDiags...) - - if attr, exists := content.Attributes["condition"]; exists { - vv.Condition = attr.Expr - - // The validation condition can only refer to the variable itself, - // to ensure that the variable declaration can't create additional - // edges in the dependency graph. - goodRefs := 0 - for _, traversal := range vv.Condition.Variables() { - ref, moreDiags := addrs.ParseRef(traversal) - if !moreDiags.HasErrors() { - if addr, ok := ref.Subject.(addrs.InputVariable); ok { - if addr.Name == varName { - goodRefs++ - continue // Reference is valid - } - } - } - // If we fall out here then the reference is invalid. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid reference in variable validation", - Detail: fmt.Sprintf("The condition for variable %q can only refer to the variable itself, using var.%s.", varName, varName), - Subject: traversal.SourceRange().Ptr(), - }) - } - if goodRefs < 1 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid variable validation condition", - Detail: fmt.Sprintf("The condition for variable %q must refer to var.%s in order to test incoming values.", varName, varName), - Subject: attr.Expr.Range().Ptr(), - }) - } - } - - if attr, exists := content.Attributes["error_message"]; exists { - moreDiags := gohcl.DecodeExpression(attr.Expr, nil, &vv.ErrorMessage) - diags = append(diags, moreDiags...) - if !moreDiags.HasErrors() { - const errSummary = "Invalid validation error message" - switch { - case vv.ErrorMessage == "": - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: errSummary, - Detail: "An empty string is not a valid nor useful error message.", - Subject: attr.Expr.Range().Ptr(), - }) - case !looksLikeSentences(vv.ErrorMessage): - // Because we're going to include this string verbatim as part - // of a bigger error message written in our usual style in - // English, we'll require the given error message to conform - // to that. We might relax this in future if e.g. we start - // presenting these error messages in a different way, or if - // Terraform starts supporting producing error messages in - // other human languages, etc. - // For pragmatism we also allow sentences ending with - // exclamation points, but we don't mention it explicitly here - // because that's not really consistent with the Terraform UI - // writing style. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: errSummary, - Detail: "Validation error message must be at least one full English sentence starting with an uppercase letter and ending with a period or question mark.", - Subject: attr.Expr.Range().Ptr(), - }) - } - } - } - - return vv, diags -} - -// looksLikeSentence is a simple heuristic that encourages writing error -// messages that will be presentable when included as part of a larger -// Terraform error diagnostic whose other text is written in the Terraform -// UI writing style. -// -// This is intentionally not a very strong validation since we're assuming -// that module authors want to write good messages and might just need a nudge -// about Terraform's specific style, rather than that they are going to try -// to work around these rules to write a lower-quality message. -func looksLikeSentences(s string) bool { - if len(s) < 1 { - return false - } - runes := []rune(s) // HCL guarantees that all strings are valid UTF-8 - first := runes[0] - last := runes[len(s)-1] - - // If the first rune is a letter then it must be an uppercase letter. - // (This will only see the first rune in a multi-rune combining sequence, - // but the first rune is generally the letter if any are, and if not then - // we'll just ignore it because we're primarily expecting English messages - // right now anyway, for consistency with all of Terraform's other output.) - if unicode.IsLetter(first) && !unicode.IsUpper(first) { - return false - } - - // The string must be at least one full sentence, which implies having - // sentence-ending punctuation. - // (This assumes that if a sentence ends with quotes then the period - // will be outside the quotes, which is consistent with Terraform's UI - // writing style.) - return last == '.' || last == '?' || last == '!' -} - // Output represents an "output" block in a module or file. type Output struct { Name string @@ -525,24 +333,6 @@ var variableBlockSchema = &hcl.BodySchema{ Name: "type", }, }, - Blocks: []hcl.BlockHeaderSchema{ - { - Type: "validation", - }, - }, -} - -var variableValidationBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "condition", - Required: true, - }, - { - Name: "error_message", - Required: true, - }, - }, } var outputBlockSchema = &hcl.BodySchema{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go index e8f94721d7..d4cbc945c3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config.go @@ -42,12 +42,6 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost file.CoreVersionConstraints, reqDiags = sniffCoreVersionRequirements(body) diags = append(diags, reqDiags...) - // We'll load the experiments first because other decoding logic in the - // loop below might depend on these experiments. - var expDiags hcl.Diagnostics - file.ActiveExperiments, expDiags = sniffActiveExperiments(body) - diags = append(diags, expDiags...) - content, contentDiags := body.Content(configFileSchema) diags = append(diags, contentDiags...) @@ -58,9 +52,8 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost content, contentDiags := block.Body.Content(terraformBlockSchema) diags = append(diags, contentDiags...) - // We ignore the "terraform_version" and "experiments" attributes - // here because sniffCoreVersionRequirements and - // sniffActiveExperiments already dealt with those above. + // We ignore the "terraform_version" attribute here because + // sniffCoreVersionRequirements already dealt with that above. for _, innerBlock := range content.Blocks { switch innerBlock.Type { @@ -75,7 +68,7 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost case "required_providers": reqs, reqsDiags := decodeRequiredProvidersBlock(innerBlock) diags = append(diags, reqsDiags...) - file.RequiredProviders = append(file.RequiredProviders, reqs...) + file.ProviderRequirements = append(file.ProviderRequirements, reqs...) default: // Should never happen because the above cases should be exhaustive @@ -155,7 +148,7 @@ func (p *Parser) loadConfigFile(path string, override bool) (*File, hcl.Diagnost // able to find, but may return no constraints at all if the given body is // so invalid that it cannot be decoded at all. func sniffCoreVersionRequirements(body hcl.Body) ([]VersionConstraint, hcl.Diagnostics) { - rootContent, _, diags := body.PartialContent(configFileTerraformBlockSniffRootSchema) + rootContent, _, diags := body.PartialContent(configFileVersionSniffRootSchema) var constraints []VersionConstraint @@ -220,8 +213,9 @@ var configFileSchema = &hcl.BodySchema{ // a configuration file. var terraformBlockSchema = &hcl.BodySchema{ Attributes: []hcl.AttributeSchema{ - {Name: "required_version"}, - {Name: "experiments"}, + { + Name: "required_version", + }, }, Blocks: []hcl.BlockHeaderSchema{ { @@ -234,9 +228,8 @@ var terraformBlockSchema = &hcl.BodySchema{ }, } -// configFileTerraformBlockSniffRootSchema is a schema for -// sniffCoreVersionRequirements and sniffActiveExperiments. -var configFileTerraformBlockSniffRootSchema = &hcl.BodySchema{ +// configFileVersionSniffRootSchema is a schema for sniffCoreVersionRequirements +var configFileVersionSniffRootSchema = &hcl.BodySchema{ Blocks: []hcl.BlockHeaderSchema{ { Type: "terraform", @@ -252,13 +245,3 @@ var configFileVersionSniffBlockSchema = &hcl.BodySchema{ }, }, } - -// configFileExperimentsSniffBlockSchema is a schema for sniffActiveExperiments, -// to decode a single attribute from inside a "terraform" block. -var configFileExperimentsSniffBlockSchema = &hcl.BodySchema{ - Attributes: []hcl.AttributeSchema{ - { - Name: "experiments", - }, - }, -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go index 2923af93a0..afdd69833f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/parser_config_dir.go @@ -154,9 +154,9 @@ func IsEmptyDir(path string) (bool, error) { } p := NewParser(nil) - fs, os, diags := p.dirFiles(path) - if diags.HasErrors() { - return false, diags + fs, os, err := p.dirFiles(path) + if err != nil { + return false, err } return len(fs) == 0 && len(os) == 0, nil diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go index 6f380860a8..47b6567918 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/provisioner.go @@ -50,11 +50,6 @@ func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { } } - // destroy provisioners can only refer to self - if pv.When == ProvisionerWhenDestroy { - diags = append(diags, onlySelfRefs(config)...) - } - if attr, exists := content.Attributes["on_failure"]; exists { expr, shimDiags := shimTraversalInString(attr.Expr, true) diags = append(diags, shimDiags...) @@ -90,11 +85,8 @@ func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { } seenConnection = block - // destroy provisioners can only refer to self - if pv.When == ProvisionerWhenDestroy { - diags = append(diags, onlySelfRefs(block.Body)...) - } - + //conn, connDiags := decodeConnectionBlock(block) + //diags = append(diags, connDiags...) pv.Connection = &Connection{ Config: block.Body, DeclRange: block.DefRange, @@ -115,52 +107,6 @@ func decodeProvisionerBlock(block *hcl.Block) (*Provisioner, hcl.Diagnostics) { return pv, diags } -func onlySelfRefs(body hcl.Body) hcl.Diagnostics { - var diags hcl.Diagnostics - - // Provisioners currently do not use any blocks in their configuration. - // Blocks are likely to remain solely for meta parameters, but in the case - // that blocks are supported for provisioners, we will want to extend this - // to find variables in nested blocks. - attrs, _ := body.JustAttributes() - for _, attr := range attrs { - for _, v := range attr.Expr.Variables() { - valid := false - switch v.RootName() { - case "self", "path", "terraform": - valid = true - case "count": - // count must use "index" - if len(v) == 2 { - if t, ok := v[1].(hcl.TraverseAttr); ok && t.Name == "index" { - valid = true - } - } - - case "each": - if len(v) == 2 { - if t, ok := v[1].(hcl.TraverseAttr); ok && t.Name == "key" { - valid = true - } - } - } - - if !valid { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: "External references from destroy provisioners are deprecated", - Detail: "Destroy-time provisioners and their connection configurations may only " + - "reference attributes of the related resource, via 'self', 'count.index', " + - "or 'each.key'.\n\nReferences to other resources during the destroy phase " + - "can cause dependency cycles and interact poorly with create_before_destroy.", - Subject: attr.Expr.Range().Ptr(), - }) - } - } - } - return diags -} - // Connection represents a "connection" block when used within either a // "resource" or "provisioner" block in a module or file. type Connection struct { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go index 323ce3627c..cd9991a389 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/configs/resource.go @@ -70,13 +70,12 @@ func (r *Resource) ProviderConfigAddr() addrs.ProviderConfig { } return addrs.ProviderConfig{ - Type: addrs.NewLegacyProvider(r.ProviderConfigRef.Name), + Type: r.ProviderConfigRef.Name, Alias: r.ProviderConfigRef.Alias, } } func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { - var diags hcl.Diagnostics r := &Resource{ Mode: addrs.ManagedResourceMode, Type: block.Labels[0], @@ -86,15 +85,7 @@ func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { Managed: &ManagedResource{}, } - // Produce deprecation messages for any pre-0.12-style - // single-interpolation-only expressions. We do this up front here because - // then we can also catch instances inside special blocks like "connection", - // before PartialContent extracts them. - moreDiags := warnForDeprecatedInterpolationsInBody(block.Body) - diags = append(diags, moreDiags...) - - content, remain, moreDiags := block.Body.PartialContent(resourceBlockSchema) - diags = append(diags, moreDiags...) + content, remain, diags := block.Body.PartialContent(resourceBlockSchema) r.Config = remain if !hclsyntax.ValidIdentifier(r.Type) { @@ -273,17 +264,6 @@ func decodeResourceBlock(block *hcl.Block) (*Resource, hcl.Diagnostics) { } } - // Now we can validate the connection block references if there are any destroy provisioners. - // TODO: should we eliminate standalone connection blocks? - if r.Managed.Connection != nil { - for _, p := range r.Managed.Provisioners { - if p.When == ProvisionerWhenDestroy { - diags = append(diags, onlySelfRefs(r.Managed.Connection.Config)...) - break - } - } - } - return r, diags } @@ -447,7 +427,7 @@ func decodeProviderConfigRef(expr hcl.Expression, argName string) (*ProviderConf // location information and keeping just the addressing information. func (r *ProviderConfigRef) Addr() addrs.ProviderConfig { return addrs.ProviderConfig{ - Type: addrs.NewLegacyProvider(r.Name), + Type: r.Name, Alias: r.Alias, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go index 95f3f926dd..5ddf8ef34c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/dag/walk.go @@ -15,7 +15,7 @@ import ( // been walked. If two vertices can be walked at the same time, they will be. // // Update can be called to update the graph. This can be called even during -// a walk, changing vertices/edges mid-walk. This should be done carefully. +// a walk, cahnging vertices/edges mid-walk. This should be done carefully. // If a vertex is removed but has already been executed, the result of that // execution (any error) is still returned by Wait. Changing or re-adding // a vertex that has already executed has no effect. Changing edges of diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go index 2ea4168757..e6898457b9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/collection.go @@ -940,7 +940,7 @@ var ReverseFunc = function.New(&function.Spec{ }, }) -// SetProductFunc calculates the Cartesian product of two or more sets or +// SetProductFunc calculates the cartesian product of two or more sets or // sequences. If the arguments are all lists then the result is a list of tuples, // preserving the ordering of all of the input lists. Otherwise the result is a // set of tuples. @@ -1179,6 +1179,7 @@ func sliceIndexes(args []cty.Value) (int, int, bool, error) { return startIndex, endIndex, startKnown && endKnown, nil } +// TransposeFunc contructs a function that takes a map of lists of strings and // TransposeFunc constructs a function that takes a map of lists of strings and // swaps the keys and values to produce a new map of lists of strings. var TransposeFunc = function.New(&function.Spec{ @@ -1225,10 +1226,6 @@ var TransposeFunc = function.New(&function.Spec{ outputMap[outKey] = cty.ListVal(values) } - if len(outputMap) == 0 { - return cty.MapValEmpty(cty.List(cty.String)), nil - } - return cty.MapVal(outputMap), nil }, }) @@ -1494,7 +1491,7 @@ func Reverse(list cty.Value) (cty.Value, error) { return ReverseFunc.Call([]cty.Value{list}) } -// SetProduct computes the Cartesian product of sets or sequences. +// SetProduct computes the cartesian product of sets or sequences. func SetProduct(sets ...cty.Value) (cty.Value, error) { return SetProductFunc.Call(sets) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go index 2e66be4512..c9ddf19e36 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/lang/funcs/string.go @@ -71,7 +71,7 @@ var SortFunc = function.New(&function.Spec{ if !listVal.IsWhollyKnown() { // If some of the element values aren't known yet then we - // can't yet predict the order of the result. + // can't yet preduct the order of the result. return cty.UnknownVal(retType), nil } if listVal.LengthInt() == 0 { // Easy path @@ -123,7 +123,7 @@ var SplitFunc = function.New(&function.Spec{ }, }) -// ChompFunc constructs a function that removes newline characters at the end of a string. +// ChompFunc constructions a function that removes newline characters at the end of a string. var ChompFunc = function.New(&function.Spec{ Params: []function.Parameter{ { @@ -138,7 +138,7 @@ var ChompFunc = function.New(&function.Spec{ }, }) -// IndentFunc constructs a function that adds a given number of spaces to the +// IndentFunc constructions a function that adds a given number of spaces to the // beginnings of all but the first line in a given multi-line string. var IndentFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -163,7 +163,7 @@ var IndentFunc = function.New(&function.Spec{ }, }) -// ReplaceFunc constructs a function that searches a given string for another +// ReplaceFunc constructions a function that searches a given string for another // given substring, and replaces each occurence with a given replacement string. var ReplaceFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -201,7 +201,7 @@ var ReplaceFunc = function.New(&function.Spec{ }, }) -// TitleFunc constructs a function that converts the first letter of each word +// TitleFunc constructions a function that converts the first letter of each word // in the given string to uppercase. var TitleFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -216,7 +216,7 @@ var TitleFunc = function.New(&function.Spec{ }, }) -// TrimSpaceFunc constructs a function that removes any space characters from +// TrimSpaceFunc constructions a function that removes any space characters from // the start and end of the given string. var TrimSpaceFunc = function.New(&function.Spec{ Params: []function.Parameter{ @@ -231,69 +231,6 @@ var TrimSpaceFunc = function.New(&function.Spec{ }, }) -// TrimFunc constructs a function that removes the specified characters from -// the start and end of the given string. -var TrimFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - { - Name: "cutset", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - str := args[0].AsString() - cutset := args[1].AsString() - return cty.StringVal(strings.Trim(str, cutset)), nil - }, -}) - -// TrimPrefixFunc constructs a function that removes the specified characters from -// the start the given string. -var TrimPrefixFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - { - Name: "prefix", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - str := args[0].AsString() - prefix := args[1].AsString() - return cty.StringVal(strings.TrimPrefix(str, prefix)), nil - }, -}) - -// TrimSuffixFunc constructs a function that removes the specified characters from -// the end of the given string. -var TrimSuffixFunc = function.New(&function.Spec{ - Params: []function.Parameter{ - { - Name: "str", - Type: cty.String, - }, - { - Name: "suffix", - Type: cty.String, - }, - }, - Type: function.StaticReturnType(cty.String), - Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { - str := args[0].AsString() - cutset := args[1].AsString() - return cty.StringVal(strings.TrimSuffix(str, cutset)), nil - }, -}) - // Join concatenates together the string elements of one or more lists with a // given separator. func Join(sep cty.Value, lists ...cty.Value) (cty.Value, error) { @@ -341,18 +278,3 @@ func Title(str cty.Value) (cty.Value, error) { func TrimSpace(str cty.Value) (cty.Value, error) { return TrimSpaceFunc.Call([]cty.Value{str}) } - -// Trim removes the specified characters from the start and end of the given string. -func Trim(str, cutset cty.Value) (cty.Value, error) { - return TrimFunc.Call([]cty.Value{str, cutset}) -} - -// TrimPrefix removes the specified prefix from the start of the given string. -func TrimPrefix(str, prefix cty.Value) (cty.Value, error) { - return TrimPrefixFunc.Call([]cty.Value{str, prefix}) -} - -// TrimSuffix removes the specified suffix from the end of the given string. -func TrimSuffix(str, suffix cty.Value) (cty.Value, error) { - return TrimSuffixFunc.Call([]cty.Value{str, suffix}) -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go index 863c504558..2d45c8520e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/modsdir/manifest.go @@ -81,11 +81,6 @@ func ReadManifestSnapshot(r io.Reader) (Manifest, error) { return nil, fmt.Errorf("invalid version %q for %s: %s", record.VersionStr, record.Key, err) } } - - // Ensure Windows is using the proper modules path format after - // reading the modules manifest Dir records - record.Dir = filepath.FromSlash(record.Dir) - if _, exists := new[record.Key]; exists { // This should never happen in any valid file, so we'll catch it // and report it to avoid confusing/undefined behavior if the @@ -120,10 +115,6 @@ func (m Manifest) WriteSnapshot(w io.Writer) error { } else { record.VersionStr = "" } - - // Ensure Dir is written in a format that can be read by Linux and - // Windows nodes for remote and apply compatibility - record.Dir = filepath.ToSlash(record.Dir) write.Records = append(write.Records, record) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go index 74a5342c2e..0f48f2447d 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/providers/addressed_types.go @@ -14,7 +14,7 @@ func AddressedTypes(providerAddrs []addrs.ProviderConfig) []string { } m := map[string]struct{}{} for _, addr := range providerAddrs { - m[addr.Type.LegacyString()] = struct{}{} + m[addr.Type] = struct{}{} } names := make([]string, 0, len(m)) @@ -34,7 +34,7 @@ func AddressedTypesAbs(providerAddrs []addrs.AbsProviderConfig) []string { } m := map[string]struct{}{} for _, addr := range providerAddrs { - m[addr.ProviderConfig.Type.LegacyString()] = struct{}{} + m[addr.ProviderConfig.Type] = struct{}{} } names := make([]string, 0, len(m)) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go index 87312f929b..3bb717d332 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object.go @@ -29,17 +29,12 @@ type ResourceInstanceObject struct { // it was updated. Status ObjectStatus - // Dependencies is a set of absolute address to other resources this - // instance dependeded on when it was applied. This is used to construct - // the dependency relationships for an object whose configuration is no - // longer available, such as if it has been removed from configuration - // altogether, or is now deposed. - Dependencies []addrs.AbsResource - - // DependsOn corresponds to the deprecated `depends_on` field in the state. - // This field contained the configuration `depends_on` values, and some of - // the references from within a single module. - DependsOn []addrs.Referenceable + // Dependencies is a set of other addresses in the same module which + // this instance depended on when the given attributes were evaluated. + // This is used to construct the dependency relationships for an object + // whose configuration is no longer available, such as if it has been + // removed from configuration altogether, or is now deposed. + Dependencies []addrs.Referenceable } // ObjectStatus represents the status of a RemoteObject. diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go index 99c0ec29e3..728ad80d12 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/instance_object_src.go @@ -53,9 +53,7 @@ type ResourceInstanceObjectSrc struct { // ResourceInstanceObject. Private []byte Status ObjectStatus - Dependencies []addrs.AbsResource - // deprecated - DependsOn []addrs.Referenceable + Dependencies []addrs.Referenceable } // Decode unmarshals the raw representation of the object attributes. Pass the @@ -88,7 +86,6 @@ func (os *ResourceInstanceObjectSrc) Decode(ty cty.Type) (*ResourceInstanceObjec Value: val, Status: os.Status, Dependencies: os.Dependencies, - DependsOn: os.DependsOn, Private: os.Private, }, nil } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go index 8c4c18a453..6b74cbfa6b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/module.go @@ -76,7 +76,7 @@ func (ms *Module) RemoveResource(addr addrs.Resource) { } // SetResourceInstanceCurrent saves the given instance object as the current -// generation of the resource instance with the given address, simultaneously +// generation of the resource instance with the given address, simulataneously // updating the recorded provider configuration address, dependencies, and // resource EachMode. // @@ -88,58 +88,23 @@ func (ms *Module) RemoveResource(addr addrs.Resource) { // are updated for all other instances of the same resource as a side-effect of // this call. func (ms *Module) SetResourceInstanceCurrent(addr addrs.ResourceInstance, obj *ResourceInstanceObjectSrc, provider addrs.AbsProviderConfig) { + ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) + rs := ms.Resource(addr.Resource) - // if the resource is nil and the object is nil, don't do anything! - // you'll probably just cause issues - if obj == nil && rs == nil { - return - } - if obj == nil && rs != nil { - // does the resource have any other objects? - // if not then delete the whole resource - // When deleting the resource, ensure that its EachMode is NoEach, - // as a resource with EachList or EachMap can have 0 instances and be valid - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - delete(ms.Resources, addr.Resource.String()) - return - } - // check for an existing resource, now that we've ensured that rs.Instances is more than 0/not nil - is := rs.Instance(addr.Key) - if is == nil { - // if there is no instance on the resource with this address and obj is nil, return and change nothing - return - } - // if we have an instance, update the current - is.Current = obj - if !is.HasObjects() { - // If we have no objects at all then we'll clean up. - delete(rs.Instances, addr.Key) - // Delete the resource if it has no instances, but only if NoEach - if rs.EachMode == NoEach && len(rs.Instances) == 0 { - delete(ms.Resources, addr.Resource.String()) - return - } - } - // Nothing more to do here, so return! - return - } - if rs == nil && obj != nil { - // We don't have have a resource so make one, which is a side effect of setResourceMeta - ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) - // now we have a resource! so update the rs value to point to it - rs = ms.Resource(addr.Resource) + is := rs.EnsureInstance(addr.Key) + + is.Current = obj + + if !is.HasObjects() { + // If we have no objects at all then we'll clean up. + delete(rs.Instances, addr.Key) } - // Get our instance from the resource; it could be there or not at this point - is := rs.Instance(addr.Key) - if is == nil { - // if we don't have a resource, create one and add to the instances - is = rs.CreateInstance(addr.Key) - // update the resource meta because we have a new instance, so EachMode may have changed - ms.SetResourceMeta(addr.Resource, eachModeForInstanceKey(addr.Key), provider) + if rs.EachMode == NoEach && len(rs.Instances) == 0 { + // Also clean up if we only expect to have one instance anyway + // and there are none. We leave the resource behind if an each mode + // is active because an empty list or map of instances is a valid state. + delete(ms.Resources, addr.Resource.String()) } - // Update the resource's ProviderConfig, in case the provider has updated - rs.ProviderConfig = provider - is.Current = obj } // SetResourceInstanceDeposed saves the given instance object as a deposed diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go index 8f75040d4d..32ea638acd 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/resource.go @@ -39,13 +39,6 @@ func (rs *Resource) Instance(key addrs.InstanceKey) *ResourceInstance { return rs.Instances[key] } -// CreateInstance creates an instance and adds it to the resource -func (rs *Resource) CreateInstance(key addrs.InstanceKey) *ResourceInstance { - is := NewResourceInstance() - rs.Instances[key] = is - return is -} - // EnsureInstance returns the state for the instance with the given key, // creating a new empty state for it if one doesn't already exist. // diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go index 672eb393a9..6266aca79d 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/state_deepcopy.go @@ -153,17 +153,8 @@ func (obj *ResourceInstanceObjectSrc) DeepCopy() *ResourceInstanceObjectSrc { // Some addrs.Referencable implementations are technically mutable, but // we treat them as immutable by convention and so we don't deep-copy here. - var dependencies []addrs.AbsResource - if obj.Dependencies != nil { - dependencies = make([]addrs.AbsResource, len(obj.Dependencies)) - copy(dependencies, obj.Dependencies) - } - - var dependsOn []addrs.Referenceable - if obj.DependsOn != nil { - dependsOn = make([]addrs.Referenceable, len(obj.DependsOn)) - copy(dependsOn, obj.DependsOn) - } + dependencies := make([]addrs.Referenceable, len(obj.Dependencies)) + copy(dependencies, obj.Dependencies) return &ResourceInstanceObjectSrc{ Status: obj.Status, @@ -172,7 +163,6 @@ func (obj *ResourceInstanceObjectSrc) DeepCopy() *ResourceInstanceObjectSrc { AttrsFlat: attrsFlat, AttrsJSON: attrsJSON, Dependencies: dependencies, - DependsOn: dependsOn, } } @@ -197,9 +187,9 @@ func (obj *ResourceInstanceObject) DeepCopy() *ResourceInstanceObject { // Some addrs.Referenceable implementations are technically mutable, but // we treat them as immutable by convention and so we don't deep-copy here. - var dependencies []addrs.AbsResource + var dependencies []addrs.Referenceable if obj.Dependencies != nil { - dependencies = make([]addrs.AbsResource, len(obj.Dependencies)) + dependencies = make([]addrs.Referenceable, len(obj.Dependencies)) copy(dependencies, obj.Dependencies) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go index 6315de8a69..164b57f827 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/states/statefile/version4.go @@ -181,10 +181,7 @@ func prepareStateV4(sV4 *stateV4) (*File, tfdiags.Diagnostics) { } { - // Allow both the deprecated `depends_on` and new - // `dependencies` to coexist for now so resources can be - // upgraded as they are refreshed. - depsRaw := isV4.DependsOn + depsRaw := isV4.Dependencies deps := make([]addrs.Referenceable, 0, len(depsRaw)) for _, depRaw := range depsRaw { ref, refDiags := addrs.ParseRefStr(depRaw) @@ -205,20 +202,6 @@ func prepareStateV4(sV4 *stateV4) (*File, tfdiags.Diagnostics) { } deps = append(deps, ref.Subject) } - obj.DependsOn = deps - } - - { - depsRaw := isV4.Dependencies - deps := make([]addrs.AbsResource, 0, len(depsRaw)) - for _, depRaw := range depsRaw { - addr, addrDiags := addrs.ParseAbsResourceStr(depRaw) - diags = diags.Append(addrDiags) - if addrDiags.HasErrors() { - continue - } - deps = append(deps, addr) - } obj.Dependencies = deps } @@ -483,11 +466,6 @@ func appendInstanceObjectStateV4(rs *states.Resource, is *states.ResourceInstanc deps[i] = depAddr.String() } - depOn := make([]string, len(obj.DependsOn)) - for i, depAddr := range obj.DependsOn { - depOn[i] = depAddr.String() - } - var rawKey interface{} switch tk := key.(type) { case addrs.IntKey: @@ -513,7 +491,6 @@ func appendInstanceObjectStateV4(rs *states.Resource, is *states.ResourceInstanc AttributesRaw: obj.AttrsJSON, PrivateRaw: privateRaw, Dependencies: deps, - DependsOn: depOn, }), diags } @@ -563,8 +540,7 @@ type instanceObjectStateV4 struct { PrivateRaw []byte `json:"private,omitempty"` - Dependencies []string `json:"dependencies,omitempty"` - DependsOn []string `json:"depends_on,omitempty"` + Dependencies []string `json:"depends_on,omitempty"` } // stateVersionV4 is a weird special type we use to produce our hard-coded diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go index d55bc2f0ce..59c06b70b5 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags/contextual.go @@ -308,8 +308,8 @@ func hclRangeFromIndexStepAndAttribute(idxStep cty.IndexStep, attr *hcl.Attribut } stepKey := idxStep.Key.AsString() for _, kvPair := range pairs { - key, diags := kvPair.Key.Value(nil) - if diags.HasErrors() { + key, err := kvPair.Key.Value(nil) + if err != nil { return attr.Expr.Range() } if key.AsString() == stepKey { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go index d317e08261..2d56dab696 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/internal/version/version.go @@ -11,7 +11,7 @@ import ( ) // The main version number that is being run at the moment. -var Version = "0.12.20" +var Version = "0.12.7" // A pre-release marker for the version. If this is "" (empty string) // then it means that it is a final release. Otherwise, this is a pre-release diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go index 27723faa49..5a99e90064 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/plugin/client.go @@ -9,11 +9,6 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/internal/plugin/discovery" ) -// The TF_DISABLE_PLUGIN_TLS environment variable is intended only for use by -// the plugin SDK test framework. We do not recommend Terraform CLI end-users -// set this variable. -var enableAutoMTLS = os.Getenv("TF_DISABLE_PLUGIN_TLS") == "" - // ClientConfig returns a configuration object that can be used to instantiate // a client for the plugin described by the given metadata. func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig { @@ -30,7 +25,7 @@ func ClientConfig(m discovery.PluginMeta) *plugin.ClientConfig { Managed: true, Logger: logger, AllowedProtocols: []plugin.Protocol{plugin.ProtocolGRPC}, - AutoMTLS: enableAutoMTLS, + AutoMTLS: true, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go index 2e31c0fc12..eb05c68ae3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context.go @@ -24,12 +24,19 @@ import ( type InputMode byte const ( + // InputModeVar asks for all variables + InputModeVar InputMode = 1 << iota + + // InputModeVarUnset asks for variables which are not set yet. + // InputModeVar must be set for this to have an effect. + InputModeVarUnset + // InputModeProvider asks for provider variables - InputModeProvider InputMode = 1 << iota + InputModeProvider // InputModeStd is the standard operating mode and asks for both variables // and providers. - InputModeStd = InputModeProvider + InputModeStd = InputModeVar | InputModeProvider ) // ContextOpts are the user-configurable options to create a context with @@ -147,7 +154,7 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { variables = variables.Override(opts.Variables) // Bind available provider plugins to the constraints in config - var providerFactories map[addrs.Provider]providers.Factory + var providerFactories map[string]providers.Factory if opts.ProviderResolver != nil { deps := ConfigTreeDependencies(opts.Config, state) reqd := deps.AllPluginRequirements() @@ -155,6 +162,7 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { reqd.LockExecutables(opts.ProviderSHA256s) } log.Printf("[TRACE] terraform.NewContext: resolving provider version selections") + var providerDiags tfdiags.Diagnostics providerFactories, providerDiags = resourceProviderFactories(opts.ProviderResolver, reqd) diags = diags.Append(providerDiags) @@ -163,7 +171,7 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { return nil, diags } } else { - providerFactories = make(map[addrs.Provider]providers.Factory) + providerFactories = make(map[string]providers.Factory) } components := &basicComponentFactory{ @@ -190,18 +198,6 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { log.Printf("[TRACE] terraform.NewContext: complete") - // By the time we get here, we should have values defined for all of - // the root module variables, even if some of them are "unknown". It's the - // caller's responsibility to have already handled the decoding of these - // from the various ways the CLI allows them to be set and to produce - // user-friendly error messages if they are not all present, and so - // the error message from checkInputVariables should never be seen and - // includes language asking the user to report a bug. - if config != nil { - varDiags := checkInputVariables(config.Module.Variables, variables) - diags = diags.Append(varDiags) - } - return &Context{ components: components, schemas: schemas, @@ -219,7 +215,7 @@ func NewContext(opts *ContextOpts) (*Context, tfdiags.Diagnostics) { providerInputConfig: make(map[string]map[string]cty.Value), providerSHA256s: opts.ProviderSHA256s, sh: sh, - }, diags + }, nil } func (c *Context) Schemas() *Schemas { @@ -650,6 +646,14 @@ func (c *Context) Validate() tfdiags.Diagnostics { var diags tfdiags.Diagnostics + // Validate input variables. We do this only for the values supplied + // by the root module, since child module calls are validated when we + // visit their graph nodes. + if c.config != nil { + varDiags := checkInputVariables(c.config.Module.Variables, c.variables) + diags = diags.Append(varDiags) + } + // If we have errors at this point then we probably won't be able to // construct a graph without producing redundant errors, so we'll halt early. if diags.HasErrors() { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go index c1ab94c9f7..b99f1afacf 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/context_input.go @@ -2,6 +2,7 @@ package terraform import ( "context" + "fmt" "log" "sort" @@ -14,22 +15,10 @@ import ( "github.com/hashicorp/terraform-plugin-sdk/internal/tfdiags" ) -// Input asks for input to fill unset required arguments in provider -// configurations. -// +// Input asks for input to fill variables and provider configurations. // This modifies the configuration in-place, so asking for Input twice // may result in different UI output showing different current values. func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { - // This function used to be responsible for more than it is now, so its - // interface is more general than its current functionality requires. - // It now exists only to handle interactive prompts for provider - // configurations, with other prompts the responsibility of the CLI - // layer prior to calling in to this package. - // - // (Hopefully in future the remaining functionality here can move to the - // CLI layer too in order to avoid this odd situation where core code - // produces UI input prompts.) - var diags tfdiags.Diagnostics defer c.acquireRun("input")() @@ -40,6 +29,85 @@ func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { ctx := context.Background() + if mode&InputModeVar != 0 { + log.Printf("[TRACE] Context.Input: Prompting for variables") + + // Walk the variables first for the root module. We walk them in + // alphabetical order for UX reasons. + configs := c.config.Module.Variables + names := make([]string, 0, len(configs)) + for name := range configs { + names = append(names, name) + } + sort.Strings(names) + Variables: + for _, n := range names { + v := configs[n] + + // If we only care about unset variables, then we should set any + // variable that is already set. + if mode&InputModeVarUnset != 0 { + if _, isSet := c.variables[n]; isSet { + continue + } + } + + // this should only happen during tests + if c.uiInput == nil { + log.Println("[WARN] Context.uiInput is nil during input walk") + continue + } + + // Ask the user for a value for this variable + var rawValue string + retry := 0 + for { + var err error + rawValue, err = c.uiInput.Input(ctx, &InputOpts{ + Id: fmt.Sprintf("var.%s", n), + Query: fmt.Sprintf("var.%s", n), + Description: v.Description, + }) + if err != nil { + diags = diags.Append(tfdiags.Sourceless( + tfdiags.Error, + "Failed to request interactive input", + fmt.Sprintf("Terraform attempted to request a value for var.%s interactively, but encountered an error: %s.", n, err), + )) + return diags + } + + if rawValue == "" && v.Default == cty.NilVal { + // Redo if it is required, but abort if we keep getting + // blank entries + if retry > 2 { + diags = diags.Append(tfdiags.Sourceless( + tfdiags.Error, + "Required variable not assigned", + fmt.Sprintf("The variable %q is required, so Terraform cannot proceed without a defined value for it.", n), + )) + continue Variables + } + retry++ + continue + } + + break + } + + val, valDiags := v.ParsingMode.Parse(n, rawValue) + diags = diags.Append(valDiags) + if diags.HasErrors() { + continue + } + + c.variables[n] = &InputValue{ + Value: val, + SourceType: ValueFromInput, + } + } + } + if mode&InputModeProvider != 0 { log.Printf("[TRACE] Context.Input: Prompting for provider arguments") @@ -96,7 +164,7 @@ func (c *Context) Input(mode InputMode) tfdiags.Diagnostics { UIInput: c.uiInput, } - schema := c.schemas.ProviderConfig(pa.Type.LegacyString()) + schema := c.schemas.ProviderConfig(pa.Type) if schema == nil { // Could either be an incorrect config or just an incomplete // mock in tests. We'll let a later pass decide, and just diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go index 05faee7813..6beeaea984 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_apply.go @@ -24,6 +24,7 @@ import ( type EvalApply struct { Addr addrs.ResourceInstance Config *configs.Resource + Dependencies []addrs.Referenceable State **states.ResourceInstanceObject Change **plans.ResourceInstanceChange ProviderAddr addrs.AbsProviderConfig @@ -253,8 +254,6 @@ func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { } } - newStatus := states.ObjectReady - // Sometimes providers return a null value when an operation fails for some // reason, but we'd rather keep the prior state so that the error can be // corrected on a subsequent run. We must only do this for null new value @@ -267,20 +266,15 @@ func (n *EvalApply) Eval(ctx EvalContext) (interface{}, error) { // If change.Action is Create then change.Before will also be null, // which is fine. newVal = change.Before - - // If we're recovering the previous state, we also want to restore the - // the tainted status of the object. - if state.Status == states.ObjectTainted { - newStatus = states.ObjectTainted - } } var newState *states.ResourceInstanceObject if !newVal.IsNull() { // null value indicates that the object is deleted, so we won't set a new state in that case newState = &states.ResourceInstanceObject{ - Status: newStatus, - Value: newVal, - Private: resp.Private, + Status: states.ObjectReady, + Value: newVal, + Private: resp.Private, + Dependencies: n.Dependencies, // Should be populated by the caller from the StateDependencies method on the resource instance node } } @@ -384,39 +378,40 @@ type EvalMaybeTainted struct { Change **plans.ResourceInstanceChange State **states.ResourceInstanceObject Error *error + + // If StateOutput is not nil, its referent will be assigned either the same + // pointer as State or a new object with its status set as Tainted, + // depending on whether an error is given and if this was a create action. + StateOutput **states.ResourceInstanceObject } +// TODO: test func (n *EvalMaybeTainted) Eval(ctx EvalContext) (interface{}, error) { - if n.State == nil || n.Change == nil || n.Error == nil { - return nil, nil - } - state := *n.State change := *n.Change err := *n.Error - // nothing to do if everything went as planned - if err == nil { - return nil, nil - } - if state != nil && state.Status == states.ObjectTainted { log.Printf("[TRACE] EvalMaybeTainted: %s was already tainted, so nothing to do", n.Addr.Absolute(ctx.Path())) return nil, nil } - if change.Action == plans.Create { - // If there are errors during a _create_ then the object is - // in an undefined state, and so we'll mark it as tainted so - // we can try again on the next run. - // - // We don't do this for other change actions because errors - // during updates will often not change the remote object at all. - // If there _were_ changes prior to the error, it's the provider's - // responsibility to record the effect of those changes in the - // object value it returned. - log.Printf("[TRACE] EvalMaybeTainted: %s encountered an error during creation, so it is now marked as tainted", n.Addr.Absolute(ctx.Path())) - *n.State = state.AsTainted() + if n.StateOutput != nil { + if err != nil && change.Action == plans.Create { + // If there are errors during a _create_ then the object is + // in an undefined state, and so we'll mark it as tainted so + // we can try again on the next run. + // + // We don't do this for other change actions because errors + // during updates will often not change the remote object at all. + // If there _were_ changes prior to the error, it's the provider's + // responsibility to record the effect of those changes in the + // object value it returned. + log.Printf("[TRACE] EvalMaybeTainted: %s encountered an error during creation, so it is now marked as tainted", n.Addr.Absolute(ctx.Path())) + *n.StateOutput = state.AsTainted() + } else { + *n.StateOutput = state + } } return nil, nil @@ -569,11 +564,6 @@ func (n *EvalApplyProvisioners) apply(ctx EvalContext, provs []*configs.Provisio config, _, configDiags := ctx.EvaluateBlock(prov.Config, schema, instanceAddr, keyData) diags = diags.Append(configDiags) - // we can't apply the provisioner if the config has errors - if diags.HasErrors() { - return diags.Err() - } - // If the provisioner block contains a connection block of its own then // it can override the base connection configuration, if any. var localConn hcl.Body diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go index 26d68c175c..7440cff7ad 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_provider.go @@ -125,7 +125,7 @@ type EvalGetProvider struct { } func (n *EvalGetProvider) Eval(ctx EvalContext) (interface{}, error) { - if n.Addr.ProviderConfig.Type.LegacyString() == "" { + if n.Addr.ProviderConfig.Type == "" { // Should never happen panic("EvalGetProvider used with uninitialized provider configuration address") } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go index 913c41eebb..0b734b793f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_read_data.go @@ -21,6 +21,7 @@ import ( type EvalReadData struct { Addr addrs.ResourceInstance Config *configs.Resource + Dependencies []addrs.Referenceable Provider *providers.Interface ProviderAddr addrs.AbsProviderConfig ProviderSchema **ProviderSchema @@ -160,8 +161,9 @@ func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { } if n.OutputState != nil { state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectPlanned, // because the partial value in the plan must be used for now + Value: change.After, + Status: states.ObjectPlanned, // because the partial value in the plan must be used for now + Dependencies: n.Dependencies, } *n.OutputState = state } @@ -273,8 +275,9 @@ func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { }, } state := &states.ResourceInstanceObject{ - Value: change.After, - Status: states.ObjectReady, // because we completed the read from the provider + Value: change.After, + Status: states.ObjectReady, // because we completed the read from the provider + Dependencies: n.Dependencies, } err = ctx.Hook(func(h Hook) (HookAction, error) { @@ -303,13 +306,14 @@ func (n *EvalReadData) Eval(ctx EvalContext) (interface{}, error) { // EvalReadDataApply is an EvalNode implementation that executes a data // resource's ReadDataApply method to read data from the data source. type EvalReadDataApply struct { - Addr addrs.ResourceInstance - Provider *providers.Interface - ProviderAddr addrs.AbsProviderConfig - ProviderSchema **ProviderSchema - Output **states.ResourceInstanceObject - Config *configs.Resource - Change **plans.ResourceInstanceChange + Addr addrs.ResourceInstance + Provider *providers.Interface + ProviderAddr addrs.AbsProviderConfig + ProviderSchema **ProviderSchema + Output **states.ResourceInstanceObject + Config *configs.Resource + Change **plans.ResourceInstanceChange + StateReferences []addrs.Referenceable } func (n *EvalReadDataApply) Eval(ctx EvalContext) (interface{}, error) { @@ -381,8 +385,9 @@ func (n *EvalReadDataApply) Eval(ctx EvalContext) (interface{}, error) { if n.Output != nil { *n.Output = &states.ResourceInstanceObject{ - Value: newVal, - Status: states.ObjectReady, + Value: newVal, + Status: states.ObjectReady, + Dependencies: n.StateReferences, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go index 1f3e9810b2..6a834445c3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/eval_refresh.go @@ -89,7 +89,6 @@ func (n *EvalRefresh) Eval(ctx EvalContext) (interface{}, error) { newState := state.DeepCopy() newState.Value = resp.NewState newState.Private = resp.Private - newState.Dependencies = state.Dependencies // Call post-refresh hook err = ctx.Hook(func(h Hook) (HookAction, error) { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go index 4187a8e4e9..d4a8d3cf74 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaltree_provider.go @@ -16,7 +16,7 @@ func ProviderEvalTree(n *NodeApplyableProvider, config *configs.Provider) EvalNo seq := make([]EvalNode, 0, 5) seq = append(seq, &EvalInitProvider{ - TypeName: relAddr.Type.LegacyString(), + TypeName: relAddr.Type, Addr: addr.ProviderConfig, }) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go index de86805b34..2d3eabd488 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate.go @@ -184,16 +184,6 @@ func (d *evaluationStateData) GetForEachAttr(addr addrs.ForEachAttr, rng tfdiags returnVal = d.InstanceKeyData.EachKey case "value": returnVal = d.InstanceKeyData.EachValue - - if returnVal == cty.NilVal { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: `each.value cannot be used in this context`, - Detail: fmt.Sprintf(`A reference to "each.value" has been used in a context in which it unavailable, such as when the configuration no longer contains the value in its "for_each" expression. Remove this reference to each.value in your configuration to work around this error.`), - Subject: rng.ToHCL().Ptr(), - }) - return cty.UnknownVal(cty.DynamicPseudoType), diags - } default: diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, @@ -647,59 +637,60 @@ func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng t for i := 0; i < length; i++ { ty := schema.ImpliedType() key := addrs.IntKey(i) - is := rs.Instances[key] - if is == nil || is.Current == nil { - // There shouldn't normally be "gaps" in our list but we'll - // allow it under the assumption that we're in a weird situation - // where e.g. someone has run "terraform state mv" to reorder - // a list and left a hole behind. - vals[i] = cty.UnknownVal(schema.ImpliedType()) - continue - } - - instAddr := addr.Instance(key).Absolute(d.ModulePath) + is, exists := rs.Instances[key] + if exists && is.Current != nil { + instAddr := addr.Instance(key).Absolute(d.ModulePath) - if is.Current.Status == states.ObjectPlanned { - if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { - val, err := change.After.Decode(ty) - if err != nil { + // Prefer pending value in plan if present. See getResourceInstanceSingle + // comment for the rationale. + if is.Current.Status == states.ObjectPlanned { + if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { + val, err := change.After.Decode(ty) + if err != nil { + diags = diags.Append(&hcl.Diagnostic{ + Severity: hcl.DiagError, + Summary: "Invalid resource instance data in plan", + Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), + Subject: &config.DeclRange, + }) + continue + } + vals[i] = val + continue + } else { + // If the object is in planned status then we should not + // get here, since we should've found a pending value + // in the plan above instead. diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, - Summary: "Invalid resource instance data in plan", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the plan: %s.", instAddr, err), + Summary: "Missing pending object in plan", + Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), Subject: &config.DeclRange, }) continue } - vals[i] = val - continue - } else { - // If the object is in planned status then we should not - // get here, since we should've found a pending value - // in the plan above instead. + } + + ios, err := is.Current.Decode(ty) + if err != nil { + // This shouldn't happen, since by the time we get here + // we should've upgraded the state data already. diags = diags.Append(&hcl.Diagnostic{ Severity: hcl.DiagError, - Summary: "Missing pending object in plan", - Detail: fmt.Sprintf("Instance %s is marked as having a change pending but that change is not recorded in the plan. This is a bug in Terraform; please report it.", instAddr), + Summary: "Invalid resource instance data in state", + Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), Subject: &config.DeclRange, }) continue } + vals[i] = ios.Value + } else { + // There shouldn't normally be "gaps" in our list but we'll + // allow it under the assumption that we're in a weird situation + // where e.g. someone has run "terraform state mv" to reorder + // a list and left a hole behind. + vals[i] = cty.UnknownVal(schema.ImpliedType()) } - - ios, err := is.Current.Decode(ty) - if err != nil { - // This shouldn't happen, since by the time we get here - // we should've upgraded the state data already. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid resource instance data in state", - Detail: fmt.Sprintf("Instance %s data could not be decoded from the state: %s.", instAddr, err), - Subject: &config.DeclRange, - }) - continue - } - vals[i] = ios.Value } // We use a tuple rather than a list here because resource schemas may @@ -713,14 +704,12 @@ func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng t vals := make(map[string]cty.Value, len(rs.Instances)) for k, is := range rs.Instances { if sk, ok := k.(addrs.StringKey); ok { - if is == nil || is.Current == nil { - // Assume we're dealing with an instance that hasn't been created yet. - vals[string(sk)] = cty.UnknownVal(schema.ImpliedType()) - continue - } - instAddr := addr.Instance(k).Absolute(d.ModulePath) + // Prefer pending value in plan if present. See getResourceInstanceSingle + // comment for the rationale. + // Prefer pending value in plan if present. See getResourceInstanceSingle + // comment for the rationale. if is.Current.Status == states.ObjectPlanned { if change := d.Evaluator.Changes.GetResourceInstanceChange(instAddr, states.CurrentGen); change != nil { val, err := change.After.Decode(ty) @@ -778,7 +767,7 @@ func (d *evaluationStateData) getResourceInstancesAll(addr addrs.Resource, rng t } func (d *evaluationStateData) getResourceSchema(addr addrs.Resource, providerAddr addrs.AbsProviderConfig) *configschema.Block { - providerType := providerAddr.ProviderConfig.Type.LegacyString() + providerType := providerAddr.ProviderConfig.Type schemas := d.Evaluator.Schemas schema, _ := schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) return schema diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go index 36da5af65a..35a8be0c96 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/evaluate_valid.go @@ -215,7 +215,7 @@ func (d *evaluationStateData) staticValidateResourceReference(modCfg *configs.Co // Normally accessing this directly is wrong because it doesn't take into // account provider inheritance, etc but it's okay here because we're only // paying attention to the type anyway. - providerType := cfg.ProviderConfigAddr().Type.LegacyString() + providerType := cfg.ProviderConfigAddr().Type schema, _ := d.Evaluator.Schemas.ResourceTypeConfig(providerType, addr.Mode, addr.Type) if schema == nil { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go index 1225d2fb4e..9189876106 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_apply.go @@ -155,21 +155,6 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { // Connect references so ordering is correct &ReferenceTransformer{}, - &AttachDependenciesTransformer{}, - - // Destruction ordering - &DestroyEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - }, - - &CBDEdgeTransformer{ - Config: b.Config, - State: b.State, - Schemas: b.Schemas, - Destroy: b.Destroy, - }, // Destruction ordering &DestroyEdgeTransformer{ @@ -189,20 +174,17 @@ func (b *ApplyGraphBuilder) Steps() []GraphTransformer { // Reverse the edges from outputs and locals, so that // interpolations don't fail during destroy. // Create a destroy node for outputs to remove them from the state. + // Prune unreferenced values, which may have interpolations that can't + // be resolved. GraphTransformIf( func() bool { return b.Destroy }, GraphTransformMulti( &DestroyValueReferenceTransformer{}, &DestroyOutputTransformer{}, + &PruneUnusedValuesTransformer{}, ), ), - // Prune unreferenced values, which may have interpolations that can't - // be resolved. - &PruneUnusedValuesTransformer{ - Destroy: b.Destroy, - }, - // Add the node to fix the state count boundaries &CountBoundaryTransformer{ Config: b.Config, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go index 970960387e..fad7bf161f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/graph_builder_refresh.go @@ -165,7 +165,6 @@ func (b *RefreshGraphBuilder) Steps() []GraphTransformer { // Connect so that the references are ready for targeting. We'll // have to connect again later for providers and so on. &ReferenceTransformer{}, - &AttachDependenciesTransformer{}, // Target &TargetsTransformer{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go index b62782f9da..f1434e6252 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/module_dependencies.go @@ -58,8 +58,9 @@ func configTreeConfigDependencies(root *configs.Config, inheritProviders map[str // The main way to declare a provider dependency is explicitly inside // the "terraform" block, which allows declaring a requirement without // also creating a configuration. - for fullName, req := range module.ProviderRequirements { + for fullName, constraints := range module.ProviderRequirements { inst := moduledeps.ProviderInstance(fullName) + // The handling here is a bit fiddly because the moduledeps package // was designed around the legacy (pre-0.12) configuration model // and hasn't yet been revised to handle the new model. As a result, @@ -68,7 +69,7 @@ func configTreeConfigDependencies(root *configs.Config, inheritProviders map[str // can also retain the source location of each constraint, for // more informative output from the "terraform providers" command. var rawConstraints version.Constraints - for _, constraint := range req.VersionConstraints { + for _, constraint := range constraints { rawConstraints = append(rawConstraints, constraint.Required...) } discoConstraints := discovery.NewConstraints(rawConstraints) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go index b363550264..56283c0ac3 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_data_refresh.go @@ -169,6 +169,7 @@ func (n *NodeRefreshableDataResourceInstance) EvalTree() EvalNode { &EvalReadData{ Addr: addr.Resource, Config: n.Config, + Dependencies: n.StateReferences(), Provider: &provider, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go index 1e4daabb98..580e60cb7e 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_provider_eval.go @@ -14,7 +14,7 @@ func (n *NodeEvalableProvider) EvalTree() EvalNode { relAddr := addr.ProviderConfig return &EvalInitProvider{ - TypeName: relAddr.Type.LegacyString(), + TypeName: relAddr.Type, Addr: addr.ProviderConfig, } } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go index 38dca73ab9..acdda45e40 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_apply_instance.go @@ -28,13 +28,12 @@ type NodeApplyableResourceInstance struct { } var ( - _ GraphNodeResource = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeResourceInstance = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeCreator = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeReferencer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeDeposer = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeEvalable = (*NodeApplyableResourceInstance)(nil) - _ GraphNodeAttachDependencies = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeResource = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeResourceInstance = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeCreator = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeReferencer = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeDeposer = (*NodeApplyableResourceInstance)(nil) + _ GraphNodeEvalable = (*NodeApplyableResourceInstance)(nil) ) // GraphNodeAttachDestroyer @@ -98,11 +97,6 @@ func (n *NodeApplyableResourceInstance) References() []*addrs.Reference { return ret } -// GraphNodeAttachDependencies -func (n *NodeApplyableResourceInstance) AttachDependencies(deps []addrs.AbsResource) { - n.Dependencies = deps -} - // GraphNodeEvalable func (n *NodeApplyableResourceInstance) EvalTree() EvalNode { addr := n.ResourceInstanceAddr() @@ -177,6 +171,7 @@ func (n *NodeApplyableResourceInstance) evalTreeDataResource(addr addrs.AbsResou &EvalReadData{ Addr: addr.Resource, Config: n.Config, + Dependencies: n.StateReferences(), Planned: &change, // setting this indicates that the result must be complete Provider: &provider, ProviderAddr: n.ResolvedProvider, @@ -346,6 +341,7 @@ func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsRe &EvalApply{ Addr: addr.Resource, Config: n.Config, + Dependencies: n.StateReferences(), State: &state, Change: &diffApply, Provider: &provider, @@ -356,17 +352,17 @@ func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsRe CreateNew: &createNew, }, &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, + Addr: addr.Resource, + State: &state, + Change: &diffApply, + Error: &err, + StateOutput: &state, }, &EvalWriteState{ Addr: addr.Resource, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, - Dependencies: &n.Dependencies, }, &EvalApplyProvisioners{ Addr: addr.Resource, @@ -377,26 +373,25 @@ func (n *NodeApplyableResourceInstance) evalTreeManagedResource(addr addrs.AbsRe When: configs.ProvisionerWhenCreate, }, &EvalMaybeTainted{ - Addr: addr.Resource, - State: &state, - Change: &diffApply, - Error: &err, + Addr: addr.Resource, + State: &state, + Change: &diffApply, + Error: &err, + StateOutput: &state, }, &EvalWriteState{ Addr: addr.Resource, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, - Dependencies: &n.Dependencies, }, &EvalIf{ If: func(ctx EvalContext) (bool, error) { return createBeforeDestroyEnabled && err != nil, nil }, Then: &EvalMaybeRestoreDeposedObject{ - Addr: addr.Resource, - PlannedChange: &diffApply, - Key: &deposedKey, + Addr: addr.Resource, + Key: &deposedKey, }, }, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go index a66c30d1dc..049e5e9907 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy.go @@ -285,13 +285,6 @@ var ( _ GraphNodeReferenceable = (*NodeDestroyResource)(nil) _ GraphNodeReferencer = (*NodeDestroyResource)(nil) _ GraphNodeEvalable = (*NodeDestroyResource)(nil) - - // FIXME: this is here to document that this node is both - // GraphNodeProviderConsumer by virtue of the embedded - // NodeAbstractResource, but that behavior is not desired and we skip it by - // checking for GraphNodeNoProvider. - _ GraphNodeProviderConsumer = (*NodeDestroyResource)(nil) - _ GraphNodeNoProvider = (*NodeDestroyResource)(nil) ) func (n *NodeDestroyResource) Name() string { @@ -326,23 +319,3 @@ func (n *NodeDestroyResource) EvalTree() EvalNode { Addr: n.ResourceAddr().Resource, } } - -// GraphNodeResource -func (n *NodeDestroyResource) ResourceAddr() addrs.AbsResource { - return n.NodeAbstractResource.ResourceAddr() -} - -// GraphNodeSubpath -func (n *NodeDestroyResource) Path() addrs.ModuleInstance { - return n.NodeAbstractResource.Path() -} - -// GraphNodeNoProvider -// FIXME: this should be removed once the node can be separated from the -// Internal NodeAbstractResource behavior. -func (n *NodeDestroyResource) NoProvider() { -} - -type GraphNodeNoProvider interface { - NoProvider() -} diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go index 42ddb3fbe3..269c798080 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_destroy_deposed.go @@ -178,7 +178,7 @@ var ( ) func (n *NodeDestroyDeposedResourceInstanceObject) Name() string { - return fmt.Sprintf("%s (destroy deposed %s)", n.ResourceInstanceAddr(), n.DeposedKey) + return fmt.Sprintf("%s (destroy deposed %s)", n.Addr.String(), n.DeposedKey) } func (n *NodeDestroyDeposedResourceInstanceObject) DeposedInstanceObjectKey() states.DeposedKey { diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go index c29e4970db..2c3a7012b9 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_destroy.go @@ -47,7 +47,7 @@ func (n *NodePlanDestroyableResourceInstance) EvalTree() EvalNode { var change *plans.ResourceInstanceChange var state *states.ResourceInstanceObject - if n.ResolvedProvider.ProviderConfig.Type.String() == "" { + if n.ResolvedProvider.ProviderConfig.Type == "" { // Should never happen; indicates that the graph was not constructed // correctly since we didn't get our provider attached. panic(fmt.Sprintf("%T %q was not assigned a resolved provider", n, dag.VertexName(n))) diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go index 3c742592b0..ac4b24cf22 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_plan_instance.go @@ -78,8 +78,8 @@ func (n *NodePlannableResourceInstance) evalTreeDataResource(addr addrs.AbsResou // Check and see if any of our dependencies have changes. changes := ctx.Changes() - for _, d := range n.References() { - ri, ok := d.Subject.(addrs.ResourceInstance) + for _, d := range n.StateReferences() { + ri, ok := d.(addrs.ResourceInstance) if !ok { continue } @@ -114,6 +114,7 @@ func (n *NodePlannableResourceInstance) evalTreeDataResource(addr addrs.AbsResou &EvalReadData{ Addr: addr.Resource, Config: n.Config, + Dependencies: n.StateReferences(), Provider: &provider, ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go index c4920ac5db..dcab37270c 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_resource_refresh.go @@ -18,10 +18,6 @@ import ( // NodeRefreshableManagedResourceInstance. Resource count orphans are also added. type NodeRefreshableManagedResource struct { *NodeAbstractResource - - // We attach dependencies to the Resource during refresh, since the - // instances are instantiated during DynamicExpand. - Dependencies []addrs.AbsResource } var ( @@ -31,14 +27,8 @@ var ( _ GraphNodeReferencer = (*NodeRefreshableManagedResource)(nil) _ GraphNodeResource = (*NodeRefreshableManagedResource)(nil) _ GraphNodeAttachResourceConfig = (*NodeRefreshableManagedResource)(nil) - _ GraphNodeAttachDependencies = (*NodeRefreshableManagedResource)(nil) ) -// GraphNodeAttachDependencies -func (n *NodeRefreshableManagedResource) AttachDependencies(deps []addrs.AbsResource) { - n.Dependencies = deps -} - // GraphNodeDynamicExpandable func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, error) { var diags tfdiags.Diagnostics @@ -68,7 +58,6 @@ func (n *NodeRefreshableManagedResource) DynamicExpand(ctx EvalContext) (*Graph, // Add the config and state since we don't do that via transforms a.Config = n.Config a.ResolvedProvider = n.ResolvedProvider - a.Dependencies = n.Dependencies return &NodeRefreshableManagedResourceInstance{ NodeAbstractResourceInstance: a, @@ -214,11 +203,6 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalN Output: &state, }, - &EvalRefreshDependencies{ - State: &state, - Dependencies: &n.Dependencies, - }, - &EvalRefresh{ Addr: addr.Resource, ProviderAddr: n.ResolvedProvider, @@ -233,7 +217,6 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResource() EvalN ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, - Dependencies: &n.Dependencies, }, }, } @@ -293,7 +276,6 @@ func (n *NodeRefreshableManagedResourceInstance) evalTreeManagedResourceNoState( ProviderAddr: n.ResolvedProvider, ProviderSchema: &providerSchema, State: &state, - Dependencies: &n.Dependencies, }, // We must also save the planned change, so that expressions in diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go index 8c4101d601..844d060c9f 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/node_root_variable.go @@ -32,26 +32,6 @@ func (n *NodeRootVariable) ReferenceableAddrs() []addrs.Referenceable { return []addrs.Referenceable{n.Addr} } -// GraphNodeEvalable -func (n *NodeRootVariable) EvalTree() EvalNode { - // We don't actually need to _evaluate_ a root module variable, because - // its value is always constant and already stashed away in our EvalContext. - // However, we might need to run some user-defined validation rules against - // the value. - - if n.Config == nil || len(n.Config.Validations) == 0 { - return &EvalSequence{} // nothing to do - } - - return &evalVariableValidations{ - Addr: addrs.RootModuleInstance.InputVariable(n.Addr.Name), - Config: n.Config, - Expr: nil, // not set for root module variables - - IgnoreDiagnostics: false, - } -} - // dag.GraphNodeDotter impl. func (n *NodeRootVariable) DotNode(name string, opts *dag.DotOpts) *dag.DotNode { return &dag.DotNode{ diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go index 0718fd09a4..93b19be57d 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/provisioner_mock.go @@ -120,6 +120,7 @@ func (p *MockProvisioner) ProvisionResource(r provisioners.ProvisionResourceRequ } if p.ProvisionResourceFn != nil { fn := p.ProvisionResourceFn + p.Unlock() return fn(r) } diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go index e202990079..fee220b52b 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_attach_schema.go @@ -59,7 +59,7 @@ func (t *AttachSchemaTransformer) Transform(g *Graph) error { mode := addr.Resource.Mode typeName := addr.Resource.Type providerAddr, _ := tv.ProvidedBy() - providerType := providerAddr.ProviderConfig.Type.LegacyString() + providerType := providerAddr.ProviderConfig.Type schema, version := t.Schemas.ResourceTypeConfig(providerType, mode, typeName) if schema == nil { @@ -72,7 +72,7 @@ func (t *AttachSchemaTransformer) Transform(g *Graph) error { if tv, ok := v.(GraphNodeAttachProviderConfigSchema); ok { providerAddr := tv.ProviderAddr() - schema := t.Schemas.ProviderConfig(providerAddr.ProviderConfig.Type.LegacyString()) + schema := t.Schemas.ProviderConfig(providerAddr.ProviderConfig.Type) if schema == nil { log.Printf("[ERROR] AttachSchemaTransformer: No provider config schema available for %s", providerAddr) continue diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go index 41e4205bd2..1d211570fc 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_destroy_edge.go @@ -54,39 +54,26 @@ type DestroyEdgeTransformer struct { func (t *DestroyEdgeTransformer) Transform(g *Graph) error { // Build a map of what is being destroyed (by address string) to - // the list of destroyers. + // the list of destroyers. Usually there will be at most one destroyer + // per node, but we allow multiple if present for completeness. destroyers := make(map[string][]GraphNodeDestroyer) destroyerAddrs := make(map[string]addrs.AbsResourceInstance) - - // Record the creators, which will need to depend on the destroyers if they - // are only being updated. - creators := make(map[string]GraphNodeCreator) - - // destroyersByResource records each destroyer by the AbsResourceAddress. - // We use this because dependencies are only referenced as resources, but we - // will want to connect all the individual instances for correct ordering. - destroyersByResource := make(map[string][]GraphNodeDestroyer) for _, v := range g.Vertices() { - switch n := v.(type) { - case GraphNodeDestroyer: - addrP := n.DestroyAddr() - if addrP == nil { - log.Printf("[WARN] DestroyEdgeTransformer: %q (%T) has no destroy address", dag.VertexName(n), v) - continue - } - addr := *addrP + dn, ok := v.(GraphNodeDestroyer) + if !ok { + continue + } - key := addr.String() - log.Printf("[TRACE] DestroyEdgeTransformer: %q (%T) destroys %s", dag.VertexName(n), v, key) - destroyers[key] = append(destroyers[key], n) - destroyerAddrs[key] = addr - - resAddr := addr.Resource.Resource.Absolute(addr.Module).String() - destroyersByResource[resAddr] = append(destroyersByResource[resAddr], n) - case GraphNodeCreator: - addr := n.CreateAddr() - creators[addr.String()] = n + addrP := dn.DestroyAddr() + if addrP == nil { + continue } + addr := *addrP + + key := addr.String() + log.Printf("[TRACE] DestroyEdgeTransformer: %q (%T) destroys %s", dag.VertexName(dn), v, key) + destroyers[key] = append(destroyers[key], dn) + destroyerAddrs[key] = addr } // If we aren't destroying anything, there will be no edges to make @@ -95,40 +82,6 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { return nil } - // Connect destroy despendencies as stored in the state - for _, ds := range destroyers { - for _, des := range ds { - ri, ok := des.(GraphNodeResourceInstance) - if !ok { - continue - } - - for _, resAddr := range ri.StateDependencies() { - for _, desDep := range destroyersByResource[resAddr.String()] { - log.Printf("[TRACE] DestroyEdgeTransformer: %s has stored dependency of %s\n", dag.VertexName(desDep), dag.VertexName(des)) - g.Connect(dag.BasicEdge(desDep, des)) - - } - } - } - } - - // connect creators to any destroyers on which they may depend - for _, c := range creators { - ri, ok := c.(GraphNodeResourceInstance) - if !ok { - continue - } - - for _, resAddr := range ri.StateDependencies() { - for _, desDep := range destroyersByResource[resAddr.String()] { - log.Printf("[TRACE] DestroyEdgeTransformer: %s has stored dependency of %s\n", dag.VertexName(c), dag.VertexName(desDep)) - g.Connect(dag.BasicEdge(c, desDep)) - - } - } - } - // Go through and connect creators to destroyers. Going along with // our example, this makes: A_d => A for _, v := range g.Vertices() { @@ -142,7 +95,13 @@ func (t *DestroyEdgeTransformer) Transform(g *Graph) error { continue } - for _, d := range destroyers[addr.String()] { + key := addr.String() + ds := destroyers[key] + if len(ds) == 0 { + continue + } + + for _, d := range ds { // For illustrating our example a_d := d.(dag.Vertex) a := v diff --git a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go index b3c3fcaadf..7dd2c4876d 100644 --- a/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go +++ b/vendor/github.com/hashicorp/terraform-plugin-sdk/terraform/transform_import_state.go @@ -20,7 +20,7 @@ func (t *ImportStateTransformer) Transform(g *Graph) error { // This will be populated if the targets come from the cli, but tests // may not specify implied provider addresses. providerAddr := target.ProviderAddr - if providerAddr.ProviderConfig.Type.Type == "" { + if providerAddr.ProviderConfig.Type == "" { providerAddr = target.Addr.Resource.Resource.DefaultProviderConfig().Absolute(target.Addr.Module) } diff --git a/vendor/github.com/hashicorp/terraform/addrs/provider.go b/vendor/github.com/hashicorp/terraform/addrs/provider.go deleted file mode 100644 index b73cfb5a7f..0000000000 --- a/vendor/github.com/hashicorp/terraform/addrs/provider.go +++ /dev/null @@ -1,49 +0,0 @@ -package addrs - -import ( - svchost "github.com/hashicorp/terraform-svchost" -) - -// Provider encapsulates a single provider type. In the future this will be -// extended to include additional fields including Namespace and SourceHost -type Provider struct { - Type string - Namespace string - Hostname svchost.Hostname -} - -// String returns an FQN string, indended for use in output. -func (pt Provider) String() string { - return pt.Hostname.ForDisplay() + "/" + pt.Namespace + "/" + pt.Type -} - -// NewDefaultProvider returns the default address of a HashiCorp-maintained, -// Registry-hosted provider. -func NewDefaultProvider(name string) Provider { - return Provider{ - Type: name, - Namespace: "hashicorp", - Hostname: "registry.terraform.io", - } -} - -// NewLegacyProvider returns a mock address for a provider. -// This will be removed when ProviderType is fully integrated. -func NewLegacyProvider(name string) Provider { - return Provider{ - Type: name, - Namespace: "-", - Hostname: "registry.terraform.io", - } -} - -// LegacyString returns the provider type, which is frequently used -// interchangeably with provider name. This function can and should be removed -// when provider type is fully integrated. As a safeguard for future -// refactoring, this function panics if the Provider is not a legacy provider. -func (pt Provider) LegacyString() string { - if pt.Namespace != "-" { - panic("not a legacy Provider") - } - return pt.Type -} diff --git a/vendor/github.com/hashicorp/terraform/configs/experiments.go b/vendor/github.com/hashicorp/terraform/configs/experiments.go deleted file mode 100644 index 435bac11d4..0000000000 --- a/vendor/github.com/hashicorp/terraform/configs/experiments.go +++ /dev/null @@ -1,156 +0,0 @@ -package configs - -import ( - "fmt" - - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform/experiments" -) - -// sniffActiveExperiments does minimal parsing of the given body for -// "terraform" blocks with "experiments" attributes, returning the -// experiments found. -// -// This is separate from other processing so that we can be sure that all of -// the experiments are known before we process the result of the module config, -// and thus we can take into account which experiments are active when deciding -// how to decode. -func sniffActiveExperiments(body hcl.Body) (experiments.Set, hcl.Diagnostics) { - rootContent, _, diags := body.PartialContent(configFileTerraformBlockSniffRootSchema) - - ret := experiments.NewSet() - - for _, block := range rootContent.Blocks { - content, _, blockDiags := block.Body.PartialContent(configFileExperimentsSniffBlockSchema) - diags = append(diags, blockDiags...) - - attr, exists := content.Attributes["experiments"] - if !exists { - continue - } - - exps, expDiags := decodeExperimentsAttr(attr) - diags = append(diags, expDiags...) - if !expDiags.HasErrors() { - ret = experiments.SetUnion(ret, exps) - } - } - - return ret, diags -} - -func decodeExperimentsAttr(attr *hcl.Attribute) (experiments.Set, hcl.Diagnostics) { - var diags hcl.Diagnostics - - exprs, moreDiags := hcl.ExprList(attr.Expr) - diags = append(diags, moreDiags...) - if moreDiags.HasErrors() { - return nil, diags - } - - var ret = experiments.NewSet() - for _, expr := range exprs { - kw := hcl.ExprAsKeyword(expr) - if kw == "" { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid experiment keyword", - Detail: "Elements of \"experiments\" must all be keywords representing active experiments.", - Subject: expr.Range().Ptr(), - }) - continue - } - - exp, err := experiments.GetCurrent(kw) - switch err := err.(type) { - case experiments.UnavailableError: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Unknown experiment keyword", - Detail: fmt.Sprintf("There is no current experiment with the keyword %q.", kw), - Subject: expr.Range().Ptr(), - }) - case experiments.ConcludedError: - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Experiment has concluded", - Detail: fmt.Sprintf("Experiment %q is no longer available. %s", kw, err.Message), - Subject: expr.Range().Ptr(), - }) - case nil: - // No error at all means it's valid and current. - ret.Add(exp) - - // However, experimental features are subject to breaking changes - // in future releases, so we'll warn about them to help make sure - // folks aren't inadvertently using them in places where that'd be - // inappropriate, particularly if the experiment is active in a - // shared module they depend on. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagWarning, - Summary: fmt.Sprintf("Experimental feature %q is active", exp.Keyword()), - Detail: "Experimental features are subject to breaking changes in future minor or patch releases, based on feedback.\n\nIf you have feedback on the design of this feature, please open a GitHub issue to discuss it.", - Subject: expr.Range().Ptr(), - }) - - default: - // This should never happen, because GetCurrent is not documented - // to return any other error type, but we'll handle it to be robust. - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid experiment keyword", - Detail: fmt.Sprintf("Could not parse %q as an experiment keyword: %s.", kw, err.Error()), - Subject: expr.Range().Ptr(), - }) - } - } - return ret, diags -} - -func checkModuleExperiments(m *Module) hcl.Diagnostics { - var diags hcl.Diagnostics - - // When we have current experiments, this is a good place to check that - // the features in question can only be used when the experiments are - // active. Return error diagnostics if a feature is being used without - // opting in to the feature. For example: - /* - if !m.ActiveExperiments.Has(experiments.ResourceForEach) { - for _, rc := range m.ManagedResources { - if rc.ForEach != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Resource for_each is experimental", - Detail: "This feature is currently an opt-in experiment, subject to change in future releases based on feedback.\n\nActivate the feature for this module by adding resource_for_each to the list of active experiments.", - Subject: rc.ForEach.Range().Ptr(), - }) - } - } - for _, rc := range m.DataResources { - if rc.ForEach != nil { - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Resource for_each is experimental", - Detail: "This feature is currently an opt-in experiment, subject to change in future releases based on feedback.\n\nActivate the feature for this module by adding resource_for_each to the list of active experiments.", - Subject: rc.ForEach.Range().Ptr(), - }) - } - } - } - */ - - if !m.ActiveExperiments.Has(experiments.VariableValidation) { - for _, vc := range m.Variables { - if len(vc.Validations) != 0 { - diags = diags.Append(&hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Custom variable validation is experimental", - Detail: "This feature is currently an opt-in experiment, subject to change in future releases based on feedback.\n\nActivate the feature for this module by adding variable_validation to the list of active experiments.", - Subject: vc.Validations[0].DeclRange.Ptr(), - }) - } - } - } - - return diags -} diff --git a/vendor/github.com/hashicorp/terraform/configs/provider_requirements.go b/vendor/github.com/hashicorp/terraform/configs/provider_requirements.go deleted file mode 100644 index f2a78e501c..0000000000 --- a/vendor/github.com/hashicorp/terraform/configs/provider_requirements.go +++ /dev/null @@ -1,82 +0,0 @@ -package configs - -import ( - version "github.com/hashicorp/go-version" - "github.com/hashicorp/hcl/v2" - "github.com/hashicorp/terraform/addrs" -) - -// RequiredProvider represents a declaration of a dependency on a particular -// provider version without actually configuring that provider. This is used in -// child modules that expect a provider to be passed in from their parent. -// -// TODO: "Source" is a placeholder for an attribute that is not yet supported. -type RequiredProvider struct { - Name string - Source string // TODO - Requirement VersionConstraint -} - -// ProviderRequirements represents merged provider version constraints. -// VersionConstraints come from terraform.require_providers blocks and provider -// blocks. -type ProviderRequirements struct { - Type addrs.Provider - VersionConstraints []VersionConstraint -} - -func decodeRequiredProvidersBlock(block *hcl.Block) ([]*RequiredProvider, hcl.Diagnostics) { - attrs, diags := block.Body.JustAttributes() - var reqs []*RequiredProvider - for name, attr := range attrs { - expr, err := attr.Expr.Value(nil) - if err != nil { - diags = append(diags, err...) - } - - switch { - case expr.Type().IsPrimitiveType(): - vc, reqDiags := decodeVersionConstraint(attr) - diags = append(diags, reqDiags...) - reqs = append(reqs, &RequiredProvider{ - Name: name, - Requirement: vc, - }) - case expr.Type().IsObjectType(): - if expr.Type().HasAttribute("version") { - vc := VersionConstraint{ - DeclRange: attr.Range, - } - constraintStr := expr.GetAttr("version").AsString() - constraints, err := version.NewConstraint(constraintStr) - if err != nil { - // NewConstraint doesn't return user-friendly errors, so we'll just - // ignore the provided error and produce our own generic one. - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid version constraint", - Detail: "This string does not use correct version constraint syntax.", - Subject: attr.Expr.Range().Ptr(), - }) - reqs = append(reqs, &RequiredProvider{Name: name}) - return reqs, diags - } - vc.Required = constraints - reqs = append(reqs, &RequiredProvider{Name: name, Requirement: vc}) - } - // No version - reqs = append(reqs, &RequiredProvider{Name: name}) - default: - // should not happen - diags = append(diags, &hcl.Diagnostic{ - Severity: hcl.DiagError, - Summary: "Invalid provider_requirements syntax", - Detail: "provider_requirements entries must be strings or objects.", - Subject: attr.Expr.Range().Ptr(), - }) - reqs = append(reqs, &RequiredProvider{Name: name}) - return reqs, diags - } - } - return reqs, diags -} diff --git a/vendor/github.com/hashicorp/terraform/experiments/doc.go b/vendor/github.com/hashicorp/terraform/experiments/doc.go deleted file mode 100644 index 5538d739c9..0000000000 --- a/vendor/github.com/hashicorp/terraform/experiments/doc.go +++ /dev/null @@ -1,9 +0,0 @@ -// Package experiments contains the models and logic for opt-in experiments -// that can be activated for a particular Terraform module. -// -// We use experiments to get feedback on new configuration language features -// in a way that permits breaking changes without waiting for a future minor -// release. Any feature behind an experiment flag is subject to change in any -// way in even a patch release, until we have enough confidence about the -// design of the feature to make compatibility commitments about it. -package experiments diff --git a/vendor/github.com/hashicorp/terraform/experiments/errors.go b/vendor/github.com/hashicorp/terraform/experiments/errors.go deleted file mode 100644 index a1fdc6f5c4..0000000000 --- a/vendor/github.com/hashicorp/terraform/experiments/errors.go +++ /dev/null @@ -1,26 +0,0 @@ -package experiments - -import ( - "fmt" -) - -// UnavailableError is the error type returned by GetCurrent when the requested -// experiment is not recognized at all. -type UnavailableError struct { - ExperimentName string -} - -func (e UnavailableError) Error() string { - return fmt.Sprintf("no current experiment is named %q", e.ExperimentName) -} - -// ConcludedError is the error type returned by GetCurrent when the requested -// experiment is recognized as concluded. -type ConcludedError struct { - ExperimentName string - Message string -} - -func (e ConcludedError) Error() string { - return fmt.Sprintf("experiment %q has concluded: %s", e.ExperimentName, e.Message) -} diff --git a/vendor/github.com/hashicorp/terraform/experiments/experiment.go b/vendor/github.com/hashicorp/terraform/experiments/experiment.go deleted file mode 100644 index 037b34e732..0000000000 --- a/vendor/github.com/hashicorp/terraform/experiments/experiment.go +++ /dev/null @@ -1,93 +0,0 @@ -package experiments - -// Experiment represents a particular experiment, which can be activated -// independently of all other experiments. -type Experiment string - -// All active and defunct experiments must be represented by constants whose -// internal string values are unique. -// -// Each of these declared constants must also be registered as either a -// current or a defunct experiment in the init() function below. -// -// Each experiment is represented by a string that must be a valid HCL -// identifier so that it can be specified in configuration. -const ( - VariableValidation = Experiment("variable_validation") -) - -func init() { - // Each experiment constant defined above must be registered here as either - // a current or a concluded experiment. - registerCurrentExperiment(VariableValidation) -} - -// GetCurrent takes an experiment name and returns the experiment value -// representing that expression if and only if it is a current experiment. -// -// If the selected experiment is concluded, GetCurrent will return an -// error of type ConcludedError whose message hopefully includes some guidance -// for users of the experiment on how to migrate to a stable feature that -// succeeded it. -// -// If the selected experiment is not known at all, GetCurrent will return an -// error of type UnavailableError. -func GetCurrent(name string) (Experiment, error) { - exp := Experiment(name) - if currentExperiments.Has(exp) { - return exp, nil - } - - if msg, concluded := concludedExperiments[exp]; concluded { - return Experiment(""), ConcludedError{ExperimentName: name, Message: msg} - } - - return Experiment(""), UnavailableError{ExperimentName: name} -} - -// Keyword returns the keyword that would be used to activate this experiment -// in the configuration. -func (e Experiment) Keyword() string { - return string(e) -} - -// IsCurrent returns true if the receiver is considered a currently-selectable -// experiment. -func (e Experiment) IsCurrent() bool { - return currentExperiments.Has(e) -} - -// IsConcluded returns true if the receiver is a concluded experiment. -func (e Experiment) IsConcluded() bool { - _, exists := concludedExperiments[e] - return exists -} - -// currentExperiments are those which are available to activate in the current -// version of Terraform. -// -// Members of this set are registered in the init function above. -var currentExperiments = make(Set) - -// concludedExperiments are those which were available to activate in an earlier -// version of Terraform but are no longer available, either because the feature -// in question has been implemented or because the experiment failed and the -// feature was abandoned. Each experiment maps to a message describing the -// outcome, so we can give users feedback about what they might do in modules -// using concluded experiments. -// -// After an experiment has been concluded for a whole major release span it can -// be removed, since we expect users to perform upgrades one major release at -// at time without skipping and thus they will see the concludedness error -// message as they upgrade through a prior major version. -// -// Members of this map are registered in the init function above. -var concludedExperiments = make(map[Experiment]string) - -func registerCurrentExperiment(exp Experiment) { - currentExperiments.Add(exp) -} - -func registerConcludedExperiment(exp Experiment, message string) { - concludedExperiments[exp] = message -} diff --git a/vendor/github.com/hashicorp/terraform/experiments/set.go b/vendor/github.com/hashicorp/terraform/experiments/set.go deleted file mode 100644 index 8247e212b5..0000000000 --- a/vendor/github.com/hashicorp/terraform/experiments/set.go +++ /dev/null @@ -1,46 +0,0 @@ -package experiments - -// Set is a collection of experiments where every experiment is either a member -// or not. -type Set map[Experiment]struct{} - -// NewSet constructs a new Set with the given experiments as its initial members. -func NewSet(exps ...Experiment) Set { - ret := make(Set) - for _, exp := range exps { - ret.Add(exp) - } - return ret -} - -// SetUnion constructs a new Set containing the members of all of the given -// sets. -func SetUnion(sets ...Set) Set { - ret := make(Set) - for _, set := range sets { - for exp := range set { - ret.Add(exp) - } - } - return ret -} - -// Add inserts the given experiment into the set. -// -// If the given experiment is already present then this is a no-op. -func (s Set) Add(exp Experiment) { - s[exp] = struct{}{} -} - -// Remove takes the given experiment out of the set. -// -// If the given experiment not already present then this is a no-op. -func (s Set) Remove(exp Experiment) { - delete(s, exp) -} - -// Has tests whether the given experiment is in the receiving set. -func (s Set) Has(exp Experiment) bool { - _, ok := s[exp] - return ok -} diff --git a/vendor/github.com/hashicorp/terraform/experiments/testing.go b/vendor/github.com/hashicorp/terraform/experiments/testing.go deleted file mode 100644 index 54ff2dfdee..0000000000 --- a/vendor/github.com/hashicorp/terraform/experiments/testing.go +++ /dev/null @@ -1,33 +0,0 @@ -package experiments - -import ( - "testing" -) - -// OverrideForTesting temporarily overrides the global tables -// of experiments in order to allow for a predictable set when unit testing -// the experiments infrastructure code. -// -// The correct way to use this function is to defer a call to its result so -// that the original tables can be restored at the conclusion of the calling -// test: -// -// defer experiments.OverrideForTesting(t, current, concluded)() -// -// This function modifies global variables that are normally fixed throughout -// our execution, so this function must not be called from non-test code and -// any test using it cannot safely run concurrently with other tests. -func OverrideForTesting(t *testing.T, current Set, concluded map[Experiment]string) func() { - // We're not currently using the given *testing.T in here, but we're - // requiring it anyway in case we might need it in future, and because - // it hopefully reinforces that only test code should be calling this. - - realCurrents := currentExperiments - realConcludeds := concludedExperiments - currentExperiments = current - concludedExperiments = concluded - return func() { - currentExperiments = realCurrents - concludedExperiments = realConcludeds - } -} diff --git a/vendor/github.com/hashicorp/terraform/helper/logging/indent.go b/vendor/github.com/hashicorp/terraform/helper/logging/indent.go deleted file mode 100644 index e0da0d7c73..0000000000 --- a/vendor/github.com/hashicorp/terraform/helper/logging/indent.go +++ /dev/null @@ -1,23 +0,0 @@ -package logging - -import ( - "strings" -) - -// Indent adds two spaces to the beginning of each line of the given string, -// with the goal of making the log level filter understand it as a line -// continuation rather than possibly as new log lines. -func Indent(s string) string { - var b strings.Builder - for len(s) > 0 { - end := strings.IndexByte(s, '\n') - if end == -1 { - end = len(s) - 1 - } - var l string - l, s = s[:end+1], s[end+1:] - b.WriteString(" ") - b.WriteString(l) - } - return b.String() -} diff --git a/vendor/github.com/hashicorp/terraform/helper/logging/level.go b/vendor/github.com/hashicorp/terraform/helper/logging/level.go deleted file mode 100644 index 0dc4dfe8d5..0000000000 --- a/vendor/github.com/hashicorp/terraform/helper/logging/level.go +++ /dev/null @@ -1,159 +0,0 @@ -package logging - -import ( - "bytes" - "io" - "sync" -) - -// LogLevel is a special string, conventionally written all in uppercase, that -// can be used to mark a log line for filtering and to specify filtering -// levels in the LevelFilter type. -type LogLevel string - -// LevelFilter is an io.Writer that can be used with a logger that -// will attempt to filter out log messages that aren't at least a certain -// level. -// -// This filtering is HEURISTIC-BASED, and so will not be 100% reliable. The -// assumptions it makes are: -// -// - Individual log messages are never split across multiple calls to the -// Write method. -// -// - Messages that carry levels are marked by a sequence starting with "[", -// then the level name string, and then "]". Any message without a sequence -// like this is an un-levelled message, and is not subject to filtering. -// -// - Each \n-delimited line in a write is a separate log message, unless a -// line starts with at least one space in which case it is interpreted -// as a continuation of the previous line. -// -// - If a log line starts with a non-whitespace character that isn't a digit -// then it's recognized as a degenerate continuation, because "real" log -// lines should start with a date/time and thus always have a leading -// digit. (This also cleans up after some situations where the assumptuion -// that messages arrive atomically aren't met, which is sadly sometimes -// true for longer messages that trip over some buffering behavior in -// panicwrap.) -// -// Because logging is a cross-cutting concern and not fully under the control -// of Terraform itself, there will certainly be cases where the above -// heuristics will fail. For example, it is likely that LevelFilter will -// occasionally misinterpret a continuation line as a new message because the -// code generating it doesn't know about our indentation convention. -// -// Our goal here is just to make a best effort to reduce the log volume, -// accepting that the results will not be 100% correct. -// -// Logging calls within Terraform Core should follow the above conventions so -// that the log output is broadly correct, however. -// -// Once the filter is in use somewhere, it is not safe to modify -// the structure. -type LevelFilter struct { - // Levels is the list of log levels, in increasing order of - // severity. Example might be: {"DEBUG", "WARN", "ERROR"}. - Levels []LogLevel - - // MinLevel is the minimum level allowed through - MinLevel LogLevel - - // The underlying io.Writer where log messages that pass the filter - // will be set. - Writer io.Writer - - badLevels map[LogLevel]struct{} - show bool - once sync.Once -} - -// Check will check a given line if it would be included in the level -// filter. -func (f *LevelFilter) Check(line []byte) bool { - f.once.Do(f.init) - - // Check for a log level - var level LogLevel - x := bytes.IndexByte(line, '[') - if x >= 0 { - y := bytes.IndexByte(line[x:], ']') - if y >= 0 { - level = LogLevel(line[x+1 : x+y]) - } - } - - //return level == "" - - _, ok := f.badLevels[level] - return !ok -} - -// Write is a specialized implementation of io.Writer suitable for being -// the output of a logger from the "log" package. -// -// This Writer implementation assumes that it will only recieve byte slices -// containing one or more entire lines of log output, each one terminated by -// a newline. This is compatible with the behavior of the "log" package -// directly, and is also tolerant of intermediaries that might buffer multiple -// separate writes together, as long as no individual log line is ever -// split into multiple slices. -// -// Behavior is undefined if any log line is split across multiple writes or -// written without a trailing '\n' delimiter. -func (f *LevelFilter) Write(p []byte) (n int, err error) { - for len(p) > 0 { - // Split at the first \n, inclusive - idx := bytes.IndexByte(p, '\n') - if idx == -1 { - // Invalid, undelimited write. We'll tolerate it assuming that - // our assumptions are being violated, but the results may be - // non-ideal. - idx = len(p) - 1 - break - } - var l []byte - l, p = p[:idx+1], p[idx+1:] - // Lines starting with characters other than decimal digits (including - // whitespace) are assumed to be continuations lines. This is an - // imprecise heuristic, but experimentally it seems to generate - // "good enough" results from Terraform Core's own logging. Its mileage - // may vary with output from other systems. - if l[0] >= '0' && l[0] <= '9' { - f.show = f.Check(l) - } - if f.show { - _, err = f.Writer.Write(l) - if err != nil { - // Technically it's not correct to say we've written the whole - // buffer, but for our purposes here it's good enough as we're - // only implementing io.Writer enough to satisfy logging - // use-cases. - return len(p), err - } - } - } - - // We always behave as if we wrote the whole of the buffer, even if - // we actually skipped some lines. We're only implementiong io.Writer - // enough to satisfy logging use-cases. - return len(p), nil -} - -// SetMinLevel is used to update the minimum log level -func (f *LevelFilter) SetMinLevel(min LogLevel) { - f.MinLevel = min - f.init() -} - -func (f *LevelFilter) init() { - badLevels := make(map[LogLevel]struct{}) - for _, level := range f.Levels { - if level == f.MinLevel { - break - } - badLevels[level] = struct{}{} - } - f.badLevels = badLevels - f.show = true -} diff --git a/vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go b/vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go deleted file mode 100644 index 06f3d52cc0..0000000000 --- a/vendor/github.com/hashicorp/terraform/tfdiags/consolidate_warnings.go +++ /dev/null @@ -1,146 +0,0 @@ -package tfdiags - -import "fmt" - -// ConsolidateWarnings checks if there is an unreasonable amount of warnings -// with the same summary in the receiver and, if so, returns a new diagnostics -// with some of those warnings consolidated into a single warning in order -// to reduce the verbosity of the output. -// -// This mechanism is here primarily for diagnostics printed out at the CLI. In -// other contexts it is likely better to just return the warnings directly, -// particularly if they are going to be interpreted by software rather than -// by a human reader. -// -// The returned slice always has a separate backing array from the reciever, -// but some diagnostic values themselves might be shared. -// -// The definition of "unreasonable" is given as the threshold argument. At most -// that many warnings with the same summary will be shown. -func (diags Diagnostics) ConsolidateWarnings(threshold int) Diagnostics { - if len(diags) == 0 { - return nil - } - - newDiags := make(Diagnostics, 0, len(diags)) - - // We'll track how many times we've seen each warning summary so we can - // decide when to start consolidating. Once we _have_ started consolidating, - // we'll also track the object representing the consolidated warning - // so we can continue appending to it. - warningStats := make(map[string]int) - warningGroups := make(map[string]*warningGroup) - - for _, diag := range diags { - severity := diag.Severity() - if severity != Warning || diag.Source().Subject == nil { - // Only warnings can get special treatment, and we only - // consolidate warnings that have source locations because - // our primary goal here is to deal with the situation where - // some configuration language feature is producing a warning - // each time it's used across a potentially-large config. - newDiags = newDiags.Append(diag) - continue - } - - desc := diag.Description() - summary := desc.Summary - if g, ok := warningGroups[summary]; ok { - // We're already grouping this one, so we'll just continue it. - g.Append(diag) - continue - } - - warningStats[summary]++ - if warningStats[summary] == threshold { - // Initially creating the group doesn't really change anything - // visibly in the result, since a group with only one warning - // is just a passthrough anyway, but once we do this any additional - // warnings with the same summary will get appended to this group. - g := &warningGroup{} - newDiags = newDiags.Append(g) - warningGroups[summary] = g - g.Append(diag) - continue - } - - // If this warning is not consolidating yet then we'll just append - // it directly. - newDiags = newDiags.Append(diag) - } - - return newDiags -} - -// A warningGroup is one or more warning diagnostics grouped together for -// UI consolidation purposes. -// -// A warningGroup with only one diagnostic in it is just a passthrough for -// that one diagnostic. If it has more than one then it will behave mostly -// like the first one but its detail message will include an additional -// sentence mentioning the consolidation. A warningGroup with no diagnostics -// at all is invalid and will panic when used. -type warningGroup struct { - Warnings Diagnostics -} - -var _ Diagnostic = (*warningGroup)(nil) - -func (wg *warningGroup) Severity() Severity { - return wg.Warnings[0].Severity() -} - -func (wg *warningGroup) Description() Description { - desc := wg.Warnings[0].Description() - if len(wg.Warnings) < 2 { - return desc - } - extraCount := len(wg.Warnings) - 1 - var msg string - switch extraCount { - case 1: - msg = "(and one more similar warning elsewhere)" - default: - msg = fmt.Sprintf("(and %d more similar warnings elsewhere)", extraCount) - } - if desc.Detail != "" { - desc.Detail = desc.Detail + "\n\n" + msg - } else { - desc.Detail = msg - } - return desc -} - -func (wg *warningGroup) Source() Source { - return wg.Warnings[0].Source() -} - -func (wg *warningGroup) FromExpr() *FromExpr { - return wg.Warnings[0].FromExpr() -} - -func (wg *warningGroup) Append(diag Diagnostic) { - if diag.Severity() != Warning { - panic("can't append a non-warning diagnostic to a warningGroup") - } - wg.Warnings = append(wg.Warnings, diag) -} - -// WarningGroupSourceRanges can be used in conjunction with -// Diagnostics.ConsolidateWarnings to recover the full set of original source -// locations from a consolidated warning. -// -// For convenience, this function accepts any diagnostic and will just return -// the single Source value from any diagnostic that isn't a warning group. -func WarningGroupSourceRanges(diag Diagnostic) []Source { - wg, ok := diag.(*warningGroup) - if !ok { - return []Source{diag.Source()} - } - - ret := make([]Source, len(wg.Warnings)) - for i, wrappedDiag := range wg.Warnings { - ret[i] = wrappedDiag.Source() - } - return ret -} diff --git a/vendor/modules.txt b/vendor/modules.txt index c7f697a417..85ff7862e1 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -73,7 +73,7 @@ github.com/google/go-cmp/cmp/internal/diff github.com/google/go-cmp/cmp/internal/flags github.com/google/go-cmp/cmp/internal/function github.com/google/go-cmp/cmp/internal/value -# github.com/google/go-github/v29 v29.0.2 +# github.com/google/go-github/v29 v29.0.3 github.com/google/go-github/v29/github # github.com/google/go-querystring v1.0.0 github.com/google/go-querystring/query From 531534aaa6bbe4a51f1b79ca03c0637cbae2e40c Mon Sep 17 00:00:00 2001 From: Ben F Date: Fri, 6 Mar 2020 09:18:52 +0000 Subject: [PATCH 6/7] Remove unneeded TLS dependency --- go.mod | 1 - go.sum | 1 - 2 files changed, 2 deletions(-) diff --git a/go.mod b/go.mod index 2f0fad1c11..516b35fdbd 100644 --- a/go.mod +++ b/go.mod @@ -4,7 +4,6 @@ require ( github.com/google/go-github/v29 v29.0.3 github.com/hashicorp/terraform-plugin-sdk v1.7.0 github.com/kylelemons/godebug v1.1.0 - github.com/terraform-providers/terraform-provider-tls v1.2.0 // indirect golang.org/x/oauth2 v0.0.0-20200107190931-bf48bf16ab8d ) diff --git a/go.sum b/go.sum index 9ee96b6341..9a7935321a 100644 --- a/go.sum +++ b/go.sum @@ -174,7 +174,6 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+ github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q= github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= -github.com/terraform-providers/terraform-provider-tls v1.2.0/go.mod h1:Mxe/v5u31LDW4m32O1z6Ursdh95dpc9Puq6otkYg7tU= github.com/ulikunitz/xz v0.5.5 h1:pFrO0lVpTBXLpYw+pnLj6TbvHuyjXMfjGeCwSqCVwok= github.com/ulikunitz/xz v0.5.5/go.mod h1:2bypXElzHzzJZwzH67Y6wb67pO62Rzfn7BSiF4ABRW8= github.com/vmihailenco/msgpack v3.3.3+incompatible/go.mod h1:fy3FlTQTDXWkZ7Bh6AcGMlsjHatGryHQYUTf1ShIgkk= From 6765427c9aaeb76434fa3dba62d6700f14aa110f Mon Sep 17 00:00:00 2001 From: Jeremy Udit Date: Thu, 19 Mar 2020 07:54:37 -0400 Subject: [PATCH 7/7] Fix Failing Team Tests --- github/resource_github_team_repository_test.go | 2 +- github/resource_github_team_test.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/github/resource_github_team_repository_test.go b/github/resource_github_team_repository_test.go index 6492bd498c..3b15a251ee 100644 --- a/github/resource_github_team_repository_test.go +++ b/github/resource_github_team_repository_test.go @@ -123,7 +123,7 @@ func testAccCheckGithubTeamRepositoryExists(n string, repository *github.Reposit } repo, _, err := conn.Teams.IsTeamRepoByID(context.TODO(), - repository.GetID(), + testAccProvider.Meta().(*Organization).id, teamId, testAccProvider.Meta().(*Organization).name, repoName) diff --git a/github/resource_github_team_test.go b/github/resource_github_team_test.go index cf7c71fcb0..e15ac831f6 100644 --- a/github/resource_github_team_test.go +++ b/github/resource_github_team_test.go @@ -146,7 +146,7 @@ func testAccCheckGithubTeamExists(n string, team *github.Team) resource.TestChec return unconvertibleIdErr(rs.Primary.ID, err) } - githubTeam, _, err := conn.Teams.GetTeamByID(context.TODO(), team.Organization.GetID(), id) + githubTeam, _, err := conn.Teams.GetTeamByID(context.TODO(), testAccProvider.Meta().(*Organization).id, id) if err != nil { return err }