From d42729e310a9a6be49dd71f79188cb0b60fa51a5 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Thu, 8 Dec 2022 08:59:31 +1300 Subject: [PATCH 01/19] feat: add new schema for check block resource under required_status_checks --- .../resource_github_branch_protection_v3.go | 22 +++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/github/resource_github_branch_protection_v3.go b/github/resource_github_branch_protection_v3.go index 5dc25746e2..16a25c6c2e 100644 --- a/github/resource_github_branch_protection_v3.go +++ b/github/resource_github_branch_protection_v3.go @@ -53,12 +53,30 @@ func resourceGithubBranchProtectionV3() *schema.Resource { Default: false, }, "contexts": { - Type: schema.TypeSet, - Optional: true, + Type: schema.TypeSet, + Optional: true, + Deprecated: "GitHub is deprecating the use of `contexts`. Use `check` blocks instead.", Elem: &schema.Schema{ Type: schema.TypeString, }, }, + "check": { + Type: schema.TypeList, + Optional: true, + Elem: &schema.Resource{ + Schema: map[string]*schema.Schema{ + "context": { + Type: schema.TypeString, + Required: true, + }, + "app_id": { + Type: schema.TypeInt, + Optional: true, + Default: nil, + }, + }, + }, + }, }, }, }, From 234cc258911fbd5feac5d371acff59ac9fafd2d7 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Thu, 8 Dec 2022 09:00:31 +1300 Subject: [PATCH 02/19] feat: iterate provided `check` blocks and build array of RequiredStatusCheck --- ...ource_github_branch_protection_v3_utils.go | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index 72dabc305b..1839538b47 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -193,6 +193,30 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC contexts := expandNestedSet(m, "contexts") rsc.Contexts = contexts + + // Iterate and parse checks + checks := m["check"].([]interface{}) + var rscChecks []*github.RequiredStatusCheck + for _, c := range checks { + chk := c.(map[string]interface{}) + + var cContext string + if cContext, ok = chk["context"].(string); !ok { + return nil, errors.New("could not parse 'context' for required_status_checks check") + } + var cAppId int + if cAppId, ok = chk["app_id"].(int); !ok { + log.Printf("[DEBUG] app_id value: %v", chk["app_id"].(int)) + return nil, errors.New("could not parse 'app_id' for required_status_checks check") + } + var rscAppId int64 + rscAppId = int64(cAppId) + rscChecks = append(rscChecks, &github.RequiredStatusCheck{ + Context: cContext, + AppID: &rscAppId, + }) + } + rsc.Checks = rscChecks } return rsc, nil } From b99d568c5364e46fa6e93b0661fad0f335b4690b Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Thu, 8 Dec 2022 10:46:30 +1300 Subject: [PATCH 03/19] feat: set default app_id to -1 --- github/resource_github_branch_protection_v3.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github/resource_github_branch_protection_v3.go b/github/resource_github_branch_protection_v3.go index 16a25c6c2e..f48e937bf1 100644 --- a/github/resource_github_branch_protection_v3.go +++ b/github/resource_github_branch_protection_v3.go @@ -72,7 +72,7 @@ func resourceGithubBranchProtectionV3() *schema.Resource { "app_id": { Type: schema.TypeInt, Optional: true, - Default: nil, + Default: -1, }, }, }, From f482da27862c7e4201f9f3bf4b5e9c580f454130 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Thu, 8 Dec 2022 11:07:23 +1300 Subject: [PATCH 04/19] feat: implement checks flattening for required status checks --- ...esource_github_branch_protection_v3_utils.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index 1839538b47..180b099ce9 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -46,10 +46,24 @@ func flattenAndSetRequiredStatusChecks(d *schema.ResourceData, protection *githu contexts = append(contexts, c) } + var checks []interface{} + for _, chk := range rsc.Checks { + chkMap := make(map[string]interface{}) + chkMap["context"] = chk.Context + chkMap["app_id"] = func() int { + if chk.AppID != nil { + return int(*chk.AppID) + } + return -1 + }() + checks = append(checks, chkMap) + } + return d.Set("required_status_checks", []interface{}{ map[string]interface{}{ "strict": rsc.Strict, "contexts": schema.NewSet(schema.HashString, contexts), + "check": checks, }, }) } @@ -209,8 +223,7 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC log.Printf("[DEBUG] app_id value: %v", chk["app_id"].(int)) return nil, errors.New("could not parse 'app_id' for required_status_checks check") } - var rscAppId int64 - rscAppId = int64(cAppId) + rscAppId := int64(cAppId) rscChecks = append(rscChecks, &github.RequiredStatusCheck{ Context: cContext, AppID: &rscAppId, From 1c32a526bbac9356c953baa9161797c1a0bae034 Mon Sep 17 00:00:00 2001 From: David Bain <97858950+david-bain@users.noreply.github.com> Date: Tue, 6 Dec 2022 05:38:33 +1100 Subject: [PATCH 05/19] Add resource github_app_installation_repositories (#1376) * Add resource github_app_installation_repositories This resource allows multiple repositories to be passed in; which greatly improves the performance of the resource compared to the single repository version when needing to control state of multiple app installations with multiple repos, required in larger organisations. The optimisation occurs as only a single call to get the list of repos is required per installation per read, regardless of the number of respositories being added. - Add resource_github_app_installation_repositories - Add tests * Update docs and link Co-authored-by: Keegan Campbell --- github/provider.go | 1 + ...ce_github_app_installation_repositories.go | 186 ++++++++++++++++++ ...thub_app_installation_repositories_test.go | 81 ++++++++ ...pp_installation_repositories.html.markdown | 57 ++++++ website/github.erb | 3 + 5 files changed, 328 insertions(+) create mode 100644 github/resource_github_app_installation_repositories.go create mode 100644 github/resource_github_app_installation_repositories_test.go create mode 100644 website/docs/r/app_installation_repositories.html.markdown diff --git a/github/provider.go b/github/provider.go index c8725c35df..ff739710b0 100644 --- a/github/provider.go +++ b/github/provider.go @@ -96,6 +96,7 @@ func Provider() terraform.ResourceProvider { "github_actions_repository_permissions": resourceGithubActionsRepositoryPermissions(), "github_actions_runner_group": resourceGithubActionsRunnerGroup(), "github_actions_secret": resourceGithubActionsSecret(), + "github_app_installation_repositories": resourceGithubAppInstallationRepositories(), "github_app_installation_repository": resourceGithubAppInstallationRepository(), "github_branch": resourceGithubBranch(), "github_branch_default": resourceGithubBranchDefault(), diff --git a/github/resource_github_app_installation_repositories.go b/github/resource_github_app_installation_repositories.go new file mode 100644 index 0000000000..f183e5986e --- /dev/null +++ b/github/resource_github_app_installation_repositories.go @@ -0,0 +1,186 @@ +package github + +import ( + "context" + "log" + "strconv" + + "github.com/google/go-github/v48/github" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func resourceGithubAppInstallationRepositories() *schema.Resource { + return &schema.Resource{ + Create: resourceGithubAppInstallationRepositoriesCreateOrUpdate, + Read: resourceGithubAppInstallationRepositoriesRead, + Update: resourceGithubAppInstallationRepositoriesCreateOrUpdate, + Delete: resourceGithubAppInstallationRepositoriesDelete, + Importer: &schema.ResourceImporter{ + State: schema.ImportStatePassthrough, + }, + + Schema: map[string]*schema.Schema{ + "installation_id": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "selected_repositories": { + Type: schema.TypeSet, + Elem: &schema.Schema{ + Type: schema.TypeString, + }, + Set: schema.HashString, + Required: true, + }, + }, + } +} + +func resourceGithubAppInstallationRepositoriesCreateOrUpdate(d *schema.ResourceData, meta interface{}) error { + installationIDString := d.Get("installation_id").(string) + selectedRepositories := d.Get("selected_repositories") + + client := meta.(*Owner).v3client + owner := meta.(*Owner).name + ctx := context.WithValue(context.Background(), ctxId, installationIDString) + + selectedRepositoryNames := []string{} + + names := selectedRepositories.(*schema.Set).List() + for _, name := range names { + selectedRepositoryNames = append(selectedRepositoryNames, name.(string)) + } + + currentReposNameIDs, instID, err := getAllAccessibleRepos(meta, installationIDString) + if err != nil { + return err + } + + // Add repos that are not in the current state on GitHub + for _, repoName := range selectedRepositoryNames { + if _, ok := currentReposNameIDs[repoName]; ok { + // If it already exists, remove it from the map so we can delete all that are left at the end + delete(currentReposNameIDs, repoName) + } else { + repo, _, err := client.Repositories.Get(ctx, owner, repoName) + if err != nil { + return err + } + repoID := repo.GetID() + log.Printf("[DEBUG]: Adding %v:%v to app installation %v", repoName, repoID, instID) + _, _, err = client.Apps.AddRepository(ctx, instID, repoID) + if err != nil { + return err + } + } + } + + // Remove repositories that existed on GitHub but not selectedRepositories + // There is a github limitation that means we can't remove the last repository from an installation. + // Therefore, we skip the first and delete the rest. The app will then need to be uninstalled via the GUI + // as there is no current API endpoint for [un]installation. Ensure there is at least one repository remaining. + if len(selectedRepositoryNames) >= 1 { + for repoName, repoID := range currentReposNameIDs { + log.Printf("[DEBUG]: Removing %v:%v from app installation %v", repoName, repoID, instID) + _, err = client.Apps.RemoveRepository(ctx, instID, repoID) + if err != nil { + return err + } + } + } + + d.SetId(installationIDString) + return resourceGithubAppInstallationRepositoriesRead(d, meta) +} + +func resourceGithubAppInstallationRepositoriesRead(d *schema.ResourceData, meta interface{}) error { + installationIDString := d.Id() + + reposNameIDs, _, err := getAllAccessibleRepos(meta, installationIDString) + if err != nil { + return err + } + + repoNames := []string{} + for name := range reposNameIDs { + repoNames = append(repoNames, name) + } + + if len(reposNameIDs) > 0 { + d.Set("installation_id", installationIDString) + d.Set("selected_repositories", repoNames) + return nil + } + + log.Printf("[INFO] Removing app installation repository association %s from state because it no longer exists in GitHub", + d.Id()) + d.SetId("") + return nil +} + +func resourceGithubAppInstallationRepositoriesDelete(d *schema.ResourceData, meta interface{}) error { + installationIDString := d.Get("installation_id").(string) + + reposNameIDs, instID, err := getAllAccessibleRepos(meta, installationIDString) + if err != nil { + return err + } + + client := meta.(*Owner).v3client + ctx := context.WithValue(context.Background(), ctxId, installationIDString) + + // There is a github limitation that means we can't remove the last repository from an installation. + // Therefore, we skip the first and delete the rest. The app will then need to be uninstalled via the GUI + // as there is no current API endpoint for [un]installation. + first := true + for repoName, repoID := range reposNameIDs { + if first { + first = false + log.Printf("[WARN]: Cannot remove %v:%v from app installation %v as there must remain at least one repository selected due to API limitations. Manually uninstall the app to remove.", repoName, repoID, instID) + continue + } else { + _, err = client.Apps.RemoveRepository(ctx, instID, repoID) + log.Printf("[DEBUG]: Removing %v:%v from app installation %v", repoName, repoID, instID) + if err != nil { + return err + } + } + } + return nil +} + +func getAllAccessibleRepos(meta interface{}, idString string) (map[string]int64, int64, error) { + err := checkOrganization(meta) + if err != nil { + return nil, 0, err + } + + installationID, err := strconv.ParseInt(idString, 10, 64) + if err != nil { + return nil, 0, unconvertibleIdErr(idString, err) + } + + ctx := context.WithValue(context.Background(), ctxId, idString) + opt := &github.ListOptions{PerPage: maxPerPage} + client := meta.(*Owner).v3client + + allRepos := make(map[string]int64) + + for { + repos, resp, err := client.Apps.ListUserRepos(ctx, installationID, opt) + if err != nil { + return nil, 0, err + } + for _, r := range repos.Repositories { + allRepos[r.GetName()] = r.GetID() + } + + if resp.NextPage == 0 { + break + } + opt.Page = resp.NextPage + } + + return allRepos, installationID, nil +} diff --git a/github/resource_github_app_installation_repositories_test.go b/github/resource_github_app_installation_repositories_test.go new file mode 100644 index 0000000000..4c3c361f2f --- /dev/null +++ b/github/resource_github_app_installation_repositories_test.go @@ -0,0 +1,81 @@ +package github + +import ( + "fmt" + "os" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func TestAccGithubAppInstallationRepositories(t *testing.T) { + + const APP_INSTALLATION_ID = "APP_INSTALLATION_ID" + randomID1 := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + randomID2 := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + installation_id, exists := os.LookupEnv(APP_INSTALLATION_ID) + + t.Run("installs an app to multiple repositories", func(t *testing.T) { + + if !exists { + t.Skipf("%s environment variable is missing", APP_INSTALLATION_ID) + } + + config := fmt.Sprintf(` + + resource "github_repository" "test1" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_repository" "test2" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_app_installation_repositories" "test" { + # The installation id of the app (in the organization). + installation_id = "%s" + selected_repositories = [github_repository.test1.name, github_repository.test2.name] + } + + `, randomID1, randomID2, installation_id) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttrSet( + "github_app_installation_repositories.test", "installation_id", + ), + resource.TestCheckResourceAttr( + "github_app_installation_repositories.test", "selected_repositories.#", "2", + ), + ) + + testCase := func(t *testing.T, mode string) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, mode) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + }, + }) + } + + t.Run("with an anonymous account", func(t *testing.T) { + t.Skip("anonymous account not supported for this operation") + }) + + t.Run("with an individual account", func(t *testing.T) { + t.Skip("individual account not supported for this operation") + }) + + t.Run("with an organization account", func(t *testing.T) { + testCase(t, organization) + }) + + }) + +} diff --git a/website/docs/r/app_installation_repositories.html.markdown b/website/docs/r/app_installation_repositories.html.markdown new file mode 100644 index 0000000000..f47e26419f --- /dev/null +++ b/website/docs/r/app_installation_repositories.html.markdown @@ -0,0 +1,57 @@ +--- +layout: "github" +page_title: "GitHub: github_app_installation_repository" +description: |- + Manages the associations between app installations and repositories. +--- + +# github_app_installation_repositories + +~> **Note**: This resource is not compatible with the GitHub App Installation authentication method. + +This resource manages relationships between app installations and repositories +in your GitHub organization. + +Creating this resource installs a particular app on multiple repositories. + +The app installation and the repositories must all belong to the same +organization on GitHub. Note: you can review your organization's installations +by the following the instructions at this +[link](https://docs.github.com/en/github/setting-up-and-managing-organizations-and-teams/reviewing-your-organizations-installed-integrations). + +## Example Usage + +```hcl +# Create some repositories. +resource "github_repository" "some_repo" { + name = "some-repo" +} + +resource "github_repository" "another_repo" { + name = "another-repo" +} + +resource "github_app_installation_repositories" "some_app_repos" { + # The installation id of the app (in the organization). + installation_id = "1234567" + selected_repository_ids = [github_repository.some_repo.name, github_repository.another_repo.name]" +} +``` + +## Argument Reference + +The following arguments are supported: + +* `installation_id` - (Required) The GitHub app installation id. +* `selected_repositories` - (Required) A list of repository names to install the app on. + +~> **Note**: Due to how GitHub implements app installations, apps cannot be installed with no repositories selected. Therefore deleting this resource will leave one repository with the app installed. Manually uninstall the app or set the installation to all repositories via the GUI as after deleting this resource. + +## Import + +GitHub App Installation Repository can be imported +using an ID made up of `installation_id:repository`, e.g. + +``` +$ terraform import github_app_installation_repository.terraform_repo 1234567:terraform +``` diff --git a/website/github.erb b/website/github.erb index 018f7f3c78..749b2d8ce8 100644 --- a/website/github.erb +++ b/website/github.erb @@ -133,6 +133,9 @@
  • github_actions_secret
  • +
  • + github_app_installation_repositories +
  • github_app_installation_repository
  • From e2dadad0fd7d152c311c921b1fbcb1ec416baea8 Mon Sep 17 00:00:00 2001 From: Sean Smith Date: Mon, 5 Dec 2022 11:48:33 -0800 Subject: [PATCH 06/19] feat: adds new branch protection options for last reviewer and locking branch (#1407) Co-authored-by: Keegan Campbell --- github/resource_github_branch_protection.go | 24 + .../resource_github_branch_protection_test.go | 10 + github/util_v4_branch_protection.go | 12 + github/util_v4_consts.go | 2 + go.mod | 2 +- go.sum | 2 + vendor/github.com/shurcooL/githubv4/enum.go | 269 ++++++++++- vendor/github.com/shurcooL/githubv4/input.go | 430 +++++++++++++++++- vendor/modules.txt | 2 +- .../docs/r/branch_protection.html.markdown | 4 +- 10 files changed, 720 insertions(+), 37 deletions(-) diff --git a/github/resource_github_branch_protection.go b/github/resource_github_branch_protection.go index ed1d213813..a99e089ffa 100644 --- a/github/resource_github_branch_protection.go +++ b/github/resource_github_branch_protection.go @@ -63,6 +63,11 @@ func resourceGithubBranchProtection() *schema.Resource { Optional: true, Default: false, }, + PROTECTION_LOCK_BRANCH: { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, PROTECTION_REQUIRES_APPROVING_REVIEWS: { Type: schema.TypeList, Optional: true, @@ -96,6 +101,11 @@ func resourceGithubBranchProtection() *schema.Resource { Optional: true, Elem: &schema.Schema{Type: schema.TypeString}, }, + PROTECTION_REQUIRES_LAST_PUSH_APPROVAL: { + Type: schema.TypeBool, + Optional: true, + Default: false, + }, }, }, }, @@ -197,6 +207,8 @@ func resourceGithubBranchProtectionCreate(d *schema.ResourceData, meta interface RestrictsPushes: githubv4.NewBoolean(githubv4.Boolean(data.RestrictsPushes)), RestrictsReviewDismissals: githubv4.NewBoolean(githubv4.Boolean(data.RestrictsReviewDismissals)), ReviewDismissalActorIDs: githubv4NewIDSlice(githubv4IDSlice(data.ReviewDismissalActorIDs)), + LockBranch: githubv4.NewBoolean(githubv4.Boolean(data.LockBranch)), + RequireLastPushApproval: githubv4.NewBoolean(githubv4.Boolean(data.RequireLastPushApproval)), } ctx := context.Background() @@ -299,6 +311,16 @@ func resourceGithubBranchProtectionRead(d *schema.ResourceData, meta interface{} log.Printf("[DEBUG] Problem setting '%s' in %s %s branch protection (%s)", PROTECTION_RESTRICTS_PUSHES, protection.Repository.Name, protection.Pattern, d.Id()) } + err = d.Set(PROTECTION_REQUIRES_LAST_PUSH_APPROVAL, protection.RequireLastPushApproval) + if err != nil { + log.Printf("[DEBUG] Problem setting '%s' in %s %s branch protection (%s)", PROTECTION_REQUIRES_LAST_PUSH_APPROVAL, protection.Repository.Name, protection.Pattern, d.Id()) + } + + err = d.Set(PROTECTION_LOCK_BRANCH, protection.LockBranch) + if err != nil { + log.Printf("[DEBUG] Problem setting '%s' in %s %s branch protection (%s)", PROTECTION_LOCK_BRANCH, protection.Repository.Name, protection.Pattern, d.Id()) + } + return nil } @@ -357,6 +379,8 @@ func resourceGithubBranchProtectionUpdate(d *schema.ResourceData, meta interface RestrictsPushes: githubv4.NewBoolean(githubv4.Boolean(data.RestrictsPushes)), RestrictsReviewDismissals: githubv4.NewBoolean(githubv4.Boolean(data.RestrictsReviewDismissals)), ReviewDismissalActorIDs: githubv4NewIDSlice(githubv4IDSlice(data.ReviewDismissalActorIDs)), + LockBranch: githubv4.NewBoolean(githubv4.Boolean(data.LockBranch)), + RequireLastPushApproval: githubv4.NewBoolean(githubv4.Boolean(data.RequireLastPushApproval)), } ctx := context.WithValue(context.Background(), ctxId, d.Id()) diff --git a/github/resource_github_branch_protection_test.go b/github/resource_github_branch_protection_test.go index 91f1d22954..26c4df7d7e 100644 --- a/github/resource_github_branch_protection_test.go +++ b/github/resource_github_branch_protection_test.go @@ -51,6 +51,9 @@ func TestAccGithubBranchProtection(t *testing.T) { resource.TestCheckResourceAttr( "github_branch_protection.test", "push_restrictions.#", "0", ), + resource.TestCheckResourceAttr( + "github_branch_protection.test", "lock_branch", "false", + ), ) testCase := func(t *testing.T, mode string) { @@ -139,6 +142,9 @@ func TestAccGithubBranchProtection(t *testing.T) { resource.TestCheckResourceAttr( "github_branch_protection.test", "push_restrictions.#", "0", ), + resource.TestCheckResourceAttr( + "github_branch_protection.test", "lock_branch", "false", + ), ) testCase := func(t *testing.T, mode string) { @@ -275,6 +281,7 @@ func TestAccGithubBranchProtection(t *testing.T) { required_pull_request_reviews { dismiss_stale_reviews = true require_code_owner_reviews = true + require_last_push_approval = true } } @@ -294,6 +301,9 @@ func TestAccGithubBranchProtection(t *testing.T) { resource.TestCheckResourceAttr( "github_branch_protection.test", "required_pull_request_reviews.0.required_approving_review_count", "1", ), + resource.TestCheckResourceAttr( + "github_branch_protection.test", "required_pull_request_reviews.0.require_last_push_approval", "true", + ), ) testCase := func(t *testing.T, mode string) { diff --git a/github/util_v4_branch_protection.go b/github/util_v4_branch_protection.go index 17d212a6e9..9ab951e582 100644 --- a/github/util_v4_branch_protection.go +++ b/github/util_v4_branch_protection.go @@ -76,6 +76,8 @@ type BranchProtectionRule struct { RequiresStrictStatusChecks githubv4.Boolean RestrictsPushes githubv4.Boolean RestrictsReviewDismissals githubv4.Boolean + RequireLastPushApproval githubv4.Boolean + LockBranch githubv4.Boolean } type BranchProtectionResourceData struct { @@ -101,6 +103,8 @@ type BranchProtectionResourceData struct { RestrictsPushes bool RestrictsReviewDismissals bool ReviewDismissalActorIDs []string + RequireLastPushApproval bool + LockBranch bool } func branchProtectionResourceData(d *schema.ResourceData, meta interface{}) (BranchProtectionResourceData, error) { @@ -193,6 +197,9 @@ func branchProtectionResourceData(d *schema.ResourceData, meta interface{}) (Bra data.BypassPullRequestActorIDs = bypassPullRequestActorIDs } } + if v, ok := m[PROTECTION_REQUIRES_LAST_PUSH_APPROVAL]; ok { + data.RequireLastPushApproval = v.(bool) + } } } @@ -229,6 +236,10 @@ func branchProtectionResourceData(d *schema.ResourceData, meta interface{}) (Bra } } + if v, ok := d.GetOk(PROTECTION_LOCK_BRANCH); ok { + data.LockBranch = v.(bool) + } + return data, nil } @@ -387,6 +398,7 @@ func setApprovingReviews(protection BranchProtectionRule, data BranchProtectionR PROTECTION_RESTRICTS_REVIEW_DISMISSALS: protection.RestrictsReviewDismissals, PROTECTION_RESTRICTS_REVIEW_DISMISSERS: dismissalActors, PROTECTION_PULL_REQUESTS_BYPASSERS: bypassPullRequestActors, + PROTECTION_REQUIRES_LAST_PUSH_APPROVAL: protection.RequireLastPushApproval, }, } diff --git a/github/util_v4_consts.go b/github/util_v4_consts.go index c0d9ac209f..74540f9ab0 100644 --- a/github/util_v4_consts.go +++ b/github/util_v4_consts.go @@ -20,6 +20,8 @@ const ( PROTECTION_RESTRICTS_REVIEW_DISMISSALS = "restrict_dismissals" PROTECTION_RESTRICTS_REVIEW_DISMISSERS = "dismissal_restrictions" PROTECTION_PULL_REQUESTS_BYPASSERS = "pull_request_bypassers" + PROTECTION_LOCK_BRANCH = "lock_branch" + PROTECTION_REQUIRES_LAST_PUSH_APPROVAL = "require_last_push_approval" REPOSITORY_ID = "repository_id" ) diff --git a/go.mod b/go.mod index bb41084ef2..1d2dd3d44c 100644 --- a/go.mod +++ b/go.mod @@ -7,7 +7,7 @@ require ( github.com/golangci/golangci-lint v1.41.1 github.com/google/go-github/v48 v48.1.0 github.com/hashicorp/terraform-plugin-sdk v1.17.2 - github.com/shurcooL/githubv4 v0.0.0-20220520033151-0b4e3294ff00 + github.com/shurcooL/githubv4 v0.0.0-20221126192849-0b5c4c7994eb golang.org/x/crypto v0.3.0 golang.org/x/oauth2 v0.0.0-20220411215720-9780585627b5 gopkg.in/square/go-jose.v2 v2.6.0 diff --git a/go.sum b/go.sum index dbdbc493aa..33e35803fd 100644 --- a/go.sum +++ b/go.sum @@ -891,6 +891,8 @@ github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c/go.mod h1:/PevMnwAx github.com/shirou/gopsutil/v3 v3.21.5/go.mod h1:ghfMypLDrFSWN2c9cDYFLHyynQ+QUht0cv/18ZqVczw= github.com/shurcooL/githubv4 v0.0.0-20220520033151-0b4e3294ff00 h1:fiFvD4lT0aWjuuAb64LlZ/67v87m+Kc9Qsu5cMFNK0w= github.com/shurcooL/githubv4 v0.0.0-20220520033151-0b4e3294ff00/go.mod h1:hAF0iLZy4td2EX+/8Tw+4nodhlMrwN3HupfaXj3zkGo= +github.com/shurcooL/githubv4 v0.0.0-20221126192849-0b5c4c7994eb h1:foJysa74+t41fG7adnt+TkfcNxQUWid8R/HlXe+Mmbw= +github.com/shurcooL/githubv4 v0.0.0-20221126192849-0b5c4c7994eb/go.mod h1:hAF0iLZy4td2EX+/8Tw+4nodhlMrwN3HupfaXj3zkGo= github.com/shurcooL/go v0.0.0-20180423040247-9e1955d9fb6e/go.mod h1:TDJrrUr11Vxrven61rcy3hJMUqaf/CLWYhHNPmT14Lk= github.com/shurcooL/go-goon v0.0.0-20170922171312-37c2f522c041/go.mod h1:N5mDOmsrJOB+vfqUK+7DmDyjhSLIIBnXo9lvZJj3MWQ= github.com/shurcooL/graphql v0.0.0-20220606043923-3cf50f8a0a29 h1:B1PEwpArrNp4dkQrfxh/abbBAOZBVp0ds+fBEOUOqOc= diff --git a/vendor/github.com/shurcooL/githubv4/enum.go b/vendor/github.com/shurcooL/githubv4/enum.go index a31baf1ecb..a17ae2762f 100644 --- a/vendor/github.com/shurcooL/githubv4/enum.go +++ b/vendor/github.com/shurcooL/githubv4/enum.go @@ -45,6 +45,27 @@ const ( CheckConclusionStateStale CheckConclusionState = "STALE" // The check suite or run was marked stale by GitHub. Only GitHub can use this conclusion. ) +// CheckRunState represents the possible states of a check run in a status rollup. +type CheckRunState string + +// The possible states of a check run in a status rollup. +const ( + CheckRunStateActionRequired CheckRunState = "ACTION_REQUIRED" // The check run requires action. + CheckRunStateCancelled CheckRunState = "CANCELLED" // The check run has been cancelled. + CheckRunStateCompleted CheckRunState = "COMPLETED" // The check run has been completed. + CheckRunStateFailure CheckRunState = "FAILURE" // The check run has failed. + CheckRunStateInProgress CheckRunState = "IN_PROGRESS" // The check run is in progress. + CheckRunStateNeutral CheckRunState = "NEUTRAL" // The check run was neutral. + CheckRunStatePending CheckRunState = "PENDING" // The check run is in pending state. + CheckRunStateQueued CheckRunState = "QUEUED" // The check run has been queued. + CheckRunStateSkipped CheckRunState = "SKIPPED" // The check run was skipped. + CheckRunStateStale CheckRunState = "STALE" // The check run was marked stale by GitHub. Only GitHub can use this conclusion. + CheckRunStateStartupFailure CheckRunState = "STARTUP_FAILURE" // The check run has failed at startup. + CheckRunStateSuccess CheckRunState = "SUCCESS" // The check run has succeeded. + CheckRunStateTimedOut CheckRunState = "TIMED_OUT" // The check run has timed out. + CheckRunStateWaiting CheckRunState = "WAITING" // The check run is in waiting state. +) + // CheckRunType represents the possible types of check runs. type CheckRunType string @@ -115,6 +136,17 @@ const ( CommitContributionOrderFieldCommitCount CommitContributionOrderField = "COMMIT_COUNT" // Order commit contributions by how many commits they represent. ) +// ComparisonStatus represents the status of a git comparison between two refs. +type ComparisonStatus string + +// The status of a git comparison between two refs. +const ( + ComparisonStatusDiverged ComparisonStatus = "DIVERGED" // The head ref is both ahead and behind of the base ref, indicating git history has diverged. + ComparisonStatusAhead ComparisonStatus = "AHEAD" // The head ref is ahead of the base ref. + ComparisonStatusBehind ComparisonStatus = "BEHIND" // The head ref is behind the base ref. + ComparisonStatusIdentical ComparisonStatus = "IDENTICAL" // The head ref and base ref are identical. +) + // ContributionLevel represents varying levels of contributions from none to many. type ContributionLevel string @@ -151,6 +183,8 @@ const ( DependencyGraphEcosystemComposer DependencyGraphEcosystem = "COMPOSER" // PHP packages hosted at packagist.org. DependencyGraphEcosystemGo DependencyGraphEcosystem = "GO" // Go modules. DependencyGraphEcosystemActions DependencyGraphEcosystem = "ACTIONS" // GitHub Actions. + DependencyGraphEcosystemRust DependencyGraphEcosystem = "RUST" // Rust crates. + DependencyGraphEcosystemPub DependencyGraphEcosystem = "PUB" // Dart packages hosted at pub.dev. ) // DeploymentOrderField represents properties by which deployment connections can be ordered. @@ -229,6 +263,15 @@ const ( DiscussionOrderFieldUpdatedAt DiscussionOrderField = "UPDATED_AT" // Order discussions by most recent modification time. ) +// DiscussionPollOptionOrderField represents properties by which discussion poll option connections can be ordered. +type DiscussionPollOptionOrderField string + +// Properties by which discussion poll option connections can be ordered. +const ( + DiscussionPollOptionOrderFieldAuthoredOrder DiscussionPollOptionOrderField = "AUTHORED_ORDER" // Order poll options by the order that the poll author specified when creating the poll. + DiscussionPollOptionOrderFieldVoteCount DiscussionPollOptionOrderField = "VOTE_COUNT" // Order poll options by the number of votes it has. +) + // DismissReason represents the possible reasons that a Dependabot alert was dismissed. type DismissReason string @@ -258,6 +301,19 @@ const ( EnterpriseAdministratorRoleBillingManager EnterpriseAdministratorRole = "BILLING_MANAGER" // Represents a billing manager of the enterprise account. ) +// EnterpriseAllowPrivateRepositoryForkingPolicyValue represents the possible values for the enterprise allow private repository forking policy value. +type EnterpriseAllowPrivateRepositoryForkingPolicyValue string + +// The possible values for the enterprise allow private repository forking policy value. +const ( + EnterpriseAllowPrivateRepositoryForkingPolicyValueEnterpriseOrganizations EnterpriseAllowPrivateRepositoryForkingPolicyValue = "ENTERPRISE_ORGANIZATIONS" // Members can fork a repository to an organization within this enterprise. + EnterpriseAllowPrivateRepositoryForkingPolicyValueSameOrganization EnterpriseAllowPrivateRepositoryForkingPolicyValue = "SAME_ORGANIZATION" // Members can fork a repository only within the same organization (intra-org). + EnterpriseAllowPrivateRepositoryForkingPolicyValueSameOrganizationUserAccounts EnterpriseAllowPrivateRepositoryForkingPolicyValue = "SAME_ORGANIZATION_USER_ACCOUNTS" // Members can fork a repository to their user account or within the same organization. + EnterpriseAllowPrivateRepositoryForkingPolicyValueEnterpriseOrganizationsUserAccounts EnterpriseAllowPrivateRepositoryForkingPolicyValue = "ENTERPRISE_ORGANIZATIONS_USER_ACCOUNTS" // Members can fork a repository to their enterprise-managed user account or an organization inside this enterprise. + EnterpriseAllowPrivateRepositoryForkingPolicyValueUserAccounts EnterpriseAllowPrivateRepositoryForkingPolicyValue = "USER_ACCOUNTS" // Members can fork a repository to their user account. + EnterpriseAllowPrivateRepositoryForkingPolicyValueEverywhere EnterpriseAllowPrivateRepositoryForkingPolicyValue = "EVERYWHERE" // Members can fork a repository to their user account or an organization, either inside or outside of this enterprise. +) + // EnterpriseDefaultRepositoryPermissionSettingValue represents the possible values for the enterprise base repository permission setting. type EnterpriseDefaultRepositoryPermissionSettingValue string @@ -369,8 +425,9 @@ type EnterpriseUserAccountMembershipRole string // The possible roles for enterprise membership. const ( - EnterpriseUserAccountMembershipRoleMember EnterpriseUserAccountMembershipRole = "MEMBER" // The user is a member of the enterprise membership. - EnterpriseUserAccountMembershipRoleOwner EnterpriseUserAccountMembershipRole = "OWNER" // The user is an owner of the enterprise membership. + EnterpriseUserAccountMembershipRoleMember EnterpriseUserAccountMembershipRole = "MEMBER" // The user is a member of an organization in the enterprise. + EnterpriseUserAccountMembershipRoleOwner EnterpriseUserAccountMembershipRole = "OWNER" // The user is an owner of an organization in the enterprise. + EnterpriseUserAccountMembershipRoleUnaffiliated EnterpriseUserAccountMembershipRole = "UNAFFILIATED" // The user is not an owner of the enterprise, and not a member or owner of any organizations in the enterprise; only for EMU-enabled enterprises. ) // EnterpriseUserDeployment represents the possible GitHub Enterprise deployments where this user can exist. @@ -491,6 +548,15 @@ const ( IpAllowListForInstalledAppsEnabledSettingValueDisabled IpAllowListForInstalledAppsEnabledSettingValue = "DISABLED" // The setting is disabled for the owner. ) +// IssueClosedStateReason represents the possible state reasons of a closed issue. +type IssueClosedStateReason string + +// The possible state reasons of a closed issue. +const ( + IssueClosedStateReasonCompleted IssueClosedStateReason = "COMPLETED" // An issue that has been closed as completed. + IssueClosedStateReasonNotPlanned IssueClosedStateReason = "NOT_PLANNED" // An issue that has been closed as not planned. +) + // IssueCommentOrderField represents properties by which issue comment connections can be ordered. type IssueCommentOrderField string @@ -518,6 +584,16 @@ const ( IssueStateClosed IssueState = "CLOSED" // An issue that has been closed. ) +// IssueStateReason represents the possible state reasons of an issue. +type IssueStateReason string + +// The possible state reasons of an issue. +const ( + IssueStateReasonReopened IssueStateReason = "REOPENED" // An issue that has been reopened. + IssueStateReasonNotPlanned IssueStateReason = "NOT_PLANNED" // An issue that has been closed as not planned. + IssueStateReasonCompleted IssueStateReason = "COMPLETED" // An issue that has been closed as completed. +) + // IssueTimelineItemsItemType represents the possible item types found in a timeline. type IssueTimelineItemsItemType string @@ -584,6 +660,25 @@ const ( LockReasonSpam LockReason = "SPAM" // The issue or pull request was locked because the conversation was spam. ) +// MergeCommitMessage represents the possible default commit messages for merges. +type MergeCommitMessage string + +// The possible default commit messages for merges. +const ( + MergeCommitMessagePrTitle MergeCommitMessage = "PR_TITLE" // Default to the pull request's title. + MergeCommitMessagePrBody MergeCommitMessage = "PR_BODY" // Default to the pull request's body. + MergeCommitMessageBlank MergeCommitMessage = "BLANK" // Default to a blank commit message. +) + +// MergeCommitTitle represents the possible default commit titles for merges. +type MergeCommitTitle string + +// The possible default commit titles for merges. +const ( + MergeCommitTitlePrTitle MergeCommitTitle = "PR_TITLE" // Default to the pull request's title. + MergeCommitTitleMergeMessage MergeCommitTitle = "MERGE_MESSAGE" // Default to the classic title for a merge message (e.g., Merge pull request #123 from branch-name). +) + // MergeableState represents whether or not a PullRequest can be merged. type MergeableState string @@ -599,10 +694,8 @@ type MigrationSourceType string // Represents the different Octoshift migration sources. const ( - MigrationSourceTypeGitLab MigrationSourceType = "GITLAB" // A GitLab migration source. MigrationSourceTypeAzureDevOps MigrationSourceType = "AZURE_DEVOPS" // An Azure DevOps migration source. MigrationSourceTypeBitbucketServer MigrationSourceType = "BITBUCKET_SERVER" // A Bitbucket Server migration source. - MigrationSourceTypeGitHub MigrationSourceType = "GITHUB" // A GitHub migration source. MigrationSourceTypeGitHubArchive MigrationSourceType = "GITHUB_ARCHIVE" // A GitHub Migration API source. ) @@ -611,11 +704,13 @@ type MigrationState string // The Octoshift migration state. const ( - MigrationStateNotStarted MigrationState = "NOT_STARTED" // The Octoshift migration has not started. - MigrationStateQueued MigrationState = "QUEUED" // The Octoshift migration has been queued. - MigrationStateInProgress MigrationState = "IN_PROGRESS" // The Octoshift migration is in progress. - MigrationStateSucceeded MigrationState = "SUCCEEDED" // The Octoshift migration has succeeded. - MigrationStateFailed MigrationState = "FAILED" // The Octoshift migration has failed. + MigrationStateNotStarted MigrationState = "NOT_STARTED" // The Octoshift migration has not started. + MigrationStateQueued MigrationState = "QUEUED" // The Octoshift migration has been queued. + MigrationStateInProgress MigrationState = "IN_PROGRESS" // The Octoshift migration is in progress. + MigrationStateSucceeded MigrationState = "SUCCEEDED" // The Octoshift migration has succeeded. + MigrationStateFailed MigrationState = "FAILED" // The Octoshift migration has failed. + MigrationStatePendingValidation MigrationState = "PENDING_VALIDATION" // The Octoshift migration needs to have its credentials validated. + MigrationStateFailedValidation MigrationState = "FAILED_VALIDATION" // The Octoshift migration has invalid credentials. ) // MilestoneOrderField represents properties by which milestone connections can be ordered. @@ -732,6 +827,7 @@ type OrgRemoveMemberAuditEntryMembershipType string // The type of membership a user has with an Organization. const ( + OrgRemoveMemberAuditEntryMembershipTypeSuspended OrgRemoveMemberAuditEntryMembershipType = "SUSPENDED" // A suspended member. OrgRemoveMemberAuditEntryMembershipTypeDirectMember OrgRemoveMemberAuditEntryMembershipType = "DIRECT_MEMBER" // A direct member is a user that is a member of the Organization. OrgRemoveMemberAuditEntryMembershipTypeAdmin OrgRemoveMemberAuditEntryMembershipType = "ADMIN" // Organization administrators have full access and can change several settings, including the names of repositories that belong to the Organization and Owners team membership. In addition, organization admins can delete the organization and all of its repositories. OrgRemoveMemberAuditEntryMembershipTypeBillingManager OrgRemoveMemberAuditEntryMembershipType = "BILLING_MANAGER" // A billing manager is a user who manages the billing settings for the Organization, such as updating payment information. @@ -1003,6 +1099,7 @@ const ( ProjectNextFieldTypeDate ProjectNextFieldType = "DATE" // Date. ProjectNextFieldTypeIteration ProjectNextFieldType = "ITERATION" // Iteration. ProjectNextFieldTypeTracks ProjectNextFieldType = "TRACKS" // Tracks. + ProjectNextFieldTypeTrackedBy ProjectNextFieldType = "TRACKED_BY" // Tracked by. ) // ProjectNextOrderField represents properties by which the return project can be ordered. @@ -1046,6 +1143,103 @@ const ( ProjectTemplateBugTriage ProjectTemplate = "BUG_TRIAGE" // Create a board to triage and prioritize bugs with To do, priority, and Done columns. ) +// ProjectV2FieldOrderField represents properties by which project v2 field connections can be ordered. +type ProjectV2FieldOrderField string + +// Properties by which project v2 field connections can be ordered. +const ( + ProjectV2FieldOrderFieldPosition ProjectV2FieldOrderField = "POSITION" // Order project v2 fields by position. + ProjectV2FieldOrderFieldCreatedAt ProjectV2FieldOrderField = "CREATED_AT" // Order project v2 fields by creation time. + ProjectV2FieldOrderFieldName ProjectV2FieldOrderField = "NAME" // Order project v2 fields by name. +) + +// ProjectV2FieldType represents the type of a project field. +type ProjectV2FieldType string + +// The type of a project field. +const ( + ProjectV2FieldTypeAssignees ProjectV2FieldType = "ASSIGNEES" // Assignees. + ProjectV2FieldTypeLinkedPullRequests ProjectV2FieldType = "LINKED_PULL_REQUESTS" // Linked Pull Requests. + ProjectV2FieldTypeReviewers ProjectV2FieldType = "REVIEWERS" // Reviewers. + ProjectV2FieldTypeLabels ProjectV2FieldType = "LABELS" // Labels. + ProjectV2FieldTypeMilestone ProjectV2FieldType = "MILESTONE" // Milestone. + ProjectV2FieldTypeRepository ProjectV2FieldType = "REPOSITORY" // Repository. + ProjectV2FieldTypeTitle ProjectV2FieldType = "TITLE" // Title. + ProjectV2FieldTypeText ProjectV2FieldType = "TEXT" // Text. + ProjectV2FieldTypeSingleSelect ProjectV2FieldType = "SINGLE_SELECT" // Single Select. + ProjectV2FieldTypeNumber ProjectV2FieldType = "NUMBER" // Number. + ProjectV2FieldTypeDate ProjectV2FieldType = "DATE" // Date. + ProjectV2FieldTypeIteration ProjectV2FieldType = "ITERATION" // Iteration. + ProjectV2FieldTypeTracks ProjectV2FieldType = "TRACKS" // Tracks. + ProjectV2FieldTypeTrackedBy ProjectV2FieldType = "TRACKED_BY" // Tracked by. +) + +// ProjectV2ItemFieldValueOrderField represents properties by which project v2 item field value connections can be ordered. +type ProjectV2ItemFieldValueOrderField string + +// Properties by which project v2 item field value connections can be ordered. +const ( + ProjectV2ItemFieldValueOrderFieldPosition ProjectV2ItemFieldValueOrderField = "POSITION" // Order project v2 item field values by the their position in the project. +) + +// ProjectV2ItemOrderField represents properties by which project v2 item connections can be ordered. +type ProjectV2ItemOrderField string + +// Properties by which project v2 item connections can be ordered. +const ( + ProjectV2ItemOrderFieldPosition ProjectV2ItemOrderField = "POSITION" // Order project v2 items by the their position in the project. +) + +// ProjectV2ItemType represents the type of a project item. +type ProjectV2ItemType string + +// The type of a project item. +const ( + ProjectV2ItemTypeIssue ProjectV2ItemType = "ISSUE" // Issue. + ProjectV2ItemTypePullRequest ProjectV2ItemType = "PULL_REQUEST" // Pull Request. + ProjectV2ItemTypeDraftIssue ProjectV2ItemType = "DRAFT_ISSUE" // Draft Issue. + ProjectV2ItemTypeRedacted ProjectV2ItemType = "REDACTED" // Redacted Item. +) + +// ProjectV2OrderField represents properties by which projects can be ordered. +type ProjectV2OrderField string + +// Properties by which projects can be ordered. +const ( + ProjectV2OrderFieldTitle ProjectV2OrderField = "TITLE" // The project's title. + ProjectV2OrderFieldNumber ProjectV2OrderField = "NUMBER" // The project's number. + ProjectV2OrderFieldUpdatedAt ProjectV2OrderField = "UPDATED_AT" // The project's date and time of update. + ProjectV2OrderFieldCreatedAt ProjectV2OrderField = "CREATED_AT" // The project's date and time of creation. +) + +// ProjectV2State represents the possible states of a project v2. +type ProjectV2State string + +// The possible states of a project v2. +const ( + ProjectV2StateOpen ProjectV2State = "OPEN" // A project v2 that is still open. + ProjectV2StateClosed ProjectV2State = "CLOSED" // A project v2 that has been closed. +) + +// ProjectV2ViewLayout represents the layout of a project v2 view. +type ProjectV2ViewLayout string + +// The layout of a project v2 view. +const ( + ProjectV2ViewLayoutBoardLayout ProjectV2ViewLayout = "BOARD_LAYOUT" // Board layout. + ProjectV2ViewLayoutTableLayout ProjectV2ViewLayout = "TABLE_LAYOUT" // Table layout. +) + +// ProjectV2ViewOrderField represents properties by which project v2 view connections can be ordered. +type ProjectV2ViewOrderField string + +// Properties by which project v2 view connections can be ordered. +const ( + ProjectV2ViewOrderFieldPosition ProjectV2ViewOrderField = "POSITION" // Order project v2 views by position. + ProjectV2ViewOrderFieldCreatedAt ProjectV2ViewOrderField = "CREATED_AT" // Order project v2 views by creation time. + ProjectV2ViewOrderFieldName ProjectV2ViewOrderField = "NAME" // Order project v2 views by name. +) + // ProjectViewLayout represents the layout of a project view. type ProjectViewLayout string @@ -1458,6 +1652,15 @@ const ( RepositoryVisibilityInternal RepositoryVisibility = "INTERNAL" // The repository is visible only to users in the same business. ) +// RepositoryVulnerabilityAlertDependencyScope represents the possible scopes of an alert's dependency. +type RepositoryVulnerabilityAlertDependencyScope string + +// The possible scopes of an alert's dependency. +const ( + RepositoryVulnerabilityAlertDependencyScopeRuntime RepositoryVulnerabilityAlertDependencyScope = "RUNTIME" // A dependency that is leveraged during application runtime. + RepositoryVulnerabilityAlertDependencyScopeDevelopment RepositoryVulnerabilityAlertDependencyScope = "DEVELOPMENT" // A dependency that is only used in development. +) + // RepositoryVulnerabilityAlertState represents the possible states of an alert. type RepositoryVulnerabilityAlertState string @@ -1531,17 +1734,29 @@ const ( SearchTypeDiscussion SearchType = "DISCUSSION" // Returns matching discussions in repositories. ) +// SecurityAdvisoryClassification represents classification of the advisory. +type SecurityAdvisoryClassification string + +// Classification of the advisory. +const ( + SecurityAdvisoryClassificationGeneral SecurityAdvisoryClassification = "GENERAL" // Classification of general advisories. + SecurityAdvisoryClassificationMalware SecurityAdvisoryClassification = "MALWARE" // Classification of malware advisories. +) + // SecurityAdvisoryEcosystem represents the possible ecosystems of a security vulnerability's package. type SecurityAdvisoryEcosystem string // The possible ecosystems of a security vulnerability's package. const ( SecurityAdvisoryEcosystemComposer SecurityAdvisoryEcosystem = "COMPOSER" // PHP packages hosted at packagist.org. + SecurityAdvisoryEcosystemErlang SecurityAdvisoryEcosystem = "ERLANG" // Erlang/Elixir packages hosted at hex.pm. + SecurityAdvisoryEcosystemActions SecurityAdvisoryEcosystem = "ACTIONS" // GitHub Actions. SecurityAdvisoryEcosystemGo SecurityAdvisoryEcosystem = "GO" // Go modules. SecurityAdvisoryEcosystemMaven SecurityAdvisoryEcosystem = "MAVEN" // Java artifacts hosted at the Maven central repository. SecurityAdvisoryEcosystemNpm SecurityAdvisoryEcosystem = "NPM" // JavaScript packages hosted at npmjs.com. SecurityAdvisoryEcosystemNuget SecurityAdvisoryEcosystem = "NUGET" // .NET packages hosted at the NuGet Gallery. SecurityAdvisoryEcosystemPip SecurityAdvisoryEcosystem = "PIP" // Python packages hosted at PyPI.org. + SecurityAdvisoryEcosystemPub SecurityAdvisoryEcosystem = "PUB" // Dart packages hosted at pub.dev. SecurityAdvisoryEcosystemRubygems SecurityAdvisoryEcosystem = "RUBYGEMS" // Ruby gems hosted at RubyGems.org. SecurityAdvisoryEcosystemRust SecurityAdvisoryEcosystem = "RUST" // Rust crates. ) @@ -1641,6 +1856,15 @@ const ( SponsorsGoalKindMonthlySponsorshipAmount SponsorsGoalKind = "MONTHLY_SPONSORSHIP_AMOUNT" // The goal is about getting a certain amount in USD from sponsorships each month. ) +// SponsorsListingFeaturedItemFeatureableType represents the different kinds of records that can be featured on a GitHub Sponsors profile page. +type SponsorsListingFeaturedItemFeatureableType string + +// The different kinds of records that can be featured on a GitHub Sponsors profile page. +const ( + SponsorsListingFeaturedItemFeatureableTypeRepository SponsorsListingFeaturedItemFeatureableType = "REPOSITORY" // A repository owned by the user or organization with the GitHub Sponsors profile. + SponsorsListingFeaturedItemFeatureableTypeUser SponsorsListingFeaturedItemFeatureableType = "USER" // A user who belongs to the organization with the GitHub Sponsors profile. +) + // SponsorsTierOrderField represents properties by which Sponsors tiers connections can be ordered. type SponsorsTierOrderField string @@ -1675,6 +1899,25 @@ const ( SponsorshipPrivacyPrivate SponsorshipPrivacy = "PRIVATE" // Private. ) +// SquashMergeCommitMessage represents the possible default commit messages for squash merges. +type SquashMergeCommitMessage string + +// The possible default commit messages for squash merges. +const ( + SquashMergeCommitMessagePrBody SquashMergeCommitMessage = "PR_BODY" // Default to the pull request's body. + SquashMergeCommitMessageCommitMessages SquashMergeCommitMessage = "COMMIT_MESSAGES" // Default to the branch's commit messages. + SquashMergeCommitMessageBlank SquashMergeCommitMessage = "BLANK" // Default to a blank commit message. +) + +// SquashMergeCommitTitle represents the possible default commit titles for squash merges. +type SquashMergeCommitTitle string + +// The possible default commit titles for squash merges. +const ( + SquashMergeCommitTitlePrTitle SquashMergeCommitTitle = "PR_TITLE" // Default to the pull request's title. + SquashMergeCommitTitleCommitOrPrTitle SquashMergeCommitTitle = "COMMIT_OR_PR_TITLE" // Default to the commit's title (if only one commit) or the pull request's title (when more than one commit). +) + // StarOrderField represents properties by which star connections can be ordered. type StarOrderField string @@ -1836,3 +2079,11 @@ const ( VerifiableDomainOrderFieldDomain VerifiableDomainOrderField = "DOMAIN" // Order verifiable domains by the domain name. VerifiableDomainOrderFieldCreatedAt VerifiableDomainOrderField = "CREATED_AT" // Order verifiable domains by their creation date. ) + +// WorkflowRunOrderField represents properties by which workflow run connections can be ordered. +type WorkflowRunOrderField string + +// Properties by which workflow run connections can be ordered. +const ( + WorkflowRunOrderFieldCreatedAt WorkflowRunOrderField = "CREATED_AT" // Order workflow runs by most recently created. +) diff --git a/vendor/github.com/shurcooL/githubv4/input.go b/vendor/github.com/shurcooL/githubv4/input.go index 3433a25b70..be12348276 100644 --- a/vendor/github.com/shurcooL/githubv4/input.go +++ b/vendor/github.com/shurcooL/githubv4/input.go @@ -4,7 +4,7 @@ package githubv4 // Input represents one of the Input structs: // -// AbortQueuedMigrationsInput, AcceptEnterpriseAdministratorInvitationInput, AcceptTopicSuggestionInput, AddAssigneesToAssignableInput, AddCommentInput, AddDiscussionCommentInput, AddEnterpriseSupportEntitlementInput, AddLabelsToLabelableInput, AddProjectCardInput, AddProjectColumnInput, AddProjectDraftIssueInput, AddProjectNextItemInput, AddPullRequestReviewCommentInput, AddPullRequestReviewInput, AddPullRequestReviewThreadInput, AddReactionInput, AddStarInput, AddUpvoteInput, AddVerifiableDomainInput, ApproveDeploymentsInput, ApproveVerifiableDomainInput, ArchiveRepositoryInput, AuditLogOrder, CancelEnterpriseAdminInvitationInput, CancelSponsorshipInput, ChangeUserStatusInput, CheckAnnotationData, CheckAnnotationRange, CheckRunAction, CheckRunFilter, CheckRunOutput, CheckRunOutputImage, CheckSuiteAutoTriggerPreference, CheckSuiteFilter, ClearLabelsFromLabelableInput, CloneProjectInput, CloneTemplateRepositoryInput, CloseIssueInput, ClosePullRequestInput, CommitAuthor, CommitContributionOrder, CommitMessage, CommittableBranch, ContributionOrder, ConvertProjectCardNoteToIssueInput, ConvertPullRequestToDraftInput, CreateBranchProtectionRuleInput, CreateCheckRunInput, CreateCheckSuiteInput, CreateCommitOnBranchInput, CreateDiscussionInput, CreateEnterpriseOrganizationInput, CreateEnvironmentInput, CreateIpAllowListEntryInput, CreateIssueInput, CreateMigrationSourceInput, CreateProjectInput, CreatePullRequestInput, CreateRefInput, CreateRepositoryInput, CreateSponsorsTierInput, CreateSponsorshipInput, CreateTeamDiscussionCommentInput, CreateTeamDiscussionInput, DeclineTopicSuggestionInput, DeleteBranchProtectionRuleInput, DeleteDeploymentInput, DeleteDiscussionCommentInput, DeleteDiscussionInput, DeleteEnvironmentInput, DeleteIpAllowListEntryInput, DeleteIssueCommentInput, DeleteIssueInput, DeleteProjectCardInput, DeleteProjectColumnInput, DeleteProjectInput, DeleteProjectNextItemInput, DeletePullRequestReviewCommentInput, DeletePullRequestReviewInput, DeleteRefInput, DeleteTeamDiscussionCommentInput, DeleteTeamDiscussionInput, DeleteVerifiableDomainInput, DeploymentOrder, DisablePullRequestAutoMergeInput, DiscussionOrder, DismissPullRequestReviewInput, DismissRepositoryVulnerabilityAlertInput, DraftPullRequestReviewComment, DraftPullRequestReviewThread, EnablePullRequestAutoMergeInput, EnterpriseAdministratorInvitationOrder, EnterpriseMemberOrder, EnterpriseServerInstallationOrder, EnterpriseServerUserAccountEmailOrder, EnterpriseServerUserAccountOrder, EnterpriseServerUserAccountsUploadOrder, FileAddition, FileChanges, FileDeletion, FollowOrganizationInput, FollowUserInput, GistOrder, GrantEnterpriseOrganizationsMigratorRoleInput, GrantMigratorRoleInput, InviteEnterpriseAdminInput, IpAllowListEntryOrder, IssueCommentOrder, IssueFilters, IssueOrder, LabelOrder, LanguageOrder, LinkRepositoryToProjectInput, LockLockableInput, MarkDiscussionCommentAsAnswerInput, MarkFileAsViewedInput, MarkPullRequestReadyForReviewInput, MergeBranchInput, MergePullRequestInput, MilestoneOrder, MinimizeCommentInput, MoveProjectCardInput, MoveProjectColumnInput, OrgEnterpriseOwnerOrder, OrganizationOrder, PackageFileOrder, PackageOrder, PackageVersionOrder, PinIssueInput, ProjectOrder, PullRequestOrder, ReactionOrder, RefOrder, RegenerateEnterpriseIdentityProviderRecoveryCodesInput, RegenerateVerifiableDomainTokenInput, RejectDeploymentsInput, ReleaseOrder, RemoveAssigneesFromAssignableInput, RemoveEnterpriseAdminInput, RemoveEnterpriseIdentityProviderInput, RemoveEnterpriseOrganizationInput, RemoveEnterpriseSupportEntitlementInput, RemoveLabelsFromLabelableInput, RemoveOutsideCollaboratorInput, RemoveReactionInput, RemoveStarInput, RemoveUpvoteInput, ReopenIssueInput, ReopenPullRequestInput, RepositoryInvitationOrder, RepositoryMigrationOrder, RepositoryOrder, RequestReviewsInput, RequiredStatusCheckInput, RerequestCheckSuiteInput, ResolveReviewThreadInput, RevokeEnterpriseOrganizationsMigratorRoleInput, RevokeMigratorRoleInput, SavedReplyOrder, SecurityAdvisoryIdentifierFilter, SecurityAdvisoryOrder, SecurityVulnerabilityOrder, SetEnterpriseIdentityProviderInput, SetOrganizationInteractionLimitInput, SetRepositoryInteractionLimitInput, SetUserInteractionLimitInput, SponsorOrder, SponsorableOrder, SponsorsActivityOrder, SponsorsTierOrder, SponsorshipNewsletterOrder, SponsorshipOrder, StarOrder, StartRepositoryMigrationInput, SubmitPullRequestReviewInput, TeamDiscussionCommentOrder, TeamDiscussionOrder, TeamMemberOrder, TeamOrder, TeamRepositoryOrder, TransferIssueInput, UnarchiveRepositoryInput, UnfollowOrganizationInput, UnfollowUserInput, UnlinkRepositoryFromProjectInput, UnlockLockableInput, UnmarkDiscussionCommentAsAnswerInput, UnmarkFileAsViewedInput, UnmarkIssueAsDuplicateInput, UnminimizeCommentInput, UnpinIssueInput, UnresolveReviewThreadInput, UpdateBranchProtectionRuleInput, UpdateCheckRunInput, UpdateCheckSuitePreferencesInput, UpdateDiscussionCommentInput, UpdateDiscussionInput, UpdateEnterpriseAdministratorRoleInput, UpdateEnterpriseAllowPrivateRepositoryForkingSettingInput, UpdateEnterpriseDefaultRepositoryPermissionSettingInput, UpdateEnterpriseMembersCanChangeRepositoryVisibilitySettingInput, UpdateEnterpriseMembersCanCreateRepositoriesSettingInput, UpdateEnterpriseMembersCanDeleteIssuesSettingInput, UpdateEnterpriseMembersCanDeleteRepositoriesSettingInput, UpdateEnterpriseMembersCanInviteCollaboratorsSettingInput, UpdateEnterpriseMembersCanMakePurchasesSettingInput, UpdateEnterpriseMembersCanUpdateProtectedBranchesSettingInput, UpdateEnterpriseMembersCanViewDependencyInsightsSettingInput, UpdateEnterpriseOrganizationProjectsSettingInput, UpdateEnterpriseOwnerOrganizationRoleInput, UpdateEnterpriseProfileInput, UpdateEnterpriseRepositoryProjectsSettingInput, UpdateEnterpriseTeamDiscussionsSettingInput, UpdateEnterpriseTwoFactorAuthenticationRequiredSettingInput, UpdateEnvironmentInput, UpdateIpAllowListEnabledSettingInput, UpdateIpAllowListEntryInput, UpdateIpAllowListForInstalledAppsEnabledSettingInput, UpdateIssueCommentInput, UpdateIssueInput, UpdateNotificationRestrictionSettingInput, UpdateOrganizationAllowPrivateRepositoryForkingSettingInput, UpdateProjectCardInput, UpdateProjectColumnInput, UpdateProjectDraftIssueInput, UpdateProjectInput, UpdateProjectNextInput, UpdateProjectNextItemFieldInput, UpdatePullRequestBranchInput, UpdatePullRequestInput, UpdatePullRequestReviewCommentInput, UpdatePullRequestReviewInput, UpdateRefInput, UpdateRepositoryInput, UpdateSponsorshipPreferencesInput, UpdateSubscriptionInput, UpdateTeamDiscussionCommentInput, UpdateTeamDiscussionInput, UpdateTeamsRepositoryInput, UpdateTopicsInput, UserStatusOrder, VerifiableDomainOrder, VerifyVerifiableDomainInput. +// AbortQueuedMigrationsInput, AcceptEnterpriseAdministratorInvitationInput, AcceptTopicSuggestionInput, AddAssigneesToAssignableInput, AddCommentInput, AddDiscussionCommentInput, AddDiscussionPollVoteInput, AddEnterpriseOrganizationMemberInput, AddEnterpriseSupportEntitlementInput, AddLabelsToLabelableInput, AddProjectCardInput, AddProjectColumnInput, AddProjectDraftIssueInput, AddProjectNextItemInput, AddProjectV2DraftIssueInput, AddProjectV2ItemByIdInput, AddPullRequestReviewCommentInput, AddPullRequestReviewInput, AddPullRequestReviewThreadInput, AddReactionInput, AddStarInput, AddUpvoteInput, AddVerifiableDomainInput, ApproveDeploymentsInput, ApproveVerifiableDomainInput, ArchiveProjectV2ItemInput, ArchiveRepositoryInput, AuditLogOrder, CancelEnterpriseAdminInvitationInput, CancelSponsorshipInput, ChangeUserStatusInput, CheckAnnotationData, CheckAnnotationRange, CheckRunAction, CheckRunFilter, CheckRunOutput, CheckRunOutputImage, CheckSuiteAutoTriggerPreference, CheckSuiteFilter, ClearLabelsFromLabelableInput, ClearProjectV2ItemFieldValueInput, CloneProjectInput, CloneTemplateRepositoryInput, CloseIssueInput, ClosePullRequestInput, CommitAuthor, CommitContributionOrder, CommitMessage, CommittableBranch, ContributionOrder, ConvertProjectCardNoteToIssueInput, ConvertPullRequestToDraftInput, CreateBranchProtectionRuleInput, CreateCheckRunInput, CreateCheckSuiteInput, CreateCommitOnBranchInput, CreateDiscussionInput, CreateEnterpriseOrganizationInput, CreateEnvironmentInput, CreateIpAllowListEntryInput, CreateIssueInput, CreateLinkedBranchInput, CreateMigrationSourceInput, CreateProjectInput, CreateProjectV2Input, CreatePullRequestInput, CreateRefInput, CreateRepositoryInput, CreateSponsorsTierInput, CreateSponsorshipInput, CreateTeamDiscussionCommentInput, CreateTeamDiscussionInput, DeclineTopicSuggestionInput, DeleteBranchProtectionRuleInput, DeleteDeploymentInput, DeleteDiscussionCommentInput, DeleteDiscussionInput, DeleteEnvironmentInput, DeleteIpAllowListEntryInput, DeleteIssueCommentInput, DeleteIssueInput, DeleteLinkedBranchInput, DeleteProjectCardInput, DeleteProjectColumnInput, DeleteProjectInput, DeleteProjectNextItemInput, DeleteProjectV2ItemInput, DeletePullRequestReviewCommentInput, DeletePullRequestReviewInput, DeleteRefInput, DeleteTeamDiscussionCommentInput, DeleteTeamDiscussionInput, DeleteVerifiableDomainInput, DeploymentOrder, DisablePullRequestAutoMergeInput, DiscussionOrder, DiscussionPollOptionOrder, DismissPullRequestReviewInput, DismissRepositoryVulnerabilityAlertInput, DraftPullRequestReviewComment, DraftPullRequestReviewThread, EnablePullRequestAutoMergeInput, EnterpriseAdministratorInvitationOrder, EnterpriseMemberOrder, EnterpriseServerInstallationOrder, EnterpriseServerUserAccountEmailOrder, EnterpriseServerUserAccountOrder, EnterpriseServerUserAccountsUploadOrder, FileAddition, FileChanges, FileDeletion, FollowOrganizationInput, FollowUserInput, GistOrder, GrantEnterpriseOrganizationsMigratorRoleInput, GrantMigratorRoleInput, InviteEnterpriseAdminInput, IpAllowListEntryOrder, IssueCommentOrder, IssueFilters, IssueOrder, LabelOrder, LanguageOrder, LinkProjectV2ToRepositoryInput, LinkProjectV2ToTeamInput, LinkRepositoryToProjectInput, LockLockableInput, MarkDiscussionCommentAsAnswerInput, MarkFileAsViewedInput, MarkPullRequestReadyForReviewInput, MergeBranchInput, MergePullRequestInput, MilestoneOrder, MinimizeCommentInput, MoveProjectCardInput, MoveProjectColumnInput, OrgEnterpriseOwnerOrder, OrganizationOrder, PackageFileOrder, PackageOrder, PackageVersionOrder, PinIssueInput, ProjectOrder, ProjectV2FieldOrder, ProjectV2FieldValue, ProjectV2Filters, ProjectV2ItemFieldValueOrder, ProjectV2ItemOrder, ProjectV2Order, ProjectV2ViewOrder, PullRequestOrder, ReactionOrder, RefOrder, RegenerateEnterpriseIdentityProviderRecoveryCodesInput, RegenerateVerifiableDomainTokenInput, RejectDeploymentsInput, ReleaseOrder, RemoveAssigneesFromAssignableInput, RemoveEnterpriseAdminInput, RemoveEnterpriseIdentityProviderInput, RemoveEnterpriseOrganizationInput, RemoveEnterpriseSupportEntitlementInput, RemoveLabelsFromLabelableInput, RemoveOutsideCollaboratorInput, RemoveReactionInput, RemoveStarInput, RemoveUpvoteInput, ReopenIssueInput, ReopenPullRequestInput, RepositoryInvitationOrder, RepositoryMigrationOrder, RepositoryOrder, RequestReviewsInput, RequiredStatusCheckInput, RerequestCheckSuiteInput, ResolveReviewThreadInput, RevokeEnterpriseOrganizationsMigratorRoleInput, RevokeMigratorRoleInput, SavedReplyOrder, SecurityAdvisoryIdentifierFilter, SecurityAdvisoryOrder, SecurityVulnerabilityOrder, SetEnterpriseIdentityProviderInput, SetOrganizationInteractionLimitInput, SetRepositoryInteractionLimitInput, SetUserInteractionLimitInput, SponsorOrder, SponsorableOrder, SponsorsActivityOrder, SponsorsTierOrder, SponsorshipNewsletterOrder, SponsorshipOrder, StarOrder, StartRepositoryMigrationInput, SubmitPullRequestReviewInput, TeamDiscussionCommentOrder, TeamDiscussionOrder, TeamMemberOrder, TeamOrder, TeamRepositoryOrder, TransferEnterpriseOrganizationInput, TransferIssueInput, UnarchiveProjectV2ItemInput, UnarchiveRepositoryInput, UnfollowOrganizationInput, UnfollowUserInput, UnlinkProjectV2FromRepositoryInput, UnlinkProjectV2FromTeamInput, UnlinkRepositoryFromProjectInput, UnlockLockableInput, UnmarkDiscussionCommentAsAnswerInput, UnmarkFileAsViewedInput, UnmarkIssueAsDuplicateInput, UnminimizeCommentInput, UnpinIssueInput, UnresolveReviewThreadInput, UpdateBranchProtectionRuleInput, UpdateCheckRunInput, UpdateCheckSuitePreferencesInput, UpdateDiscussionCommentInput, UpdateDiscussionInput, UpdateEnterpriseAdministratorRoleInput, UpdateEnterpriseAllowPrivateRepositoryForkingSettingInput, UpdateEnterpriseDefaultRepositoryPermissionSettingInput, UpdateEnterpriseMembersCanChangeRepositoryVisibilitySettingInput, UpdateEnterpriseMembersCanCreateRepositoriesSettingInput, UpdateEnterpriseMembersCanDeleteIssuesSettingInput, UpdateEnterpriseMembersCanDeleteRepositoriesSettingInput, UpdateEnterpriseMembersCanInviteCollaboratorsSettingInput, UpdateEnterpriseMembersCanMakePurchasesSettingInput, UpdateEnterpriseMembersCanUpdateProtectedBranchesSettingInput, UpdateEnterpriseMembersCanViewDependencyInsightsSettingInput, UpdateEnterpriseOrganizationProjectsSettingInput, UpdateEnterpriseOwnerOrganizationRoleInput, UpdateEnterpriseProfileInput, UpdateEnterpriseRepositoryProjectsSettingInput, UpdateEnterpriseTeamDiscussionsSettingInput, UpdateEnterpriseTwoFactorAuthenticationRequiredSettingInput, UpdateEnvironmentInput, UpdateIpAllowListEnabledSettingInput, UpdateIpAllowListEntryInput, UpdateIpAllowListForInstalledAppsEnabledSettingInput, UpdateIssueCommentInput, UpdateIssueInput, UpdateNotificationRestrictionSettingInput, UpdateOrganizationAllowPrivateRepositoryForkingSettingInput, UpdateOrganizationWebCommitSignoffSettingInput, UpdateProjectCardInput, UpdateProjectColumnInput, UpdateProjectDraftIssueInput, UpdateProjectInput, UpdateProjectNextInput, UpdateProjectNextItemFieldInput, UpdateProjectV2DraftIssueInput, UpdateProjectV2Input, UpdateProjectV2ItemFieldValueInput, UpdateProjectV2ItemPositionInput, UpdatePullRequestBranchInput, UpdatePullRequestInput, UpdatePullRequestReviewCommentInput, UpdatePullRequestReviewInput, UpdateRefInput, UpdateRepositoryInput, UpdateRepositoryWebCommitSignoffSettingInput, UpdateSponsorshipPreferencesInput, UpdateSubscriptionInput, UpdateTeamDiscussionCommentInput, UpdateTeamDiscussionInput, UpdateTeamsRepositoryInput, UpdateTopicsInput, UserStatusOrder, VerifiableDomainOrder, VerifyVerifiableDomainInput, WorkflowRunOrder. type Input interface{} // AbortQueuedMigrationsInput is an autogenerated input type of AbortQueuedMigrations. @@ -71,6 +71,30 @@ type AddDiscussionCommentInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// AddDiscussionPollVoteInput is an autogenerated input type of AddDiscussionPollVote. +type AddDiscussionPollVoteInput struct { + // The Node ID of the discussion poll option to vote for. (Required.) + PollOptionID ID `json:"pollOptionId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// AddEnterpriseOrganizationMemberInput is an autogenerated input type of AddEnterpriseOrganizationMember. +type AddEnterpriseOrganizationMemberInput struct { + // The ID of the enterprise which owns the organization. (Required.) + EnterpriseID ID `json:"enterpriseId"` + // The ID of the organization the users will be added to. (Required.) + OrganizationID ID `json:"organizationId"` + // The IDs of the enterprise members to add. (Required.) + UserIDs []ID `json:"userIds"` + + // The role to assign the users in the organization. (Optional.) + Role *OrganizationMemberRole `json:"role,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // AddEnterpriseSupportEntitlementInput is an autogenerated input type of AddEnterpriseSupportEntitlement. type AddEnterpriseSupportEntitlementInput struct { // The ID of the Enterprise which the admin belongs to. (Required.) @@ -119,6 +143,32 @@ type AddProjectColumnInput struct { // AddProjectDraftIssueInput is an autogenerated input type of AddProjectDraftIssue. type AddProjectDraftIssueInput struct { + + // The ID of the Project to add the draft issue to. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `projectId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ProjectID *ID `json:"projectId,omitempty"` + // The title of the draft issue. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `title` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + Title *String `json:"title,omitempty"` + // The body of the draft issue. **Upcoming Change on 2023-01-01 UTC** **Description:** `body` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + Body *String `json:"body,omitempty"` + // The IDs of the assignees of the draft issue. **Upcoming Change on 2023-01-01 UTC** **Description:** `assigneeIds` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + AssigneeIDs *[]ID `json:"assigneeIds,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// AddProjectNextItemInput is an autogenerated input type of AddProjectNextItem. +type AddProjectNextItemInput struct { + + // The ID of the Project to add the item to. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `projectId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ProjectID *ID `json:"projectId,omitempty"` + // The content id of the item (Issue or PullRequest). This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `contentId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ContentID *ID `json:"contentId,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// AddProjectV2DraftIssueInput is an autogenerated input type of AddProjectV2DraftIssue. +type AddProjectV2DraftIssueInput struct { // The ID of the Project to add the draft issue to. (Required.) ProjectID ID `json:"projectId"` // The title of the draft issue. (Required.) @@ -132,11 +182,11 @@ type AddProjectDraftIssueInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } -// AddProjectNextItemInput is an autogenerated input type of AddProjectNextItem. -type AddProjectNextItemInput struct { +// AddProjectV2ItemByIdInput is an autogenerated input type of AddProjectV2ItemById. +type AddProjectV2ItemByIdInput struct { // The ID of the Project to add the item to. (Required.) ProjectID ID `json:"projectId"` - // The content id of the item (Issue or PullRequest). (Required.) + // The id of the Issue or Pull Request to add. (Required.) ContentID ID `json:"contentId"` // A unique identifier for the client performing the mutation. (Optional.) @@ -268,6 +318,17 @@ type ApproveVerifiableDomainInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// ArchiveProjectV2ItemInput is an autogenerated input type of ArchiveProjectV2Item. +type ArchiveProjectV2ItemInput struct { + // The ID of the Project to archive the item from. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the ProjectV2Item to archive. (Required.) + ItemID ID `json:"itemId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // ArchiveRepositoryInput is an autogenerated input type of ArchiveRepository. type ArchiveRepositoryInput struct { // The ID of the repository to mark as archived. (Required.) @@ -376,8 +437,12 @@ type CheckRunFilter struct { AppID *Int `json:"appId,omitempty"` // Filters the check runs by this name. (Optional.) CheckName *String `json:"checkName,omitempty"` - // Filters the check runs by this status. (Optional.) + // Filters the check runs by this status. Superceded by statuses. (Optional.) Status *CheckStatusState `json:"status,omitempty"` + // Filters the check runs by this status. Overrides status. (Optional.) + Statuses *[]CheckStatusState `json:"statuses,omitempty"` + // Filters the check runs by these conclusions. (Optional.) + Conclusions *[]CheckConclusionState `json:"conclusions,omitempty"` } // CheckRunOutput represents descriptive details about the check run. @@ -432,6 +497,19 @@ type ClearLabelsFromLabelableInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// ClearProjectV2ItemFieldValueInput is an autogenerated input type of ClearProjectV2ItemFieldValue. +type ClearProjectV2ItemFieldValueInput struct { + // The ID of the Project. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the item to be cleared. (Required.) + ItemID ID `json:"itemId"` + // The ID of the field to be cleared. (Required.) + FieldID ID `json:"fieldId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // CloneProjectInput is an autogenerated input type of CloneProject. type CloneProjectInput struct { // The owner ID to create the project under. (Required.) @@ -475,6 +553,8 @@ type CloseIssueInput struct { // ID of the issue to be closed. (Required.) IssueID ID `json:"issueId"` + // The reason the issue is to be closed. (Optional.) + StateReason *IssueClosedStateReason `json:"stateReason,omitempty"` // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -514,7 +594,7 @@ type CommitMessage struct { Body *String `json:"body,omitempty"` } -// CommittableBranch represents a git ref for a commit to be appended to. The ref must be a branch, i.e. its fully qualified name must start with `refs/heads/` (although the input is not required to be fully qualified). The Ref may be specified by its global node ID or by the repository nameWithOwner and branch name. ### Examples Specify a branch using a global node ID: { "id": "MDM6UmVmMTpyZWZzL2hlYWRzL21haW4=" } Specify a branch using nameWithOwner and branch name: { "nameWithOwner": "github/graphql-client", "branchName": "main" }. +// CommittableBranch represents a git ref for a commit to be appended to. The ref must be a branch, i.e. its fully qualified name must start with `refs/heads/` (although the input is not required to be fully qualified). The Ref may be specified by its global node ID or by the `repositoryNameWithOwner` and `branchName`. ### Examples Specify a branch using a global node ID: { "id": "MDM6UmVmMTpyZWZzL2hlYWRzL21haW4=" } Specify a branch using `repositoryNameWithOwner` and `branchName`: { "repositoryNameWithOwner": "github/graphql-client", "branchName": "main" }. type CommittableBranch struct { // The Node ID of the Ref to be updated. (Optional.) @@ -588,11 +668,11 @@ type CreateBranchProtectionRuleInput struct { DismissesStaleReviews *Boolean `json:"dismissesStaleReviews,omitempty"` // Is dismissal of pull request reviews restricted. (Optional.) RestrictsReviewDismissals *Boolean `json:"restrictsReviewDismissals,omitempty"` - // A list of User or Team IDs allowed to dismiss reviews on pull requests targeting matching branches. (Optional.) + // A list of User, Team, or App IDs allowed to dismiss reviews on pull requests targeting matching branches. (Optional.) ReviewDismissalActorIDs *[]ID `json:"reviewDismissalActorIds,omitempty"` - // A list of User or Team IDs allowed to bypass pull requests targeting matching branches. (Optional.) + // A list of User, Team, or App IDs allowed to bypass pull requests targeting matching branches. (Optional.) BypassPullRequestActorIDs *[]ID `json:"bypassPullRequestActorIds,omitempty"` - // A list of User or Team IDs allowed to bypass force push targeting matching branches. (Optional.) + // A list of User, Team, or App IDs allowed to bypass force push targeting matching branches. (Optional.) BypassForcePushActorIDs *[]ID `json:"bypassForcePushActorIds,omitempty"` // Is pushing to matching branches restricted. (Optional.) RestrictsPushes *Boolean `json:"restrictsPushes,omitempty"` @@ -604,6 +684,12 @@ type CreateBranchProtectionRuleInput struct { RequiredStatusChecks *[]RequiredStatusCheckInput `json:"requiredStatusChecks,omitempty"` // Are conversations required to be resolved before merging. (Optional.) RequiresConversationResolution *Boolean `json:"requiresConversationResolution,omitempty"` + // Whether the most recent push must be approved by someone other than the person who pushed it. (Optional.) + RequireLastPushApproval *Boolean `json:"requireLastPushApproval,omitempty"` + // Whether to set the branch as read-only. If this is true, users will not be able to push to the branch. (Optional.) + LockBranch *Boolean `json:"lockBranch,omitempty"` + // Whether users can pull changes from upstream when the branch is locked. Set to `true` to allow fork syncing. Set to `false` to prevent fork syncing. (Optional.) + LockAllowsFetchAndMerge *Boolean `json:"lockAllowsFetchAndMerge,omitempty"` // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -744,6 +830,21 @@ type CreateIssueInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// CreateLinkedBranchInput is an autogenerated input type of CreateLinkedBranch. +type CreateLinkedBranchInput struct { + // ID of the issue to link to. (Required.) + IssueID ID `json:"issueId"` + // The commit SHA to base the new branch on. (Required.) + Oid GitObjectID `json:"oid"` + + // The name of the new branch. Defaults to issue number and title. (Optional.) + Name *String `json:"name,omitempty"` + // ID of the repository to create the branch in. Defaults to the issue repository. (Optional.) + RepositoryID *ID `json:"repositoryId,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // CreateMigrationSourceInput is an autogenerated input type of CreateMigrationSource. type CreateMigrationSourceInput struct { // The Octoshift migration source name. (Required.) @@ -780,6 +881,21 @@ type CreateProjectInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// CreateProjectV2Input is an autogenerated input type of CreateProjectV2. +type CreateProjectV2Input struct { + // The owner ID to create the project under. (Required.) + OwnerID ID `json:"ownerId"` + // The title of the project. (Required.) + Title String `json:"title"` + + // The repository to link the project to. (Optional.) + RepositoryID *ID `json:"repositoryId,omitempty"` + // The team to link the project to. The team will be granted read permissions. (Optional.) + TeamID *ID `json:"teamId,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // CreatePullRequestInput is an autogenerated input type of CreatePullRequest. type CreatePullRequestInput struct { // The Node ID of the repository. (Required.) @@ -1002,6 +1118,15 @@ type DeleteIssueInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// DeleteLinkedBranchInput is an autogenerated input type of DeleteLinkedBranch. +type DeleteLinkedBranchInput struct { + // The ID of the linked branch. (Required.) + LinkedBranchID ID `json:"linkedBranchId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // DeleteProjectCardInput is an autogenerated input type of DeleteProjectCard. type DeleteProjectCardInput struct { // The id of the card to delete. (Required.) @@ -1031,6 +1156,17 @@ type DeleteProjectInput struct { // DeleteProjectNextItemInput is an autogenerated input type of DeleteProjectNextItem. type DeleteProjectNextItemInput struct { + + // The ID of the Project from which the item should be removed. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `projectId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ProjectID *ID `json:"projectId,omitempty"` + // The ID of the item to be removed. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `itemId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ItemID *ID `json:"itemId,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// DeleteProjectV2ItemInput is an autogenerated input type of DeleteProjectV2Item. +type DeleteProjectV2ItemInput struct { // The ID of the Project from which the item should be removed. (Required.) ProjectID ID `json:"projectId"` // The ID of the item to be removed. (Required.) @@ -1119,6 +1255,14 @@ type DiscussionOrder struct { Direction OrderDirection `json:"direction"` } +// DiscussionPollOptionOrder represents ordering options for discussion poll option connections. +type DiscussionPollOptionOrder struct { + // The field to order poll options by. (Required.) + Field DiscussionPollOptionOrderField `json:"field"` + // The ordering direction. (Required.) + Direction OrderDirection `json:"direction"` +} + // DismissPullRequestReviewInput is an autogenerated input type of DismissPullRequestReview. type DismissPullRequestReviewInput struct { // The Node ID of the pull request review to modify. (Required.) @@ -1173,11 +1317,11 @@ type EnablePullRequestAutoMergeInput struct { // ID of the pull request to enable auto-merge on. (Required.) PullRequestID ID `json:"pullRequestId"` - // Commit headline to use for the commit when the PR is mergable; if omitted, a default message will be used. (Optional.) + // Commit headline to use for the commit when the PR is mergable; if omitted, a default message will be used. NOTE: when merging with a merge queue any input value for commit headline is ignored. (Optional.) CommitHeadline *String `json:"commitHeadline,omitempty"` - // Commit body to use for the commit when the PR is mergable; if omitted, a default message will be used. (Optional.) + // Commit body to use for the commit when the PR is mergable; if omitted, a default message will be used. NOTE: when merging with a merge queue any input value for commit message is ignored. (Optional.) CommitBody *String `json:"commitBody,omitempty"` - // The merge method to use. If omitted, defaults to 'MERGE'. (Optional.) + // The merge method to use. If omitted, defaults to `MERGE`. NOTE: when merging with a merge queue any input value for merge method is ignored. (Optional.) MergeMethod *PullRequestMergeMethod `json:"mergeMethod,omitempty"` // The email address to associate with this merge. (Optional.) AuthorEmail *String `json:"authorEmail,omitempty"` @@ -1384,6 +1528,28 @@ type LanguageOrder struct { Direction OrderDirection `json:"direction"` } +// LinkProjectV2ToRepositoryInput is an autogenerated input type of LinkProjectV2ToRepository. +type LinkProjectV2ToRepositoryInput struct { + // The ID of the project to link to the repository. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the repository to link to the project. (Required.) + RepositoryID ID `json:"repositoryId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// LinkProjectV2ToTeamInput is an autogenerated input type of LinkProjectV2ToTeam. +type LinkProjectV2ToTeamInput struct { + // The ID of the project to link to the team. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the team to link to the project. (Required.) + TeamID ID `json:"teamId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // LinkRepositoryToProjectInput is an autogenerated input type of LinkRepositoryToProject. type LinkRepositoryToProjectInput struct { // The ID of the Project to link to a Repository. (Required.) @@ -1574,6 +1740,68 @@ type ProjectOrder struct { Direction OrderDirection `json:"direction"` } +// ProjectV2FieldOrder represents ordering options for project v2 field connections. +type ProjectV2FieldOrder struct { + // The field to order the project v2 fields by. (Required.) + Field ProjectV2FieldOrderField `json:"field"` + // The ordering direction. (Required.) + Direction OrderDirection `json:"direction"` +} + +// ProjectV2FieldValue represents the values that can be used to update a field of an item inside a Project. Only 1 value can be updated at a time. +type ProjectV2FieldValue struct { + + // The text to set on the field. (Optional.) + Text *String `json:"text,omitempty"` + // The number to set on the field. (Optional.) + Number *Float `json:"number,omitempty"` + // The ISO 8601 date to set on the field. (Optional.) + Date *Date `json:"date,omitempty"` + // The id of the single select option to set on the field. (Optional.) + SingleSelectOptionID *String `json:"singleSelectOptionId,omitempty"` + // The id of the iteration to set on the field. (Optional.) + IterationID *String `json:"iterationId,omitempty"` +} + +// ProjectV2Filters represents ways in which to filter lists of projects. +type ProjectV2Filters struct { + + // List project v2 filtered by the state given. (Optional.) + State *ProjectV2State `json:"state,omitempty"` +} + +// ProjectV2ItemFieldValueOrder represents ordering options for project v2 item field value connections. +type ProjectV2ItemFieldValueOrder struct { + // The field to order the project v2 item field values by. (Required.) + Field ProjectV2ItemFieldValueOrderField `json:"field"` + // The ordering direction. (Required.) + Direction OrderDirection `json:"direction"` +} + +// ProjectV2ItemOrder represents ordering options for project v2 item connections. +type ProjectV2ItemOrder struct { + // The field to order the project v2 items by. (Required.) + Field ProjectV2ItemOrderField `json:"field"` + // The ordering direction. (Required.) + Direction OrderDirection `json:"direction"` +} + +// ProjectV2Order represents ways in which lists of projects can be ordered upon return. +type ProjectV2Order struct { + // The field in which to order projects by. (Required.) + Field ProjectV2OrderField `json:"field"` + // The direction in which to order projects by the specified field. (Required.) + Direction OrderDirection `json:"direction"` +} + +// ProjectV2ViewOrder represents ordering options for project v2 view connections. +type ProjectV2ViewOrder struct { + // The field to order the project v2 views by. (Required.) + Field ProjectV2ViewOrderField `json:"field"` + // The ordering direction. (Required.) + Direction OrderDirection `json:"direction"` +} + // PullRequestOrder represents ways in which lists of issues can be ordered upon return. type PullRequestOrder struct { // The field in which to order pull requests by. (Required.) @@ -2007,6 +2235,8 @@ type StartRepositoryMigrationInput struct { SourceRepositoryURL URI `json:"sourceRepositoryUrl"` // The name of the imported repository. (Required.) RepositoryName String `json:"repositoryName"` + // The Octoshift migration source access token. (Required.) + AccessToken String `json:"accessToken"` // Whether to continue the migration on error. (Optional.) ContinueOnError *Boolean `json:"continueOnError,omitempty"` @@ -2014,12 +2244,14 @@ type StartRepositoryMigrationInput struct { GitArchiveURL *String `json:"gitArchiveUrl,omitempty"` // The signed URL to access the user-uploaded metadata archive. (Optional.) MetadataArchiveURL *String `json:"metadataArchiveUrl,omitempty"` - // The Octoshift migration source access token. (Optional.) - AccessToken *String `json:"accessToken,omitempty"` // The GitHub personal access token of the user importing to the target repository. (Optional.) GitHubPat *String `json:"githubPat,omitempty"` // Whether to skip migrating releases for the repository. (Optional.) SkipReleases *Boolean `json:"skipReleases,omitempty"` + // The visibility of the imported repository. (Optional.) + TargetRepoVisibility *String `json:"targetRepoVisibility,omitempty"` + // Whether to lock the source repository. (Optional.) + LockSource *Boolean `json:"lockSource,omitempty"` // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -2079,6 +2311,17 @@ type TeamRepositoryOrder struct { Direction OrderDirection `json:"direction"` } +// TransferEnterpriseOrganizationInput is an autogenerated input type of TransferEnterpriseOrganization. +type TransferEnterpriseOrganizationInput struct { + // The ID of the organization to transfer. (Required.) + OrganizationID ID `json:"organizationId"` + // The ID of the enterprise where the organization should be transferred. (Required.) + DestinationEnterpriseID ID `json:"destinationEnterpriseId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // TransferIssueInput is an autogenerated input type of TransferIssue. type TransferIssueInput struct { // The Node ID of the issue to be transferred. (Required.) @@ -2086,6 +2329,19 @@ type TransferIssueInput struct { // The Node ID of the repository the issue should be transferred to. (Required.) RepositoryID ID `json:"repositoryId"` + // Whether to create labels if they don't exist in the target repository (matched by name). (Optional.) + CreateLabelsIfMissing *Boolean `json:"createLabelsIfMissing,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// UnarchiveProjectV2ItemInput is an autogenerated input type of UnarchiveProjectV2Item. +type UnarchiveProjectV2ItemInput struct { + // The ID of the Project to archive the item from. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the ProjectV2Item to unarchive. (Required.) + ItemID ID `json:"itemId"` + // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -2117,6 +2373,28 @@ type UnfollowUserInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// UnlinkProjectV2FromRepositoryInput is an autogenerated input type of UnlinkProjectV2FromRepository. +type UnlinkProjectV2FromRepositoryInput struct { + // The ID of the project to unlink from the repository. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the repository to unlink from the project. (Required.) + RepositoryID ID `json:"repositoryId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// UnlinkProjectV2FromTeamInput is an autogenerated input type of UnlinkProjectV2FromTeam. +type UnlinkProjectV2FromTeamInput struct { + // The ID of the project to unlink from the team. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the team to unlink from the project. (Required.) + TeamID ID `json:"teamId"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // UnlinkRepositoryFromProjectInput is an autogenerated input type of UnlinkRepositoryFromProject. type UnlinkRepositoryFromProjectInput struct { // The ID of the Project linked to the Repository. (Required.) @@ -2228,11 +2506,11 @@ type UpdateBranchProtectionRuleInput struct { DismissesStaleReviews *Boolean `json:"dismissesStaleReviews,omitempty"` // Is dismissal of pull request reviews restricted. (Optional.) RestrictsReviewDismissals *Boolean `json:"restrictsReviewDismissals,omitempty"` - // A list of User or Team IDs allowed to dismiss reviews on pull requests targeting matching branches. (Optional.) + // A list of User, Team, or App IDs allowed to dismiss reviews on pull requests targeting matching branches. (Optional.) ReviewDismissalActorIDs *[]ID `json:"reviewDismissalActorIds,omitempty"` - // A list of User or Team IDs allowed to bypass pull requests targeting matching branches. (Optional.) + // A list of User, Team, or App IDs allowed to bypass pull requests targeting matching branches. (Optional.) BypassPullRequestActorIDs *[]ID `json:"bypassPullRequestActorIds,omitempty"` - // A list of User or Team IDs allowed to bypass force push targeting matching branches. (Optional.) + // A list of User, Team, or App IDs allowed to bypass force push targeting matching branches. (Optional.) BypassForcePushActorIDs *[]ID `json:"bypassForcePushActorIds,omitempty"` // Is pushing to matching branches restricted. (Optional.) RestrictsPushes *Boolean `json:"restrictsPushes,omitempty"` @@ -2244,6 +2522,12 @@ type UpdateBranchProtectionRuleInput struct { RequiredStatusChecks *[]RequiredStatusCheckInput `json:"requiredStatusChecks,omitempty"` // Are conversations required to be resolved before merging. (Optional.) RequiresConversationResolution *Boolean `json:"requiresConversationResolution,omitempty"` + // Whether the most recent push must be approved by someone other than the person who pushed it. (Optional.) + RequireLastPushApproval *Boolean `json:"requireLastPushApproval,omitempty"` + // Whether to set the branch as read-only. If this is true, users will not be able to push to the branch. (Optional.) + LockBranch *Boolean `json:"lockBranch,omitempty"` + // Whether users can pull changes from upstream when the branch is locked. Set to `true` to allow fork syncing. Set to `false` to prevent fork syncing. (Optional.) + LockAllowsFetchAndMerge *Boolean `json:"lockAllowsFetchAndMerge,omitempty"` // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -2334,6 +2618,8 @@ type UpdateEnterpriseAllowPrivateRepositoryForkingSettingInput struct { // The value for the allow private repository forking setting on the enterprise. (Required.) SettingValue EnterpriseEnabledDisabledSettingValue `json:"settingValue"` + // The value for the allow private repository forking policy on the enterprise. (Optional.) + PolicyValue *EnterpriseAllowPrivateRepositoryForkingPolicyValue `json:"policyValue,omitempty"` // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -2625,6 +2911,17 @@ type UpdateOrganizationAllowPrivateRepositoryForkingSettingInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } +// UpdateOrganizationWebCommitSignoffSettingInput is an autogenerated input type of UpdateOrganizationWebCommitSignoffSetting. +type UpdateOrganizationWebCommitSignoffSettingInput struct { + // The ID of the organization on which to set the web commit signoff setting. (Required.) + OrganizationID ID `json:"organizationId"` + // Enable signoff on web-based commits for repositories in the organization?. (Required.) + WebCommitSignoffRequired Boolean `json:"webCommitSignoffRequired"` + + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + // UpdateProjectCardInput is an autogenerated input type of UpdateProjectCard. type UpdateProjectCardInput struct { // The ProjectCard ID to update. (Required.) @@ -2683,15 +2980,64 @@ type UpdateProjectInput struct { // UpdateProjectNextInput is an autogenerated input type of UpdateProjectNext. type UpdateProjectNextInput struct { + + // The ID of the Project to update. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `projectId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ProjectID *ID `json:"projectId,omitempty"` + // Set the title of the project. **Upcoming Change on 2023-01-01 UTC** **Description:** `title` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + Title *String `json:"title,omitempty"` + // Set the readme description of the project. **Upcoming Change on 2023-01-01 UTC** **Description:** `description` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + Description *String `json:"description,omitempty"` + // Set the short description of the project. **Upcoming Change on 2023-01-01 UTC** **Description:** `shortDescription` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ShortDescription *String `json:"shortDescription,omitempty"` + // Set the project to closed or open. **Upcoming Change on 2023-01-01 UTC** **Description:** `closed` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + Closed *Boolean `json:"closed,omitempty"` + // Set the project to public or private. **Upcoming Change on 2023-01-01 UTC** **Description:** `public` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + Public *Boolean `json:"public,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// UpdateProjectNextItemFieldInput is an autogenerated input type of UpdateProjectNextItemField. +type UpdateProjectNextItemFieldInput struct { + + // The ID of the Project. This field is required. (Optional.) + ProjectID *ID `json:"projectId,omitempty"` + // The id of the item to be updated. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `itemId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + ItemID *ID `json:"itemId,omitempty"` + // The id of the field to be updated. **Upcoming Change on 2023-01-01 UTC** **Description:** `fieldId` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + FieldID *ID `json:"fieldId,omitempty"` + // The value which will be set on the field. This field is required. **Upcoming Change on 2023-01-01 UTC** **Description:** `value` will be removed. Follow the ProjectV2 guide at https://github.blog/changelog/2022-06-23-the-new-github-issues-june-23rd-update/, to find a suitable replacement. **Reason:** The `ProjectNext` API is deprecated in favour of the more capable `ProjectV2` API. (Optional.) + Value *String `json:"value,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// UpdateProjectV2DraftIssueInput is an autogenerated input type of UpdateProjectV2DraftIssue. +type UpdateProjectV2DraftIssueInput struct { + // The ID of the draft issue to update. (Required.) + DraftIssueID ID `json:"draftIssueId"` + + // The title of the draft issue. (Optional.) + Title *String `json:"title,omitempty"` + // The body of the draft issue. (Optional.) + Body *String `json:"body,omitempty"` + // The IDs of the assignees of the draft issue. (Optional.) + AssigneeIDs *[]ID `json:"assigneeIds,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// UpdateProjectV2Input is an autogenerated input type of UpdateProjectV2. +type UpdateProjectV2Input struct { // The ID of the Project to update. (Required.) ProjectID ID `json:"projectId"` // Set the title of the project. (Optional.) Title *String `json:"title,omitempty"` - // Set the readme description of the project. (Optional.) - Description *String `json:"description,omitempty"` // Set the short description of the project. (Optional.) ShortDescription *String `json:"shortDescription,omitempty"` + // Set the readme description of the project. (Optional.) + Readme *String `json:"readme,omitempty"` // Set the project to closed or open. (Optional.) Closed *Boolean `json:"closed,omitempty"` // Set the project to public or private. (Optional.) @@ -2700,17 +3046,30 @@ type UpdateProjectNextInput struct { ClientMutationID *String `json:"clientMutationId,omitempty"` } -// UpdateProjectNextItemFieldInput is an autogenerated input type of UpdateProjectNextItemField. -type UpdateProjectNextItemFieldInput struct { +// UpdateProjectV2ItemFieldValueInput is an autogenerated input type of UpdateProjectV2ItemFieldValue. +type UpdateProjectV2ItemFieldValueInput struct { // The ID of the Project. (Required.) ProjectID ID `json:"projectId"` - // The id of the item to be updated. (Required.) + // The ID of the item to be updated. (Required.) ItemID ID `json:"itemId"` + // The ID of the field to be updated. (Required.) + FieldID ID `json:"fieldId"` // The value which will be set on the field. (Required.) - Value String `json:"value"` + Value ProjectV2FieldValue `json:"value"` - // The id of the field to be updated. (Optional.) - FieldID *ID `json:"fieldId,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// UpdateProjectV2ItemPositionInput is an autogenerated input type of UpdateProjectV2ItemPosition. +type UpdateProjectV2ItemPositionInput struct { + // The ID of the Project. (Required.) + ProjectID ID `json:"projectId"` + // The ID of the item to be moved. (Required.) + ItemID ID `json:"itemId"` + + // The ID of the item to position this item after. If omitted or set to null the item will be moved to top. (Optional.) + AfterID *ID `json:"afterId,omitempty"` // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -2807,6 +3166,19 @@ type UpdateRepositoryInput struct { HasIssuesEnabled *Boolean `json:"hasIssuesEnabled,omitempty"` // Indicates if the repository should have the project boards feature enabled. (Optional.) HasProjectsEnabled *Boolean `json:"hasProjectsEnabled,omitempty"` + // Indicates if the repository should have the discussions feature enabled. (Optional.) + HasDiscussionsEnabled *Boolean `json:"hasDiscussionsEnabled,omitempty"` + // A unique identifier for the client performing the mutation. (Optional.) + ClientMutationID *String `json:"clientMutationId,omitempty"` +} + +// UpdateRepositoryWebCommitSignoffSettingInput is an autogenerated input type of UpdateRepositoryWebCommitSignoffSetting. +type UpdateRepositoryWebCommitSignoffSettingInput struct { + // The ID of the repository to update. (Required.) + RepositoryID ID `json:"repositoryId"` + // Indicates if the repository should require signoff on web-based commits. (Required.) + WebCommitSignoffRequired Boolean `json:"webCommitSignoffRequired"` + // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } @@ -2919,3 +3291,11 @@ type VerifyVerifiableDomainInput struct { // A unique identifier for the client performing the mutation. (Optional.) ClientMutationID *String `json:"clientMutationId,omitempty"` } + +// WorkflowRunOrder represents ways in which lists of workflow runs can be ordered upon return. +type WorkflowRunOrder struct { + // The field by which to order workflows. (Required.) + Field WorkflowRunOrderField `json:"field"` + // The direction in which to order workflow runs by the specified field. (Required.) + Direction OrderDirection `json:"direction"` +} diff --git a/vendor/modules.txt b/vendor/modules.txt index d31d15ba65..8195869455 100644 --- a/vendor/modules.txt +++ b/vendor/modules.txt @@ -682,7 +682,7 @@ github.com/securego/gosec/v2/rules # github.com/shazow/go-diff v0.0.0-20160112020656-b6b7b6733b8c ## explicit github.com/shazow/go-diff/difflib -# github.com/shurcooL/githubv4 v0.0.0-20220520033151-0b4e3294ff00 +# github.com/shurcooL/githubv4 v0.0.0-20221126192849-0b5c4c7994eb ## explicit github.com/shurcooL/githubv4 # github.com/shurcooL/graphql v0.0.0-20220606043923-3cf50f8a0a29 diff --git a/website/docs/r/branch_protection.html.markdown b/website/docs/r/branch_protection.html.markdown index c6310c0d58..839cbafd24 100644 --- a/website/docs/r/branch_protection.html.markdown +++ b/website/docs/r/branch_protection.html.markdown @@ -88,6 +88,7 @@ The following arguments are supported: * `allows_deletions` - (Optional) Boolean, setting this to `true` to allow the branch to be deleted. * `allows_force_pushes` - (Optional) Boolean, setting this to `true` to allow force pushes on the branch. * `blocks_creations` - (Optional) Boolean, setting this to `true` to block creating the branch. +* `lock_branch` - (Optional) Boolean, Setting this to `true` will make the branch read-only and preventing any pushes to it. Defaults to `false` ### Required Status Checks @@ -106,7 +107,8 @@ The following arguments are supported: * `pull_request_bypassers`: (Optional) The list of actor Names/IDs that are allowed to bypass pull request requirements. Actor names must either begin with a "/" for users or the organization name followed by a "/" for teams. * `require_code_owner_reviews`: (Optional) Require an approved review in pull requests including files with a designated code owner. Defaults to `false`. * `required_approving_review_count`: (Optional) Require x number of approvals to satisfy branch protection requirements. If this is specified it must be a number between 0-6. This requirement matches GitHub's API, see the upstream [documentation](https://developer.github.com/v3/repos/branches/#parameters-1) for more information. - + (https://developer.github.com/v3/repos/branches/#parameters-1) for more information. +* `require_last_push_approval`: (Optional) Require that The most recent push must be approved by someone other than the last pusher. Defaults to `false` ## Import From a6565a9cb6fb7af2d3da15b76e0c59b1a3b146eb Mon Sep 17 00:00:00 2001 From: Trent Millar Date: Tue, 6 Dec 2022 15:05:32 -0700 Subject: [PATCH 07/19] feat(github_release): adding github_release resource and tests (#1122) * feat(github_release): adding github_release resource and tests * feat(docs) adding github_release page to website docs * chore: update changelog with this pr's new resource * fix: adding node_id and release_id to resource attributes * Update CHANGELOG.md * Fix broken merge/build Co-authored-by: Keegan Campbell --- github/provider.go | 1 + github/resource_github_release.go | 239 +++++++++++++++++++++++++ github/resource_github_release_test.go | 208 +++++++++++++++++++++ website/docs/r/release.html.markdown | 104 +++++++++++ website/github.erb | 3 + 5 files changed, 555 insertions(+) create mode 100644 github/resource_github_release.go create mode 100644 github/resource_github_release_test.go create mode 100644 website/docs/r/release.html.markdown diff --git a/github/provider.go b/github/provider.go index ff739710b0..405e3eb2ab 100644 --- a/github/provider.go +++ b/github/provider.go @@ -116,6 +116,7 @@ func Provider() terraform.ResourceProvider { "github_organization_webhook": resourceGithubOrganizationWebhook(), "github_project_card": resourceGithubProjectCard(), "github_project_column": resourceGithubProjectColumn(), + "github_release": resourceGithubRelease(), "github_repository": resourceGithubRepository(), "github_repository_autolink_reference": resourceGithubRepositoryAutolinkReference(), "github_repository_collaborator": resourceGithubRepositoryCollaborator(), diff --git a/github/resource_github_release.go b/github/resource_github_release.go new file mode 100644 index 0000000000..e1062499aa --- /dev/null +++ b/github/resource_github_release.go @@ -0,0 +1,239 @@ +package github + +import ( + "context" + "fmt" + "log" + "strconv" + + "github.com/google/go-github/v48/github" + "github.com/hashicorp/terraform-plugin-sdk/helper/schema" +) + +func resourceGithubRelease() *schema.Resource { + return &schema.Resource{ + Create: resourceGithubReleaseCreateUpdate, + Update: resourceGithubReleaseCreateUpdate, + Read: resourceGithubReleaseRead, + Delete: resourceGithubReleaseDelete, + Importer: &schema.ResourceImporter{ + State: resourceGithubReleaseImport, + }, + + Schema: map[string]*schema.Schema{ + "repository": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "tag_name": { + Type: schema.TypeString, + Required: true, + ForceNew: true, + }, + "target_commitish": { + Type: schema.TypeString, + Default: "main", + Optional: true, + ForceNew: true, + }, + "name": { + Type: schema.TypeString, + Optional: true, + ForceNew: false, + }, + "body": { + Type: schema.TypeString, + Optional: true, + ForceNew: false, + }, + "draft": { + Type: schema.TypeBool, + Default: true, + Optional: true, + ForceNew: true, + }, + "prerelease": { + Type: schema.TypeBool, + Default: true, + Optional: true, + }, + "generate_release_notes": { + Type: schema.TypeBool, + Default: false, + Optional: true, + }, + "discussion_category_name": { + Type: schema.TypeString, + Optional: true, + ForceNew: true, + }, + "etag": { + Type: schema.TypeString, + Computed: true, + }, + }, + } +} + +func resourceGithubReleaseCreateUpdate(d *schema.ResourceData, meta interface{}) error { + ctx := context.Background() + if !d.IsNewResource() { + ctx = context.WithValue(ctx, ctxId, d.Id()) + } + + client := meta.(*Owner).v3client + owner := meta.(*Owner).name + repoName := d.Get("repository").(string) + tagName := d.Get("tag_name").(string) + targetCommitish := d.Get("target_commitish").(string) + draft := d.Get("draft").(bool) + prerelease := d.Get("prerelease").(bool) + generateReleaseNotes := d.Get("generate_release_notes").(bool) + + req := &github.RepositoryRelease{ + TagName: github.String(tagName), + TargetCommitish: github.String(targetCommitish), + Draft: github.Bool(draft), + Prerelease: github.Bool(prerelease), + GenerateReleaseNotes: github.Bool(generateReleaseNotes), + } + + if v, ok := d.GetOk("body"); ok { + req.Body = github.String(v.(string)) + } + + if v, ok := d.GetOk("name"); ok { + req.Name = github.String(v.(string)) + } + + if v, ok := d.GetOk("discussion_category_name"); ok { + req.DiscussionCategoryName = github.String(v.(string)) + } + + var release *github.RepositoryRelease + var resp *github.Response + var err error + if d.IsNewResource() { + log.Printf("[DEBUG] Creating release: %s (%s/%s)", + targetCommitish, owner, repoName) + release, resp, err = client.Repositories.CreateRelease(ctx, owner, repoName, req) + if resp != nil { + log.Printf("[DEBUG] Response from creating release: %#v", *resp) + } + } else { + number := d.Get("number").(int64) + log.Printf("[DEBUG] Updating release: %d:%s (%s/%s)", + number, targetCommitish, owner, repoName) + release, resp, err = client.Repositories.EditRelease(ctx, owner, repoName, number, req) + if resp != nil { + log.Printf("[DEBUG] Response from updating release: %#v", *resp) + } + } + + if err != nil { + return err + } + transformResponseToResourceData(d, release, repoName) + return nil +} + +func resourceGithubReleaseRead(d *schema.ResourceData, meta interface{}) error { + repository := d.Get("repository").(string) + ctx := context.WithValue(context.Background(), ctxId, d.Id()) + client := meta.(*Owner).v3client + owner := meta.(*Owner).name + releaseID, err := strconv.ParseInt(d.Id(), 10, 64) + if err != nil { + return err + } + if releaseID == 0 { + return fmt.Errorf("`release_id` must be present") + } + + release, _, err := client.Repositories.GetRelease(ctx, owner, repository, releaseID) + if err != nil { + return err + } + transformResponseToResourceData(d, release, repository) + return nil +} + +func resourceGithubReleaseDelete(d *schema.ResourceData, meta interface{}) error { + ctx := context.WithValue(context.Background(), ctxId, d.Id()) + repository := d.Get("repository").(string) + client := meta.(*Owner).v3client + owner := meta.(*Owner).name + + releaseIDStr := d.Id() + releaseID, err := strconv.ParseInt(d.Id(), 10, 64) + if err != nil { + return unconvertibleIdErr(releaseIDStr, err) + } + if releaseID == 0 { + return fmt.Errorf("`release_id` must be present") + } + + _, err = client.Repositories.DeleteRelease(ctx, owner, repository, releaseID) + if err != nil { + return fmt.Errorf("error deleting GitHub release reference %s/%s (%s): %s", + fmt.Sprint(releaseID), repository, owner, err) + } + return nil +} + +func resourceGithubReleaseImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) { + repoName, releaseIDStr, err := parseTwoPartID(d.Id(), "repository", "release") + if err != nil { + return []*schema.ResourceData{d}, err + } + + releaseID, err := strconv.ParseInt(releaseIDStr, 10, 64) + if err != nil { + return []*schema.ResourceData{d}, unconvertibleIdErr(releaseIDStr, err) + } + if releaseID == 0 { + return []*schema.ResourceData{d}, fmt.Errorf("`release_id` must be present") + } + log.Printf("[DEBUG] Importing release with ID: %d, for repository: %s", releaseID, repoName) + + client := meta.(*Owner).v3client + owner := meta.(*Owner).name + ctx := context.Background() + repository, _, err := client.Repositories.Get(ctx, owner, repoName) + if repository == nil || err != nil { + return []*schema.ResourceData{d}, err + } + d.Set("repository", *repository.Name) + + release, _, err := client.Repositories.GetRelease(ctx, owner, *repository.Name, releaseID) + if release == nil || err != nil { + return []*schema.ResourceData{d}, err + } + d.SetId(strconv.FormatInt(release.GetID(), 10)) + + return []*schema.ResourceData{d}, nil +} + +func transformResponseToResourceData(d *schema.ResourceData, release *github.RepositoryRelease, repository string) { + d.SetId(strconv.FormatInt(release.GetID(), 10)) + d.Set("release_id", release.GetID()) + d.Set("node_id", release.GetNodeID()) + d.Set("repository", repository) + d.Set("tag_name", release.GetTagName()) + d.Set("target_commitish", release.GetTargetCommitish()) + d.Set("name", release.GetName()) + d.Set("body", release.GetBody()) + d.Set("draft", release.GetDraft()) + d.Set("generate_release_notes", release.GetGenerateReleaseNotes()) + d.Set("prerelease", release.GetPrerelease()) + d.Set("discussion_category_name", release.GetDiscussionCategoryName()) + d.Set("created_at", release.GetCreatedAt()) + d.Set("published_at", release.GetPublishedAt()) + d.Set("url", release.GetURL()) + d.Set("html_url", release.GetHTMLURL()) + d.Set("assets_url", release.GetAssetsURL()) + d.Set("upload_url", release.GetUploadURL()) + d.Set("zipball_url", release.GetZipballURL()) + d.Set("tarball_url", release.GetTarballURL()) +} diff --git a/github/resource_github_release_test.go b/github/resource_github_release_test.go new file mode 100644 index 0000000000..57ba6437b1 --- /dev/null +++ b/github/resource_github_release_test.go @@ -0,0 +1,208 @@ +package github + +import ( + "fmt" + "github.com/hashicorp/terraform-plugin-sdk/terraform" + "log" + "testing" + + "github.com/hashicorp/terraform-plugin-sdk/helper/acctest" + "github.com/hashicorp/terraform-plugin-sdk/helper/resource" +) + +func TestAccGithubReleaseResource(t *testing.T) { + + t.Run("create a release with defaults", func(t *testing.T) { + + randomRepoPart := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + randomVersion := fmt.Sprintf("v1.0.%d", acctest.RandIntRange(0, 9999)) + + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_release" "test" { + repository = github_repository.test.name + tag_name = "%s" + } + `, randomRepoPart, randomVersion) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_release.test", "tag_name", randomVersion, + ), + resource.TestCheckResourceAttr( + "github_release.test", "target_commitish", "main", + ), + resource.TestCheckResourceAttr( + "github_release.test", "name", "", + ), + resource.TestCheckResourceAttr( + "github_release.test", "body", "", + ), + resource.TestCheckResourceAttr( + "github_release.test", "draft", "true", + ), + resource.TestCheckResourceAttr( + "github_release.test", "prerelease", "true", + ), + resource.TestCheckResourceAttr( + "github_release.test", "generate_release_notes", "false", + ), + resource.TestCheckResourceAttr( + "github_release.test", "discussion_category_name", "", + ), + ) + + testCase := func(t *testing.T, mode string) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, mode) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + { + ResourceName: "github_release.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importReleaseByResourcePaths( + "github_repository.test", "github_release.test"), + }, + }, + }) + } + + t.Run("with an anonymous account", func(t *testing.T) { + t.Skip("anonymous account not supported for this operation") + }) + + t.Run("with an individual account", func(t *testing.T) { + testCase(t, individual) + }) + + t.Run("with an organization account", func(t *testing.T) { + testCase(t, organization) + }) + + }) + + t.Run("create a release on branch", func(t *testing.T) { + + randomRepoPart := acctest.RandStringFromCharSet(5, acctest.CharSetAlphaNum) + randomVersion := fmt.Sprintf("v1.0.%d", acctest.RandIntRange(0, 9999)) + testBranchName := "test" + + config := fmt.Sprintf(` + resource "github_repository" "test" { + name = "tf-acc-test-%s" + auto_init = true + } + + resource "github_branch" "test" { + repository = github_repository.test.name + branch = "%s" + source_branch = github_repository.test.default_branch + } + + resource "github_release" "test" { + repository = github_repository.test.name + tag_name = "%s" + target_commitish = github_branch.test.branch + draft = false + prerelease = false + } + `, randomRepoPart, testBranchName, randomVersion) + + check := resource.ComposeTestCheckFunc( + resource.TestCheckResourceAttr( + "github_release.test", "tag_name", randomVersion, + ), + resource.TestCheckResourceAttr( + "github_release.test", "target_commitish", testBranchName, + ), + resource.TestCheckResourceAttr( + "github_release.test", "name", "", + ), + resource.TestCheckResourceAttr( + "github_release.test", "body", "", + ), + resource.TestCheckResourceAttr( + "github_release.test", "draft", "false", + ), + resource.TestCheckResourceAttr( + "github_release.test", "prerelease", "false", + ), + resource.TestCheckResourceAttr( + "github_release.test", "generate_release_notes", "false", + ), + resource.TestCheckResourceAttr( + "github_release.test", "discussion_category_name", "", + ), + ) + + testCase := func(t *testing.T, mode string) { + resource.Test(t, resource.TestCase{ + PreCheck: func() { skipUnlessMode(t, mode) }, + Providers: testAccProviders, + Steps: []resource.TestStep{ + { + Config: config, + Check: check, + }, + { + ResourceName: "github_release.test", + ImportState: true, + ImportStateVerify: true, + ImportStateIdFunc: importReleaseByResourcePaths( + "github_repository.test", "github_release.test"), + }, + }, + }) + } + + t.Run("with an anonymous account", func(t *testing.T) { + t.Skip("anonymous account not supported for this operation") + }) + + t.Run("with an individual account", func(t *testing.T) { + testCase(t, individual) + }) + + t.Run("with an organization account", func(t *testing.T) { + testCase(t, organization) + }) + + }) + +} + +func importReleaseByResourcePaths(repoLogicalName, releaseLogicalName string) resource.ImportStateIdFunc { + // test importing using an ID of the form : + // by retrieving the GraphQL ID from the terraform.State + return func(s *terraform.State) (string, error) { + log.Printf("[DEBUG] Looking up tf state ") + repo := s.RootModule().Resources[repoLogicalName] + if repo == nil { + return "", fmt.Errorf("Cannot find %s in terraform state", repoLogicalName) + } + repoID := repo.Primary.ID + if repoID == "" { + return "", fmt.Errorf("repository %s does not have an id in terraform state", repoLogicalName) + } + + release := s.RootModule().Resources[releaseLogicalName] + if release == nil { + return "", fmt.Errorf("Cannot find %s in terraform state", releaseLogicalName) + } + releaseID := release.Primary.ID + if releaseID == "" { + return "", fmt.Errorf("release %s does not have an id in terraform state", releaseLogicalName) + } + + return fmt.Sprintf("%s:%s", repoID, releaseID), nil + } +} diff --git a/website/docs/r/release.html.markdown b/website/docs/r/release.html.markdown new file mode 100644 index 0000000000..b03067a596 --- /dev/null +++ b/website/docs/r/release.html.markdown @@ -0,0 +1,104 @@ +--- +layout: "github" +page_title: "GitHub: github_release" +description: |- + Creates and manages releases within a single GitHub repository +--- + +# github_release + +This resource allows you to create and manage a release in a specific +GitHub repository. + +## Example Usage + +```hcl +resource "github_repository" "repo" { + name = "repo" + description = "GitHub repo managed by Terraform" + + private = false +} + +resource "github_release" "example" { + repository = github_repository.repo.name + tag_name = "v1.0.0" +} +``` + +## Example Usage on Non-Default Branch + +```hcl +resource "github_repository" "example" { + name = "repo" + auto_init = true +} + +resource "github_branch" "example" { + repository = github_repository.example.name + branch = "branch_name" + source_branch = github_repository.example.default_branch +} + +resource "github_release" "example" { + repository = github_repository.example.name + tag_name = "v1.0.0" + target_commitish = github_branch.example.branch + draft = false + prerelease = false +} +``` + +## Argument Reference + +The following arguments are supported: + +* `repository` - (Required) The name of the repository. + +* `tag_name` - (Required) The name of the tag. + +* `target_commitish` - (Optional) The branch name or commit SHA the tag is created from. Defaults to the default branch of the repository. + +* `name` - (Optional) The name of the release. + +* `body` - (Optional) Text describing the contents of the tag. + +* `draft` - (Optional) Set to `false` to create a published release. + +* `prerelease` - (Optional) Set to `false` to identify the release as a full release. + +* `generate_release_notes` - (Optional) Set to `true` to automatically generate the name and body for this release. If `name` is specified, the specified `name` will be used; otherwise, a name will be automatically generated. If `body` is specified, the `body` will be pre-pended to the automatically generated notes. + +* `discussion_category_name` - (Optional) If specified, a discussion of the specified category is created and linked to the release. The value must be a category that already exists in the repository. For more information, see [Managing categories for discussions in your repository](https://docs.github.com/discussions/managing-discussions-for-your-community/managing-categories-for-discussions-in-your-repository). + +## Attributes Reference + +The following additional attributes are exported: + +* `release_id` - The ID of the release. + +* `created_at` - This is the date of the commit used for the release, and not the date when the release was drafted or published. + +* `published_at` - This is the date when the release was published. This will be empty if the release is a draft. + +* `html_url` - URL of the release in GitHub. + +* `url` - URL that can be provided to API calls that reference this release. + +* `assets_url` - URL that can be provided to API calls displaying the attached assets to this release. + +* `upload_url` - URL that can be provided to API calls to upload assets. + +* `zipball_url` - URL that can be provided to API calls to fetch the release ZIP archive. + +* `tarball_url` - URL that can be provided to API calls to fetch the release TAR archive. + +* `node_id` - GraphQL global node id for use with v4 API + +## Import + +This resource can be imported using the `name` of the repository, combined with the `id` of the release, and a `:` character for separating components, e.g. + +```sh +$ terraform import github_release.example repo:12345678 +``` diff --git a/website/github.erb b/website/github.erb index 749b2d8ce8..72fdd07f0e 100644 --- a/website/github.erb +++ b/website/github.erb @@ -178,6 +178,9 @@
  • github_project_column
  • +
  • + github_release +
  • github_repository
  • From b55408c1607f10582234ecfc71932698d755f571 Mon Sep 17 00:00:00 2001 From: Nick Floyd <139819+nickfloyd@users.noreply.github.com> Date: Thu, 8 Dec 2022 08:48:00 -0600 Subject: [PATCH 08/19] =?UTF-8?q?=F0=9F=9A=A7=20Workflows=20have=20changed?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Workflow changes have been made in the Octokit org repo. This PR is propagating those changes. --- .github/workflows/add_to_octokit_project.yml | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 .github/workflows/add_to_octokit_project.yml diff --git a/.github/workflows/add_to_octokit_project.yml b/.github/workflows/add_to_octokit_project.yml new file mode 100644 index 0000000000..63c3338b79 --- /dev/null +++ b/.github/workflows/add_to_octokit_project.yml @@ -0,0 +1,19 @@ +name: Add PRs and issues to Octokit org project + +on: + issues: + types: [reopened, opened] + pull_request: + types: [reopened, opened] + +jobs: + add-to-project: + name: Add issue to project + runs-on: ubuntu-latest + steps: + - uses: actions/add-to-project@v0.4.0 + with: + project-url: https://github.com/orgs/octokit/projects/10 + github-token: ${{ secrets.OCTOKITBOT_PROJECT_ACTION_TOKEN }} + labeled: 'Status: Stale' + label-operator: NOT From 8959009297dab17f9018ac4c628eb80f041387e6 Mon Sep 17 00:00:00 2001 From: Keegan Campbell Date: Fri, 9 Dec 2022 14:15:42 -0800 Subject: [PATCH 09/19] Issue template tweak (#1422) * Don't link to a real PR * Wording tweak --- .github/ISSUE_TEMPLATE/bug.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/ISSUE_TEMPLATE/bug.md b/.github/ISSUE_TEMPLATE/bug.md index f3d78a8bde..f0a0a29a94 100644 --- a/.github/ISSUE_TEMPLATE/bug.md +++ b/.github/ISSUE_TEMPLATE/bug.md @@ -39,5 +39,5 @@ Please list the steps required to reproduce the issue, for example: Is there anything atypical about your accounts that we should know? For example: Running in EC2 Classic? Custom version of OpenStack? Tight ACLs? ### References -Are there any other GitHub issues (open or closed) or Pull Requests that should be linked here? For example: -- GH-1234 +Are there any other open or closed GitHub issues or Pull Requests that should be linked here? For example: +- #123456 From 702835a1c7a4a75d2b5638481d1030a8b64d19cb Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Fri, 9 Dec 2022 08:37:11 +1300 Subject: [PATCH 10/19] feat: allow branch protection check app_id to be null --- github/resource_github_branch_protection_v3.go | 1 - 1 file changed, 1 deletion(-) diff --git a/github/resource_github_branch_protection_v3.go b/github/resource_github_branch_protection_v3.go index f48e937bf1..e17a94cc3a 100644 --- a/github/resource_github_branch_protection_v3.go +++ b/github/resource_github_branch_protection_v3.go @@ -72,7 +72,6 @@ func resourceGithubBranchProtectionV3() *schema.Resource { "app_id": { Type: schema.TypeInt, Optional: true, - Default: -1, }, }, }, From 3032488ece1716755a10818ea478eb62ff3bbdec Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Fri, 9 Dec 2022 08:38:02 +1300 Subject: [PATCH 11/19] chore: change branch protection flatten function to use GetAppID sdk method --- github/resource_github_branch_protection_v3_utils.go | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index 180b099ce9..14e2e89acb 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -50,12 +50,7 @@ func flattenAndSetRequiredStatusChecks(d *schema.ResourceData, protection *githu for _, chk := range rsc.Checks { chkMap := make(map[string]interface{}) chkMap["context"] = chk.Context - chkMap["app_id"] = func() int { - if chk.AppID != nil { - return int(*chk.AppID) - } - return -1 - }() + chkMap["app_id"] = chk.GetAppID() checks = append(checks, chkMap) } From 1deac0d3b77429cdc3afdd28a455d04e731bbbcf Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Mon, 12 Dec 2022 10:00:57 +1300 Subject: [PATCH 12/19] feat: change branch protection v3 utils to flatten and expand contexts into checks --- .../resource_github_branch_protection_v3.go | 1 + ...ource_github_branch_protection_v3_utils.go | 44 ++++++++++++++----- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/github/resource_github_branch_protection_v3.go b/github/resource_github_branch_protection_v3.go index e17a94cc3a..f48e937bf1 100644 --- a/github/resource_github_branch_protection_v3.go +++ b/github/resource_github_branch_protection_v3.go @@ -72,6 +72,7 @@ func resourceGithubBranchProtectionV3() *schema.Resource { "app_id": { Type: schema.TypeInt, Optional: true, + Default: -1, }, }, }, diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index 14e2e89acb..f58e9c7509 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -4,11 +4,10 @@ import ( "context" "errors" "fmt" - "log" - "strings" - "github.com/google/go-github/v48/github" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" + "log" + "strings" ) func buildProtectionRequest(d *schema.ResourceData) (*github.ProtectionRequest, error) { @@ -40,25 +39,35 @@ func buildProtectionRequest(d *schema.ResourceData) (*github.ProtectionRequest, func flattenAndSetRequiredStatusChecks(d *schema.ResourceData, protection *github.Protection) error { rsc := protection.GetRequiredStatusChecks() + if rsc != nil { - contexts := make([]interface{}, 0, len(rsc.Contexts)) + + var checks []interface{} + + // TODO: Remove once contexts is fully deprecated. + // Handle contexts as check objects while waiting for contexts to become deprecated + // Flatten contexts for _, c := range rsc.Contexts { - contexts = append(contexts, c) + chkMap := make(map[string]interface{}) + chkMap["context"] = c + chkMap["app_id"] = -1 + checks = append(checks, chkMap) } - var checks []interface{} + // Flatten checks for _, chk := range rsc.Checks { chkMap := make(map[string]interface{}) chkMap["context"] = chk.Context - chkMap["app_id"] = chk.GetAppID() + chkMap["app_id"] = chk.AppID checks = append(checks, chkMap) } return d.Set("required_status_checks", []interface{}{ map[string]interface{}{ - "strict": rsc.Strict, - "contexts": schema.NewSet(schema.HashString, contexts), - "check": checks, + "strict": rsc.Strict, + // TODO: As above, remove if unneeded + //"contexts": schema.NewSet(schema.HashString, contexts), + "check": checks, }, }) } @@ -200,12 +209,22 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC m := v.(map[string]interface{}) rsc.Strict = m["strict"].(bool) + var rscChecks []*github.RequiredStatusCheck + + // Iterate and parse contexts into checks objects as contexts is deprecated. + // TODO: Remove this code once contexts is fully deprecated + // Iterate and parse contexts contexts := expandNestedSet(m, "contexts") - rsc.Contexts = contexts + for _, c := range contexts { + appID := int64(-1) // Default + rscChecks = append(rscChecks, &github.RequiredStatusCheck{ + Context: c, + AppID: &appID, + }) + } // Iterate and parse checks checks := m["check"].([]interface{}) - var rscChecks []*github.RequiredStatusCheck for _, c := range checks { chk := c.(map[string]interface{}) @@ -224,6 +243,7 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC AppID: &rscAppId, }) } + // Assign after looping both checks and contexts rsc.Checks = rscChecks } return rsc, nil From cb9c464e3c43ce7821133540da2df3b5167506c7 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Tue, 13 Dec 2022 10:54:47 +1300 Subject: [PATCH 13/19] feat: change checks from it's own resource to a list of strings --- .../resource_github_branch_protection_v3.go | 18 ++--- ...ource_github_branch_protection_v3_utils.go | 70 +++++++++++-------- 2 files changed, 45 insertions(+), 43 deletions(-) diff --git a/github/resource_github_branch_protection_v3.go b/github/resource_github_branch_protection_v3.go index f48e937bf1..5627d1f3ba 100644 --- a/github/resource_github_branch_protection_v3.go +++ b/github/resource_github_branch_protection_v3.go @@ -60,21 +60,11 @@ func resourceGithubBranchProtectionV3() *schema.Resource { Type: schema.TypeString, }, }, - "check": { - Type: schema.TypeList, + "checks": { + Type: schema.TypeSet, Optional: true, - Elem: &schema.Resource{ - Schema: map[string]*schema.Schema{ - "context": { - Type: schema.TypeString, - Required: true, - }, - "app_id": { - Type: schema.TypeInt, - Optional: true, - Default: -1, - }, - }, + Elem: &schema.Schema{ + Type: schema.TypeString, }, }, }, diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index f58e9c7509..74f9e41bb5 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -7,6 +7,7 @@ import ( "github.com/google/go-github/v48/github" "github.com/hashicorp/terraform-plugin-sdk/helper/schema" "log" + "strconv" "strings" ) @@ -42,32 +43,31 @@ func flattenAndSetRequiredStatusChecks(d *schema.ResourceData, protection *githu if rsc != nil { + // Contexts and Checks arrays to flatten into + var contexts []interface{} var checks []interface{} // TODO: Remove once contexts is fully deprecated. - // Handle contexts as check objects while waiting for contexts to become deprecated // Flatten contexts for _, c := range rsc.Contexts { - chkMap := make(map[string]interface{}) - chkMap["context"] = c - chkMap["app_id"] = -1 - checks = append(checks, chkMap) + // Parse into contexts + contexts = append(contexts, c) + checks = append(contexts, c) } // Flatten checks for _, chk := range rsc.Checks { - chkMap := make(map[string]interface{}) - chkMap["context"] = chk.Context - chkMap["app_id"] = chk.AppID - checks = append(checks, chkMap) + // Parse into contexts + contexts = append(contexts, chk.Context) + checks = append(contexts, fmt.Sprintf("%s:%d", chk.Context, chk.AppID)) // buildTwoPartID(chk.Context, strconv.Itoa(int(*chk.AppID)))) } return d.Set("required_status_checks", []interface{}{ map[string]interface{}{ "strict": rsc.Strict, - // TODO: As above, remove if unneeded - //"contexts": schema.NewSet(schema.HashString, contexts), - "check": checks, + // TODO: Remove once contexts is fully deprecated. + "contexts": schema.NewSet(schema.HashString, contexts), + "checks": schema.NewSet(schema.HashString, checks), }, }) } @@ -211,9 +211,8 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC var rscChecks []*github.RequiredStatusCheck - // Iterate and parse contexts into checks objects as contexts is deprecated. - // TODO: Remove this code once contexts is fully deprecated - // Iterate and parse contexts + // TODO: Remove once contexts is deprecated + // Iterate and parse contexts into checks using -1 as default to allow checks from all apps. contexts := expandNestedSet(m, "contexts") for _, c := range contexts { appID := int64(-1) // Default @@ -224,24 +223,37 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC } // Iterate and parse checks - checks := m["check"].([]interface{}) + checks := expandNestedSet(m, "checks") for _, c := range checks { - chk := c.(map[string]interface{}) - var cContext string - if cContext, ok = chk["context"].(string); !ok { - return nil, errors.New("could not parse 'context' for required_status_checks check") + // Expect a string of "context:app_id", allowing for the absence of "app_id" + parts := strings.SplitN(c, ":", 2) + var cContext, cAppId string + switch len(parts) { + case 1: + cContext, cAppId = parts[0], "" + case 2: + cContext, cAppId = parts[0], parts[1] + default: + return nil, errors.New(fmt.Sprintf("Could not parse check '%s'. Expected `context:app_id` or `context`", c)) } - var cAppId int - if cAppId, ok = chk["app_id"].(int); !ok { - log.Printf("[DEBUG] app_id value: %v", chk["app_id"].(int)) - return nil, errors.New("could not parse 'app_id' for required_status_checks check") + + var rscCheck *github.RequiredStatusCheck + if cAppId != "" { + // If we have a valid app_id, include it in the RSC + rscAppId, err := strconv.Atoi(cAppId) + if err != nil { + return nil, errors.New(fmt.Sprintf("Could not parse %v as valid app_id", cAppId)) + } + rscAppId64 := int64(rscAppId) + rscCheck = &github.RequiredStatusCheck{Context: cContext, AppID: &rscAppId64} + } else { + // Else simply provide the context + rscCheck = &github.RequiredStatusCheck{Context: cContext} } - rscAppId := int64(cAppId) - rscChecks = append(rscChecks, &github.RequiredStatusCheck{ - Context: cContext, - AppID: &rscAppId, - }) + + // Append + rscChecks = append(rscChecks, rscCheck) } // Assign after looping both checks and contexts rsc.Checks = rscChecks From 36e85f51665cbbd3b48ed538ee761a1949f7c891 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Tue, 13 Dec 2022 11:33:36 +1300 Subject: [PATCH 14/19] chore: resolve incorrect merge of main --- .github/workflows/add_to_octokit_project.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/.github/workflows/add_to_octokit_project.yml b/.github/workflows/add_to_octokit_project.yml index 1883634968..53565f62cd 100644 --- a/.github/workflows/add_to_octokit_project.yml +++ b/.github/workflows/add_to_octokit_project.yml @@ -17,6 +17,5 @@ jobs: with: project-url: https://github.com/orgs/octokit/projects/10 github-token: ${{ secrets.OCTOKITBOT_PROJECT_ACTION_TOKEN }} - labeled: 'Status: Stale' labeled: "Status: Stale" label-operator: NOT From 47cb610de2c666ebc12c32f88d007ba2078b12f1 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Tue, 13 Dec 2022 11:34:15 +1300 Subject: [PATCH 15/19] chore: update deprecation notice on contexts array --- github/resource_github_branch_protection_v3.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github/resource_github_branch_protection_v3.go b/github/resource_github_branch_protection_v3.go index 5627d1f3ba..d18fcfc7b1 100644 --- a/github/resource_github_branch_protection_v3.go +++ b/github/resource_github_branch_protection_v3.go @@ -55,7 +55,7 @@ func resourceGithubBranchProtectionV3() *schema.Resource { "contexts": { Type: schema.TypeSet, Optional: true, - Deprecated: "GitHub is deprecating the use of `contexts`. Use `check` blocks instead.", + Deprecated: "GitHub is deprecating the use of `contexts`. Use a `checks` array instead.", Elem: &schema.Schema{ Type: schema.TypeString, }, From 0d421239d72549878a5e07ff46282bc95ba6b6c6 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Tue, 13 Dec 2022 11:48:55 +1300 Subject: [PATCH 16/19] chore(docs): Update branch_protection_v3 docs to mention the new `checks` functionality --- website/docs/r/branch_protection_v3.html.markdown | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/website/docs/r/branch_protection_v3.html.markdown b/website/docs/r/branch_protection_v3.html.markdown index 12a7c25efd..4194fba8e7 100644 --- a/website/docs/r/branch_protection_v3.html.markdown +++ b/website/docs/r/branch_protection_v3.html.markdown @@ -29,8 +29,8 @@ resource "github_branch_protection_v3" "example" { ```hcl # Protect the main branch of the foo repository. Additionally, require that -# the "ci/travis" context to be passing and only allow the engineers team merge -# to the branch. +# the "ci/check" check ran by the Github Actions app is passing and only allow +# the engineers team merge to the branch. resource "github_branch_protection_v3" "example" { repository = github_repository.example.name @@ -39,7 +39,9 @@ resource "github_branch_protection_v3" "example" { required_status_checks { strict = false - contexts = ["ci/travis"] + checks = [ + "ci/check:824642007264" + ] } required_pull_request_reviews { @@ -88,7 +90,8 @@ The following arguments are supported: `required_status_checks` supports the following arguments: * `strict`: (Optional) Require branches to be up to date before merging. Defaults to `false`. -* `contexts`: (Optional) The list of status checks to require in order to merge into this branch. No status checks are required by default. +* `contexts`: [**DEPRECATED**] (Optional) The list of status checks to require in order to merge into this branch. No status checks are required by default. +* `checks`: (Optional) The list of status checks to require in order to merge into this branch. No status checks are required by default. Checks should be strings containing the context and app_id like so "context:app_id". ### Required Pull Request Reviews From 422f731f9f36cf76e696ce97de2681ae9577c351 Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Tue, 13 Dec 2022 11:49:47 +1300 Subject: [PATCH 17/19] fix: Initialise literal empty slice of RequiredStatusCheck to mitigate errors when passing nil to the sdk --- github/resource_github_branch_protection_v3_utils.go | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index 74f9e41bb5..f82da89c6b 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -209,7 +209,9 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC m := v.(map[string]interface{}) rsc.Strict = m["strict"].(bool) - var rscChecks []*github.RequiredStatusCheck + // Initialise empty literal to ensure an empty array is passed mitigating schema errors like so: + // For 'anyOf/1', {"strict"=>true, "checks"=>nil} is not a null. [] + rscChecks := []*github.RequiredStatusCheck{} // TODO: Remove once contexts is deprecated // Iterate and parse contexts into checks using -1 as default to allow checks from all apps. From 6600e7b6065e644b0638018a5ddcb2c96c9e6fee Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Tue, 13 Dec 2022 15:32:49 +1300 Subject: [PATCH 18/19] chore(lint): resolve gosimple S1082 violation (errors.New => fmt.Errorf) --- github/resource_github_branch_protection_v3_utils.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index f82da89c6b..5994ff723f 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -237,7 +237,7 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC case 2: cContext, cAppId = parts[0], parts[1] default: - return nil, errors.New(fmt.Sprintf("Could not parse check '%s'. Expected `context:app_id` or `context`", c)) + return nil, fmt.Errorf("Could not parse check '%s'. Expected `context:app_id` or `context`", c) } var rscCheck *github.RequiredStatusCheck @@ -245,7 +245,7 @@ func expandRequiredStatusChecks(d *schema.ResourceData) (*github.RequiredStatusC // If we have a valid app_id, include it in the RSC rscAppId, err := strconv.Atoi(cAppId) if err != nil { - return nil, errors.New(fmt.Sprintf("Could not parse %v as valid app_id", cAppId)) + return nil, fmt.Errorf("Could not parse %v as valid app_id", cAppId) } rscAppId64 := int64(rscAppId) rscCheck = &github.RequiredStatusCheck{Context: cContext, AppID: &rscAppId64} From cdf30eb569a1ce05c5db420fe404fb127237aa6e Mon Sep 17 00:00:00 2001 From: TheQueenIsDead <30706552+TheQueenIsDead@users.noreply.github.com> Date: Wed, 11 Jan 2023 08:21:51 +1300 Subject: [PATCH 19/19] chore: remove unused code comment --- github/resource_github_branch_protection_v3_utils.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/github/resource_github_branch_protection_v3_utils.go b/github/resource_github_branch_protection_v3_utils.go index 5994ff723f..97a0861b23 100644 --- a/github/resource_github_branch_protection_v3_utils.go +++ b/github/resource_github_branch_protection_v3_utils.go @@ -59,7 +59,7 @@ func flattenAndSetRequiredStatusChecks(d *schema.ResourceData, protection *githu for _, chk := range rsc.Checks { // Parse into contexts contexts = append(contexts, chk.Context) - checks = append(contexts, fmt.Sprintf("%s:%d", chk.Context, chk.AppID)) // buildTwoPartID(chk.Context, strconv.Itoa(int(*chk.AppID)))) + checks = append(contexts, fmt.Sprintf("%s:%d", chk.Context, chk.AppID)) } return d.Set("required_status_checks", []interface{}{