Skip to content

Commit

Permalink
Branch restrictions - add support for branch types + update deps (#2)
Browse files Browse the repository at this point in the history
* update deps

* branching permissions support branch types

* remove imports

* docs
  • Loading branch information
DrFaust92 authored Dec 29, 2021
1 parent d322bd7 commit 18da777
Show file tree
Hide file tree
Showing 1,317 changed files with 101,711 additions and 215,408 deletions.
33 changes: 11 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,17 +1,4 @@
# Maintenance status

Unmaintained, maintainers needed! I just took the archived repository, and released it to the Terraform Registry. I'm not a Go developer, so I'll not be able to maintain this repository in the long run. PRs are welcome, and I'll try to merge and release them as frequently as possible.

If you would like Atlassian to take ownership of the provider, you can voice your opinion at [BCLOUD-17209](https://jira.atlassian.com/browse/BCLOUD-17209).

## History

- Initally created during an Atlassian [24h hackathon](https://www.atlassian.com/company/shipit) by @cwood
- Maintained by HashiCorp and @cwood with contributions from the community
- [Archived](https://www.terraform.io/docs/internals/archiving.html) by HashiCorp due not being maintained (likely related to not being published to the registry)
- Forked and published to [Terraform Registry](https://registry.terraform.io) by @aeirola

Terraform Provider
Bitbucket Terraform Provider
==================

- Website: https://www.terraform.io
Expand All @@ -24,7 +11,7 @@ Requirements
------------

- [Terraform](https://www.terraform.io/downloads.html) 0.12.x
- [Go](https://golang.org/doc/install) 1.11 (to build the provider plugin)
- [Go](https://golang.org/doc/install) 1.16 (to build the provider plugin)

Building The Provider
---------------------
Expand All @@ -47,6 +34,15 @@ Using the provider
----------------------

```hcl
terraform {
required_providers {
bitbucket = {
source = "DrFaust92/bitbucket"
version = "version-here"
}
}
}
# Configure the Bitbucket Provider
provider "bitbucket" {
username = "GobBluthe"
Expand Down Expand Up @@ -96,10 +92,3 @@ In order to run the full suite of Acceptance tests, run `make testacc`.
```sh
$ make testacc
```

About V1 APIs
------------------

This provider will not take any PRs about the v1 apis that dont have v2
equivalents. Please only focus on v2 apis when adding new featues to this
provider.
97 changes: 53 additions & 44 deletions bitbucket/resource_branch_restriction.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,24 @@ import (
"bytes"
"encoding/json"
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
"io/ioutil"
"log"
"net/url"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/validation"
)

// BranchRestriction is the data we need to send to create a new branch restriction for the repository
type BranchRestriction struct {
ID int `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
Pattern string `json:"pattern,omitempty"`
Value int `json:"value,omitempty"`
Users []User `json:"users,omitempty"`
Groups []Group `json:"groups,omitempty"`
ID int `json:"id,omitempty"`
Kind string `json:"kind,omitempty"`
BranchMatchkind string `json:"branch_match_kind,omitempty"`
BranchType string `json:"branch_type,omitempty"`
Pattern string `json:"pattern,omitempty"`
Value int `json:"value,omitempty"`
Users []User `json:"users,omitempty"`
Groups []Group `json:"groups,omitempty"`
}

// User is just the user struct we want to use for BranchRestrictions
Expand All @@ -38,7 +41,6 @@ func resourceBranchRestriction() *schema.Resource {
Read: resourceBranchRestrictionsRead,
Update: resourceBranchRestrictionsUpdate,
Delete: resourceBranchRestrictionsDelete,
Exists: resourceBranchRestrictionsExists,

Schema: map[string]*schema.Schema{
"owner": {
Expand All @@ -56,22 +58,36 @@ func resourceBranchRestriction() *schema.Resource {
Required: true,
ValidateFunc: validation.StringInSlice([]string{
"require_tasks_to_be_completed",
"allow_auto_merge_when_builds_pass",
"require_passing_builds_to_merge",
"force",
"require_all_dependencies_merged",
"require_commits_behind",
"restrict_merges, enforce_merge_checks",
"reset_pullrequest_changes_requested_on_change",
"require_no_changes_requested",
"smart_reset_pullrequest_approvals",
"push",
"require_approvals_to_merge",
"enforce_merge_checks",
"restrict_merges",
"require_default_reviewer_approvals_to_merge",
"reset_pullrequest_approvals_on_change",
"delete",
"require_default_reviewer_approvals_to_merge",
},
false),
}, false),
},
"branch_match_kind": {
Type: schema.TypeString,
Optional: true,
Default: "glob",
ValidateFunc: validation.StringInSlice([]string{"branching_model", "glob"}, false),
},
"pattern": {
Type: schema.TypeString,
Required: true,
Optional: true,
},
"branch_type": {
Type: schema.TypeString,
Optional: true,
ValidateFunc: validation.StringInSlice([]string{"feature", "bugfix", "release", "hotfix", "development", "production"}, false),
},
"users": {
Type: schema.TypeSet,
Expand Down Expand Up @@ -119,13 +135,27 @@ func createBranchRestriction(d *schema.ResourceData) *BranchRestriction {
groups = append(groups, Group{Owner: User{Username: m["owner"].(string)}, Slug: m["slug"].(string)})
}

return &BranchRestriction{
Kind: d.Get("kind").(string),
Pattern: d.Get("pattern").(string),
Value: d.Get("value").(int),
Users: users,
Groups: groups,
restict := &BranchRestriction{
Kind: d.Get("kind").(string),
Value: d.Get("value").(int),
Users: users,
Groups: groups,
}

if v, ok := d.GetOk("pattern"); ok {
restict.Pattern = v.(string)
}

if v, ok := d.GetOk("branch_type"); ok {
restict.BranchType = v.(string)
}

if v, ok := d.GetOk("branch_match_kind"); ok {
restict.BranchMatchkind = v.(string)
}

return restict

}

func resourceBranchRestrictionsCreate(d *schema.ResourceData, m interface{}) error {
Expand Down Expand Up @@ -191,6 +221,8 @@ func resourceBranchRestrictionsRead(d *schema.ResourceData, m interface{}) error
d.Set("value", branchRestriction.Value)
d.Set("users", branchRestriction.Users)
d.Set("groups", branchRestriction.Groups)
d.Set("branch_type", branchRestriction.BranchType)
d.Set("branch_match_kind", branchRestriction.BranchMatchkind)
}

return nil
Expand Down Expand Up @@ -227,26 +259,3 @@ func resourceBranchRestrictionsDelete(d *schema.ResourceData, m interface{}) err

return err
}

func resourceBranchRestrictionsExists(d *schema.ResourceData, m interface{}) (bool, error) {
client := m.(*Client)

if v := d.Id(); v != "" {
branchRestrictionsReq, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions/%s",
d.Get("owner").(string),
d.Get("repository").(string),
url.PathEscape(d.Id()),
))
if err != nil {
panic(err)
}

if branchRestrictionsReq.StatusCode != 200 {
return false, err
}

return true, nil
}

return false, nil
}
108 changes: 80 additions & 28 deletions bitbucket/resource_branch_restriction_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,60 +2,112 @@ package bitbucket

import (
"fmt"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
"net/url"
"os"
"testing"

"github.com/hashicorp/terraform-plugin-sdk/v2/helper/acctest"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccBitbucketBranchRestriction_basic(t *testing.T) {
var branchRestriction BranchRestriction
rName := acctest.RandomWithPrefix("tf-test")
testUser := os.Getenv("BITBUCKET_TEAM")
resourceName := "bitbucket_branch_restriction.test"

testUser := os.Getenv("BITBUCKET_USERNAME")
testAccBitbucketBranchRestrictionConfig := fmt.Sprintf(`
resource "bitbucket_repository" "test_repo" {
owner = "%s"
name = "test-repo-for-branch-restriction-test"
}
resource "bitbucket_branch_restriction" "test_repo_branch_restriction" {
owner = "%s"
repository = "${bitbucket_repository.test_repo.name}"
kind = "force"
pattern = "master"
}
`, testUser, testUser)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckBitbucketBranchRestrictionDestroy,
Steps: []resource.TestStep{
{
Config: testAccBitbucketBranchRestrictionConfig(testUser, rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckBitbucketBranchRestrictionExists(resourceName, &branchRestriction),
resource.TestCheckResourceAttrPair(resourceName, "repository", "bitbucket_repository.test", "name"),
resource.TestCheckResourceAttr(resourceName, "kind", "force"),
resource.TestCheckResourceAttr(resourceName, "pattern", "master"),
resource.TestCheckResourceAttr(resourceName, "branch_match_kind", "glob"),
),
},
},
})
}

func TestAccBitbucketBranchRestriction_model(t *testing.T) {
var branchRestriction BranchRestriction
rName := acctest.RandomWithPrefix("tf-test")
testUser := os.Getenv("BITBUCKET_TEAM")
resourceName := "bitbucket_branch_restriction.test"

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckBitbucketBranchRestrictionDestroy,
Steps: []resource.TestStep{
{
Config: testAccBitbucketBranchRestrictionConfig,
Config: testAccBitbucketBranchRestrictionModelConfig(testUser, rName),
Check: resource.ComposeTestCheckFunc(
testAccCheckBitbucketBranchRestrictionExists("bitbucket_branch_restriction.test_repo_branch_restriction", &branchRestriction),
testAccCheckBitbucketBranchRestrictionExists(resourceName, &branchRestriction),
resource.TestCheckResourceAttrPair(resourceName, "repository", "bitbucket_repository.test", "name"),
resource.TestCheckResourceAttr(resourceName, "kind", "force"),
resource.TestCheckResourceAttr(resourceName, "pattern", ""),
resource.TestCheckResourceAttr(resourceName, "branch_match_kind", "branching_model"),
resource.TestCheckResourceAttr(resourceName, "branch_type", "production"),
),
},
},
})
}

func testAccBitbucketBranchRestrictionConfig(testUser, rName string) string {
return fmt.Sprintf(`
resource "bitbucket_repository" "test" {
owner = %[1]q
name = %[2]q
}
resource "bitbucket_branch_restriction" "test" {
owner = %[1]q
repository = bitbucket_repository.test.name
kind = "force"
pattern = "master"
}
`, testUser, rName)
}

func testAccBitbucketBranchRestrictionModelConfig(testUser, rName string) string {
return fmt.Sprintf(`
resource "bitbucket_repository" "test" {
owner = %[1]q
name = %[2]q
}
resource "bitbucket_branch_restriction" "test" {
owner = %[1]q
repository = bitbucket_repository.test.name
kind = "force"
branch_match_kind = "branching_model"
branch_type = "production"
}
`, testUser, rName)
}

func testAccCheckBitbucketBranchRestrictionDestroy(s *terraform.State) error {
client := testAccProvider.Meta().(*Client)
rs, ok := s.RootModule().Resources["bitbucket_branch_restriction.test_repo_branch_restriction"]
if !ok {
return fmt.Errorf("Not found %s", "bitbucket_branch_restriction.test_repo_branch_restriction")
}

response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["repository"], url.PathEscape(rs.Primary.Attributes["id"])))
for _, rs := range s.RootModule().Resources {
if rs.Type != "bitbucket_branch_restriction" {
continue
}
response, err := client.Get(fmt.Sprintf("2.0/repositories/%s/%s/branch-restrictions/%s", rs.Primary.Attributes["owner"], rs.Primary.Attributes["repository"], url.PathEscape(rs.Primary.Attributes["id"])))

if err == nil {
return fmt.Errorf("The resource was found should have errored")
}
if err == nil {
return fmt.Errorf("The resource was found should have errored")
}

if response.StatusCode != 404 {
return fmt.Errorf("BranchRestriction still exists")
if response.StatusCode != 404 {
return fmt.Errorf("BranchRestriction still exists")
}
}

return nil
Expand Down
1 change: 1 addition & 0 deletions bitbucket/resource_repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ func resourceRepository() *schema.Resource {
"project_key": {
Type: schema.TypeString,
Optional: true,
Computed: true,
},
"is_private": {
Type: schema.TypeBool,
Expand Down
4 changes: 3 additions & 1 deletion docs/resources/branch_restriction.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ The following arguments are supported:
have write access to.
* `repository` - (Required) The name of the repository.
* `kind` - (Required) The type of restriction that is being applied. List of possible stages is [here](https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories/%7Bworkspace%7D/%7Brepo_slug%7D/branch-restrictions/%7Bid%7Da).
* `pattern` - (Required) The pattern to determine which branches will be restricted.
* `branch_match_kind` - (Optional) Indicates how the restriction is matched against a branch. The default is `glob`. Valid values: `branching_model`, `glob`
* `branch_type` - (Optional) Apply the restriction to branches of this type. Active when `branch_match_kind` is `branching_model`. The branch type will be calculated using the branching model configured for the repository. Valid values: `feature`, `bugfix`, `release`, `hotfix`, `development`, `production`.
* `pattern` - (Optional) Apply the restriction to branches that match this pattern. Active when `branch_match_kind` is `glob`. Will be empty when `branch_match_kind` is `branching_model`.
* `users` - (Optional) A list of users to use.
* `groups` - (Optional) A list of groups to use.
4 changes: 2 additions & 2 deletions go.mod
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
module github.com/terraform-providers/terraform-provider-bitbucket

require (
github.com/hashicorp/terraform-plugin-sdk/v2 v2.4.3
github.com/hashicorp/terraform-plugin-sdk/v2 v2.10.1
github.com/satori/go.uuid v1.2.0
)

go 1.13
go 1.16
Loading

0 comments on commit 18da777

Please sign in to comment.