feat: add repository resource (#5)

This commit is contained in:
Dawid Wysokiński 2023-09-02 07:11:10 +02:00 committed by GitHub
parent 860baf9957
commit a2c6aac53d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 775 additions and 45 deletions

View File

@ -33,8 +33,8 @@ data "woodpecker_user" "user" {
### Read-Only
- `active` (Boolean) whether user is active in the system
- `admin` (Boolean) whether user is an admin
- `avatar` (String) the user's avatar URL
- `avatar_url` (String) the user's avatar URL
- `email` (String) the user's email
- `id` (Number) the user's id
- `is_active` (Boolean) whether user is active in the system
- `is_admin` (Boolean) whether user is an admin

View File

@ -0,0 +1,51 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "woodpecker_repository Resource - terraform-provider-woodpecker"
subcategory: ""
description: |-
Provides a repository resource.
---
# woodpecker_repository (Resource)
Provides a repository resource.
## Example Usage
```terraform
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
is_trusted = true
visibility = "public"
}
```
<!-- schema generated by tfplugindocs -->
## Schema
### Required
- `full_name` (String) the full name of the repository (format: owner/reponame)
### Optional
- `allow_pull_requests` (Boolean) Enables handling webhook's pull request event. If disabled, then pipeline won't run for pull requests.
- `config_file` (String) The path to the pipeline config file or folder. By default it is left empty which will use the following configuration resolution .woodpecker/*.yml -> .woodpecker/*.yaml -> .woodpecker.yml -> .woodpecker.yaml.
- `is_gated` (Boolean) when true, every pipeline needs to be approved before being executed
- `is_trusted` (Boolean) when true, underlying pipeline containers get access to escalated capabilities like mounting volumes
- `netrc_only_trusted` (Boolean) whether netrc credentials should be only injected into trusted containers, see [the docs](https://woodpecker-ci.org/docs/usage/project-settings#only-inject-netrc-credentials-into-trusted-containers) for more info
- `timeout` (Number) after this timeout a pipeline has to finish or will be treated as timed out (in minutes)
- `visibility` (String) project visibility (public, private, internal), see [the docs](https://woodpecker-ci.org/docs/usage/project-settings#project-visibility) for more info
### Read-Only
- `avatar_url` (String) the repository's avatar URL
- `clone_url` (String) the URL to clone repository
- `default_branch` (String) the name of the default branch
- `forge_remote_id` (String) the unique identifier for the repository on the forge
- `id` (Number) the repository's id
- `is_private` (Boolean) whether the repo (SCM) is private
- `name` (String) the name of the repository
- `owner` (String) the owner of the repository
- `scm` (String) type of repository (see [the source code](https://github.com/woodpecker-ci/woodpecker/blob/main/server/model/const.go#L67))
- `url` (String) the URL of the repository on the forge

View File

@ -33,11 +33,11 @@ resource "woodpecker_user" "test" {
### Optional
- `admin` (Boolean) whether user is an admin
- `avatar` (String) the user's avatar URL
- `avatar_url` (String) the user's avatar URL
- `email` (String) the email of the user
- `is_admin` (Boolean) whether user is an admin
### Read-Only
- `active` (Boolean) whether user is active in the system
- `id` (Number) the user's id
- `is_active` (Boolean) whether user is active in the system

View File

@ -0,0 +1,5 @@
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
is_trusted = true
visibility = "public"
}

View File

@ -40,15 +40,15 @@ func (d *userDataSource) Schema(_ context.Context, _ datasource.SchemaRequest, r
Computed: true,
Description: "the user's email",
},
"avatar": schema.StringAttribute{
"avatar_url": schema.StringAttribute{
Computed: true,
Description: "the user's avatar URL",
},
"active": schema.BoolAttribute{
"is_active": schema.BoolAttribute{
Computed: true,
Description: "whether user is active in the system",
},
"admin": schema.BoolAttribute{
"is_admin": schema.BoolAttribute{
Computed: true,
Description: "whether user is an admin",
},

View File

@ -23,9 +23,9 @@ func TestDataSourceUser(t *testing.T) {
resource.TestCheckResourceAttr("data.woodpecker_user.current", "id", strconv.FormatInt(user.ID, 10)),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "login", user.Login),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "email", user.Email),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "avatar", user.Avatar),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "admin", strconv.FormatBool(user.Admin)),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "active", strconv.FormatBool(user.Active)),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "avatar_url", user.Avatar),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "is_admin", strconv.FormatBool(user.Admin)),
resource.TestCheckResourceAttr("data.woodpecker_user.current", "is_active", strconv.FormatBool(user.Active)),
),
},
{
@ -34,9 +34,9 @@ func TestDataSourceUser(t *testing.T) {
resource.TestCheckResourceAttr("data.woodpecker_user.user", "id", strconv.FormatInt(user.ID, 10)),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "login", user.Login),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "email", user.Email),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "avatar", user.Avatar),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "admin", strconv.FormatBool(user.Admin)),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "active", strconv.FormatBool(user.Active)),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "avatar_url", user.Avatar),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "is_admin", strconv.FormatBool(user.Admin)),
resource.TestCheckResourceAttr("data.woodpecker_user.user", "is_active", strconv.FormatBool(user.Active)),
),
},
},

View File

@ -9,19 +9,19 @@ import (
)
type userModel struct {
ID types.Int64 `tfsdk:"id"`
Login types.String `tfsdk:"login"`
Email types.String `tfsdk:"email"`
Avatar types.String `tfsdk:"avatar"`
Active types.Bool `tfsdk:"active"`
Admin types.Bool `tfsdk:"admin"`
ID types.Int64 `tfsdk:"id"`
Login types.String `tfsdk:"login"`
Email types.String `tfsdk:"email"`
AvatarURL types.String `tfsdk:"avatar_url"`
Active types.Bool `tfsdk:"is_active"`
Admin types.Bool `tfsdk:"is_admin"`
}
func (m *userModel) setValues(_ context.Context, user *woodpecker.User) diag.Diagnostics {
m.ID = types.Int64Value(user.ID)
m.Login = types.StringValue(user.Login)
m.Email = types.StringValue(user.Email)
m.Avatar = types.StringValue(user.Avatar)
m.AvatarURL = types.StringValue(user.Avatar)
m.Active = types.BoolValue(user.Active)
m.Admin = types.BoolValue(user.Admin)
return nil
@ -32,7 +32,7 @@ func (m *userModel) toWoodpeckerModel(_ context.Context) (*woodpecker.User, diag
ID: m.ID.ValueInt64(),
Login: m.Login.ValueString(),
Email: m.Email.ValueString(),
Avatar: m.Avatar.ValueString(),
Avatar: m.AvatarURL.ValueString(),
Active: m.Active.ValueBool(),
Admin: m.Admin.ValueBool(),
}, nil
@ -99,3 +99,57 @@ func (m *secretDataSourceModel) setValues(ctx context.Context, secret *woodpecke
return diagsRes
}
type repositoryModel struct {
ID types.Int64 `tfsdk:"id"`
ForgeRemoteID types.String `tfsdk:"forge_remote_id"`
Owner types.String `tfsdk:"owner"`
Name types.String `tfsdk:"name"`
FullName types.String `tfsdk:"full_name"`
AvatarURL types.String `tfsdk:"avatar_url"`
URL types.String `tfsdk:"url"`
CloneURL types.String `tfsdk:"clone_url"`
DefaultBranch types.String `tfsdk:"default_branch"`
SCMKind types.String `tfsdk:"scm"`
Timeout types.Int64 `tfsdk:"timeout"`
Visibility types.String `tfsdk:"visibility"`
IsSCMPrivate types.Bool `tfsdk:"is_private"`
IsTrusted types.Bool `tfsdk:"is_trusted"`
IsGated types.Bool `tfsdk:"is_gated"`
AllowPullRequests types.Bool `tfsdk:"allow_pull_requests"`
ConfigFile types.String `tfsdk:"config_file"`
NetrcOnlyTrusted types.Bool `tfsdk:"netrc_only_trusted"`
}
func (m *repositoryModel) setValues(_ context.Context, repo *woodpecker.Repo) diag.Diagnostics {
m.ID = types.Int64Value(repo.ID)
m.ForgeRemoteID = types.StringValue(repo.ForgeRemoteID)
m.Owner = types.StringValue(repo.Owner)
m.Name = types.StringValue(repo.Name)
m.FullName = types.StringValue(repo.FullName)
m.AvatarURL = types.StringValue(repo.Avatar)
m.URL = types.StringValue(repo.Link)
m.CloneURL = types.StringValue(repo.Clone)
m.DefaultBranch = types.StringValue(repo.DefaultBranch)
m.SCMKind = types.StringValue(repo.SCMKind)
m.Timeout = types.Int64Value(repo.Timeout)
m.Visibility = types.StringValue(repo.Visibility)
m.IsSCMPrivate = types.BoolValue(repo.IsSCMPrivate)
m.IsTrusted = types.BoolValue(repo.IsTrusted)
m.IsGated = types.BoolValue(repo.IsGated)
m.AllowPullRequests = types.BoolValue(repo.AllowPullRequests)
m.ConfigFile = types.StringValue(repo.Config)
m.NetrcOnlyTrusted = types.BoolValue(repo.NetrcOnlyTrusted)
return nil
}
func (m *repositoryModel) toWoodpeckerPatch(ctx context.Context) (*woodpecker.RepoPatch, diag.Diagnostics) {
return &woodpecker.RepoPatch{
Config: m.ConfigFile.ValueStringPointer(),
IsTrusted: m.IsTrusted.ValueBoolPointer(),
IsGated: m.IsGated.ValueBoolPointer(),
Timeout: m.Timeout.ValueInt64Pointer(),
Visibility: m.Visibility.ValueStringPointer(),
AllowPull: m.AllowPullRequests.ValueBoolPointer(),
}, nil
}

View File

@ -63,6 +63,7 @@ func (p *woodpeckerProvider) Resources(_ context.Context) []func() resource.Reso
return []func() resource.Resource{
newUserResource,
newSecretResource,
newRepositoryResource,
}
}
@ -137,7 +138,7 @@ func newClient(
_, err := client.Self()
if err != nil {
resp.Diagnostics.AddError("Unable to login", err.Error())
resp.Diagnostics.AddError("Couldn't get current user", err.Error())
return nil
}

View File

@ -0,0 +1,347 @@
package internal
import (
"context"
"fmt"
"slices"
"strconv"
"github.com/hashicorp/terraform-plugin-framework-validators/int64validator"
"github.com/hashicorp/terraform-plugin-framework-validators/stringvalidator"
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/woodpecker-ci/woodpecker/woodpecker-go/woodpecker"
)
type repositoryResource struct {
client woodpecker.Client
}
var _ resource.Resource = (*repositoryResource)(nil)
var _ resource.ResourceWithConfigure = (*repositoryResource)(nil)
var _ resource.ResourceWithImportState = (*repositoryResource)(nil)
func newRepositoryResource() resource.Resource {
return &repositoryResource{}
}
func (r *repositoryResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_repository"
}
func (r *repositoryResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
MarkdownDescription: `Provides a repository resource.`,
Attributes: map[string]schema.Attribute{
"id": schema.Int64Attribute{
Computed: true,
Description: "the repository's id",
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"forge_remote_id": schema.StringAttribute{
Computed: true,
Description: "the unique identifier for the repository on the forge",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"owner": schema.StringAttribute{
Computed: true,
Description: "the owner of the repository",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
Computed: true,
Description: "the name of the repository",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"full_name": schema.StringAttribute{
Required: true,
Description: "the full name of the repository (format: owner/reponame)",
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"avatar_url": schema.StringAttribute{
Computed: true,
Description: "the repository's avatar URL",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"url": schema.StringAttribute{
Computed: true,
Description: "the URL of the repository on the forge",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"clone_url": schema.StringAttribute{
Computed: true,
Description: "the URL to clone repository",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"default_branch": schema.StringAttribute{
Computed: true,
Description: "the name of the default branch",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"scm": schema.StringAttribute{
Computed: true,
MarkdownDescription: "type of repository " +
"(see [the source code](https://github.com/woodpecker-ci/woodpecker/blob/main/server/model/const.go#L67))",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"timeout": schema.Int64Attribute{
Optional: true,
Computed: true,
Description: "after this timeout a pipeline has to finish or will be treated as timed out (in minutes)",
Validators: []validator.Int64{
int64validator.AtLeast(1),
},
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"visibility": schema.StringAttribute{
Optional: true,
Computed: true,
MarkdownDescription: "project visibility (public, private, internal), " +
"see [the docs](https://woodpecker-ci.org/docs/usage/project-settings#project-visibility) for more info",
Validators: []validator.String{
stringvalidator.OneOfCaseInsensitive("public", "private", "internal"),
},
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"is_private": schema.BoolAttribute{
Computed: true,
Description: "whether the repo (SCM) is private",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"is_trusted": schema.BoolAttribute{
Optional: true,
Computed: true,
Description: "when true, underlying pipeline containers get access to escalated capabilities like mounting volumes",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"is_gated": schema.BoolAttribute{
Optional: true,
Computed: true,
Description: "when true, every pipeline needs to be approved before being executed",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"allow_pull_requests": schema.BoolAttribute{
Optional: true,
Computed: true,
Description: "Enables handling webhook's pull request event. If disabled, then pipeline won't run for pull requests.",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"config_file": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "The path to the pipeline config file or folder. " +
"By default it is left empty which will use the following configuration " +
"resolution .woodpecker/*.yml -> .woodpecker/*.yaml -> .woodpecker.yml -> .woodpecker.yaml.",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
// woodpecker.Client doesn't support editing this field for now
// "cancel_previous_pipeline_events": schema.SetAttribute{
// ElementType: types.StringType,
// Optional: true,
// Computed: true,
// Description: "Enables to cancel pending and running pipelines of the same " +
// "event and context before starting the newly triggered one (push, tag, pull_request, deployment).",
// Validators: []validator.Set{
// setvalidator.ValueStringsAre(
// stringvalidator.OneOfCaseInsensitive("push", "tag", "pull_request", "deployment"),
// ),
// },
// },
"netrc_only_trusted": schema.BoolAttribute{
Optional: true,
Computed: true,
MarkdownDescription: "whether netrc credentials should be only injected into trusted containers, " +
"see [the docs](https://woodpecker-ci.org/docs/usage/project-settings#only-inject-netrc-credentials-into-trusted-containers) for more info",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
},
}
}
func (r *repositoryResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
// Prevent panic if the provider has not been configured.
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(woodpecker.Client)
if !ok {
resp.Diagnostics.AddError(
"Unexpected Data Source Configure Type",
fmt.Sprintf("Expected woodpecker.Client, got: %T. Please report this issue to the provider developers.", req.ProviderData),
)
return
}
r.client = client
}
func (r *repositoryResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var data repositoryModel
resp.Diagnostics.Append(req.Config.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
repoFullName := data.FullName.ValueString()
repos, err := r.client.RepoListOpts(true, true)
if err != nil {
resp.Diagnostics.AddError("Couldn't list repositories", err.Error())
return
}
idx := slices.IndexFunc(repos, func(repo *woodpecker.Repo) bool {
return repo.FullName == repoFullName
})
if idx < 0 {
resp.Diagnostics.AddError("Repository not found", fmt.Sprintf("Repository with name '%s' not found", repoFullName))
return
}
wData, diags := data.toWoodpeckerPatch(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
forgeRemoteID, err := strconv.ParseInt(repos[idx].ForgeRemoteID, 10, 64)
if err != nil {
resp.Diagnostics.AddError("Couldn't parse ForgeRemoteID", err.Error())
return
}
// I'm not sure why this function wants int64 instead of string
activatedRepo, err := r.client.RepoPost(forgeRemoteID)
if err != nil {
resp.Diagnostics.AddError("Couldn't activate repository", err.Error())
return
}
updatedRepo, err := r.client.RepoPatch(activatedRepo.ID, wData)
if err != nil {
resp.Diagnostics.AddError("Couldn't update repository", err.Error())
return
}
resp.Diagnostics.Append(data.setValues(ctx, updatedRepo)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *repositoryResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var data repositoryModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
repo, err := r.client.RepoLookup(data.FullName.ValueString())
if err != nil {
resp.Diagnostics.AddError("Couldn't get repository", err.Error())
}
resp.Diagnostics.Append(data.setValues(ctx, repo)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *repositoryResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var data repositoryModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
wData, diags := data.toWoodpeckerPatch(ctx)
resp.Diagnostics.Append(diags...)
if resp.Diagnostics.HasError() {
return
}
repo, err := r.client.RepoPatch(data.ID.ValueInt64(), wData)
if err != nil {
resp.Diagnostics.AddError("Couldn't update repository", err.Error())
return
}
resp.Diagnostics.Append(data.setValues(ctx, repo)...)
if resp.Diagnostics.HasError() {
return
}
resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
}
func (r *repositoryResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var data repositoryModel
resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.RepoDel(data.ID.ValueInt64()); err != nil {
resp.Diagnostics.AddError("Couldn't delete repository", err.Error())
return
}
// If execution completes without error, the framework will automatically
// call DeleteResponse.State.RemoveResource(), so it can be omitted
// from provider logic.
}
func (r *repositoryResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resp.Diagnostics.Append(resp.State.SetAttribute(ctx, path.Root("full_name"), req.ID)...)
}

View File

@ -0,0 +1,235 @@
package internal_test
import (
"errors"
"fmt"
"regexp"
"slices"
"strconv"
"testing"
"code.gitea.io/sdk/gitea"
"github.com/google/uuid"
"github.com/hashicorp/terraform-plugin-testing/helper/resource"
"github.com/hashicorp/terraform-plugin-testing/plancheck"
"github.com/hashicorp/terraform-plugin-testing/terraform"
"github.com/woodpecker-ci/woodpecker/woodpecker-go/woodpecker"
)
func TestResourceRepository(t *testing.T) {
t.Parallel()
t.Run("OK", func(t *testing.T) {
t.Parallel()
repo1, repo2 := createRepo(t), createRepo(t)
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
CheckDestroy: testAccCheckRepositoryResourceDestroy(repo1.FullName, repo2.FullName),
Steps: []resource.TestStep{
{ // create repo
Config: fmt.Sprintf(`
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
is_trusted = true
visibility = "public"
}
`, repo1.FullName),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("woodpecker_repository.test_repo", "id"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "forge_remote_id", strconv.FormatInt(repo1.ID, 10)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "name", repo1.Name),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "owner", repo1.Owner.UserName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "full_name", repo1.FullName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "url", repo1.HTMLURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "clone_url", repo1.CloneURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "default_branch", repo1.DefaultBranch),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "scm", "git"),
resource.TestCheckResourceAttrSet("woodpecker_repository.test_repo", "timeout"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "visibility", "public"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_private", strconv.FormatBool(repo1.Private)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_trusted", "true"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_gated", "false"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "allow_pull_requests", "true"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "config_file", ""),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "netrc_only_trusted", "true"),
),
},
{ // update repo
Config: fmt.Sprintf(`
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
is_trusted = false
visibility = "private"
is_gated = true
timeout = 30
config_file = ".woodpecker2.yaml"
}
`, repo1.FullName),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("woodpecker_repository.test_repo", "id"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "forge_remote_id", strconv.FormatInt(repo1.ID, 10)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "name", repo1.Name),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "owner", repo1.Owner.UserName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "full_name", repo1.FullName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "url", repo1.HTMLURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "clone_url", repo1.CloneURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "default_branch", repo1.DefaultBranch),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "scm", "git"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "timeout", "30"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "visibility", "private"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_private", strconv.FormatBool(repo1.Private)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_trusted", "false"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_gated", "true"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "allow_pull_requests", "true"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "config_file", ".woodpecker2.yaml"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "netrc_only_trusted", "true"),
),
},
{ // update repo
Config: fmt.Sprintf(`
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
timeout = 15
}
//`, repo1.FullName),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("woodpecker_repository.test_repo", "id"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "forge_remote_id", strconv.FormatInt(repo1.ID, 10)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "name", repo1.Name),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "owner", repo1.Owner.UserName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "full_name", repo1.FullName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "url", repo1.HTMLURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "clone_url", repo1.CloneURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "default_branch", repo1.DefaultBranch),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "scm", "git"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "timeout", "15"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "visibility", "private"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_private", strconv.FormatBool(repo1.Private)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_trusted", "false"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_gated", "true"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "allow_pull_requests", "true"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "config_file", ".woodpecker2.yaml"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "netrc_only_trusted", "true"),
),
},
{ // import
ResourceName: "woodpecker_repository.test_repo",
ImportState: true,
ImportStateId: repo1.FullName,
ImportStateVerify: true,
},
{ // replace repo
Config: fmt.Sprintf(`
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
}
`, repo2.FullName),
ConfigPlanChecks: resource.ConfigPlanChecks{
PreApply: []plancheck.PlanCheck{
plancheck.ExpectResourceAction("woodpecker_repository.test_repo", plancheck.ResourceActionReplace),
},
},
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("woodpecker_repository.test_repo", "id"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "forge_remote_id", strconv.FormatInt(repo2.ID, 10)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "name", repo2.Name),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "owner", repo2.Owner.UserName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "full_name", repo2.FullName),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "url", repo2.HTMLURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "clone_url", repo2.CloneURL),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "default_branch", repo2.DefaultBranch),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "scm", "git"),
resource.TestCheckResourceAttrSet("woodpecker_repository.test_repo", "timeout"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "visibility", "public"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_private", strconv.FormatBool(repo2.Private)),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_trusted", "false"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "is_gated", "false"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "allow_pull_requests", "true"),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "config_file", ""),
resource.TestCheckResourceAttr("woodpecker_repository.test_repo", "netrc_only_trusted", "true"),
),
},
},
})
})
t.Run("ERR: incorrect visibility value", func(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(`
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
visibility = "asdf"
}
`, uuid.NewString()),
ExpectError: regexp.MustCompile(`Attribute visibility value must be one of`),
},
},
})
})
t.Run("ERR: timeout needs to be >= 1", func(t *testing.T) {
t.Parallel()
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{
Config: fmt.Sprintf(`
resource "woodpecker_repository" "test_repo" {
full_name = "%s"
timeout = 0
}
`, uuid.NewString()),
ExpectError: regexp.MustCompile(`Attribute timeout value must be at least 1`),
},
},
})
})
}
func testAccCheckRepositoryResourceDestroy(names ...string) func(state *terraform.State) error {
return func(state *terraform.State) error {
repos, err := woodpeckerClient.RepoListOpts(true, true)
if err != nil {
return fmt.Errorf("couldn't list repos: %w", err)
}
if slices.ContainsFunc(repos, func(repo *woodpecker.Repo) bool {
return slices.Contains(names, repo.FullName) && repo.IsActive
}) {
return errors.New("at least one of the repositories isn't inactive")
}
return nil
}
}
func createRepo(tb testing.TB) *gitea.Repository {
tb.Helper()
repo, _, err := giteaClient.CreateRepo(gitea.CreateRepoOption{
Name: uuid.NewString(),
Description: uuid.NewString(),
Private: false,
AutoInit: true,
Template: false,
License: "MIT",
Readme: "Default",
DefaultBranch: "master",
})
if err != nil {
tb.Fatalf("got unexpected error while creating repo: %s", err)
}
return repo
}

View File

@ -9,7 +9,10 @@ import (
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/setplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/schema/validator"
"github.com/hashicorp/terraform-plugin-framework/types"
@ -41,6 +44,9 @@ func (r *secretResource) Schema(_ context.Context, _ resource.SchemaRequest, res
"id": schema.Int64Attribute{
Computed: true,
Description: "the secret's id",
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"name": schema.StringAttribute{
Required: true,
@ -53,6 +59,9 @@ func (r *secretResource) Schema(_ context.Context, _ resource.SchemaRequest, res
Required: true,
Description: "the value of the secret",
Sensitive: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"events": schema.SetAttribute{
ElementType: types.StringType,
@ -63,17 +72,26 @@ func (r *secretResource) Schema(_ context.Context, _ resource.SchemaRequest, res
stringvalidator.OneOfCaseInsensitive("push", "tag", "pull_request", "deployment", "cron", "manual"),
),
},
PlanModifiers: []planmodifier.Set{
setplanmodifier.UseStateForUnknown(),
},
},
"plugins_only": schema.BoolAttribute{
Optional: true,
Computed: true,
MarkdownDescription: "whether secret is only available for [plugins](https://woodpecker-ci.org/docs/usage/plugins/plugins)",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"images": schema.SetAttribute{
ElementType: types.StringType,
Optional: true,
Computed: true,
Description: "list of Docker images for which this secret is available, leave blank to allow all images",
PlanModifiers: []planmodifier.Set{
setplanmodifier.UseStateForUnknown(),
},
},
},
}

View File

@ -64,12 +64,12 @@ resource "woodpecker_secret" "test_secret" {
resource.TestCheckTypeSetElemAttr("woodpecker_secret.test_secret", "images.*", "testimage"),
),
},
{ // fields shouldn't be overridden
{ // update secret
Config: fmt.Sprintf(`
resource "woodpecker_secret" "test_secret" {
name = "%s"
value = "test123123"
events = ["push", "deployment"]
events = ["push", "deployment", "cron"]
}
//`, name),
Check: resource.ComposeAggregateTestCheckFunc(
@ -78,6 +78,7 @@ resource "woodpecker_secret" "test_secret" {
resource.TestCheckResourceAttr("woodpecker_secret.test_secret", "value", "test123123"),
resource.TestCheckTypeSetElemAttr("woodpecker_secret.test_secret", "events.*", "push"),
resource.TestCheckTypeSetElemAttr("woodpecker_secret.test_secret", "events.*", "deployment"),
resource.TestCheckTypeSetElemAttr("woodpecker_secret.test_secret", "events.*", "cron"),
resource.TestCheckResourceAttr("woodpecker_secret.test_secret", "plugins_only", "true"),
resource.TestCheckTypeSetElemAttr("woodpecker_secret.test_secret", "images.*", "testimage"),
),
@ -121,7 +122,7 @@ resource "woodpecker_secret" "test_secret" {
PreCheck: func() { testAccPreCheck(t) },
ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
Steps: []resource.TestStep{
{ // create secret
{
Config: fmt.Sprintf(`
resource "woodpecker_secret" "test_secret" {
name = "%s"

View File

@ -7,6 +7,8 @@ import (
"github.com/hashicorp/terraform-plugin-framework/path"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/resource/schema"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/boolplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/int64planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/woodpecker-ci/woodpecker/woodpecker-go/woodpecker"
@ -38,6 +40,9 @@ This resource allows you to add/remove users. When applied, a new user will be c
"id": schema.Int64Attribute{
Computed: true,
Description: "the user's id",
PlanModifiers: []planmodifier.Int64{
int64planmodifier.UseStateForUnknown(),
},
},
"login": schema.StringAttribute{
Required: true,
@ -50,20 +55,32 @@ This resource allows you to add/remove users. When applied, a new user will be c
Optional: true,
Computed: true,
Description: "the email of the user",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"avatar": schema.StringAttribute{
"avatar_url": schema.StringAttribute{
Optional: true,
Computed: true,
Description: "the user's avatar URL",
PlanModifiers: []planmodifier.String{
stringplanmodifier.UseStateForUnknown(),
},
},
"active": schema.BoolAttribute{
"is_active": schema.BoolAttribute{
Computed: true,
Description: "whether user is active in the system",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
"admin": schema.BoolAttribute{
"is_admin": schema.BoolAttribute{
Optional: true,
Computed: true,
Description: "whether user is an admin",
PlanModifiers: []planmodifier.Bool{
boolplanmodifier.UseStateForUnknown(),
},
},
},
}

View File

@ -34,9 +34,9 @@ resource "woodpecker_user" "test_user" {
resource.TestCheckResourceAttrSet("woodpecker_user.test_user", "id"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "login", login),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "email", ""),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar", ""),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "admin", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar_url", ""),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_admin", "false"),
),
},
{ // update user
@ -44,32 +44,33 @@ resource "woodpecker_user" "test_user" {
resource "woodpecker_user" "test_user" {
login = "%s"
email = "%s@localhost"
avatar = "http://localhost/%s"
admin = true
avatar_url = "http://localhost/%s"
is_admin = true
}
`, login, login, login),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("woodpecker_user.test_user", "id"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "login", login),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "email", login+"@localhost"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar", "http://localhost/"+login),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "admin", "true"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar_url", "http://localhost/"+login),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_admin", "true"),
),
},
{ // fields shouldn't be overridden
{ // update user
Config: fmt.Sprintf(`
resource "woodpecker_user" "test_user" {
login = "%s"
is_admin = false
}
`, login),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttrSet("woodpecker_user.test_user", "id"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "login", login),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "email", login+"@localhost"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar", "http://localhost/"+login),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "admin", "true"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar_url", "http://localhost/"+login),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_admin", "false"),
),
},
{ // import
@ -93,9 +94,9 @@ resource "woodpecker_user" "test_user" {
resource.TestCheckResourceAttrSet("woodpecker_user.test_user", "id"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "login", newLogin),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "email", ""),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar", ""),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "admin", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "avatar_url", ""),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_active", "false"),
resource.TestCheckResourceAttr("woodpecker_user.test_user", "is_admin", "false"),
),
},
},