18 Commits

Author SHA1 Message Date
benvin 0b4db409b0 Merge pull request 'feat: add artifactapi_local_pypi and artifactapi_local_rpm resources' (#8) from benvin/add-local-pypi-rpm-resources into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #8
2026-06-23 23:21:56 +10:00
unkinben 1bddc48e5a feat: add artifactapi_local_pypi and artifactapi_local_rpm resource types
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
2026-06-23 23:16:17 +10:00
benvin 4dcb3ac71a Merge pull request 'fix: escape shell variables in release pipeline' (#7) from benvin/fix-release-vars into main
ci/woodpecker/tag/release Pipeline was successful
Reviewed-on: #7
2026-06-23 00:42:40 +10:00
unkinben eeb4a60639 fix: escape shell variables in release pipeline
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
Woodpecker interpolates ${VERSION} as a CI variable (empty) before the
shell sees it. Use $$ escaping so the shell assignment and references
survive YAML interpolation.
2026-06-23 00:39:21 +10:00
benvin 41ef83ba34 Merge pull request 'fix: use python3 zipfile instead of zip binary' (#6) from benvin/fix-zip-packaging into main
ci/woodpecker/tag/release Pipeline failed
Reviewed-on: #6
2026-06-23 00:35:50 +10:00
unkinben 3d5154a12a fix: use python3 zipfile instead of zip binary for packaging
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
The almalinux9-gobuilder image doesn't have the zip binary and dnf
install is unreliable in CI. python3 is always available.
2026-06-23 00:31:53 +10:00
benvin ec9f7d410f Merge pull request 'feat: add zip packaging target and woodpecker release pipeline' (#5) from benvin/makefile-ci-upload into main
ci/woodpecker/tag/release Pipeline failed
Reviewed-on: #5
2026-06-23 00:21:30 +10:00
unkinben 03b3344d8f feat: add zip packaging target and woodpecker release pipeline
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
2026-06-23 00:18:06 +10:00
benvin 2dfbd1d799 Merge pull request 'feat: add artifactapi_local_terraform resource type' (#4) from benvin/add-local-terraform-resource into main
Reviewed-on: #4
2026-06-23 00:02:39 +10:00
benvin ddd9e41679 Merge branch 'main' into benvin/add-local-terraform-resource
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
2026-06-22 23:59:16 +10:00
benvin e6d58ac2ee Merge pull request 'fix: strip v prefix from version in make install path' (#3) from benvin/fix-make-install-version into main
Reviewed-on: #3
2026-06-21 22:34:39 +10:00
unkinben 3d776f9e0f feat: add pre-commit to build jobs
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/pre-commit Pipeline was successful
ensure pre-commit is run by woodpecker in ci
2026-06-21 22:31:28 +10:00
unkinben d2da94cb52 fix: pul_request tests only
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
- update tests to run on pull request only
2026-06-21 22:16:59 +10:00
unkinben 6446997a12 fix: strip v prefix from version in make install path
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
Terraform plugin directory expects bare version numbers (e.g. 0.0.2)
but git tags use v-prefixed versions (e.g. v0.0.2).
2026-06-21 22:07:47 +10:00
benvin 0ec5b80682 Merge pull request 'feat: add tag bumping features' (#2) from benvin/tag_bumping into main
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
Reviewed-on: #2
2026-06-21 18:58:12 +10:00
unkinben 40aa86bc68 feat: add tag bumping features
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
enable the use of make minor, major and patch to automatically bump
tagged releases
2026-06-21 18:55:30 +10:00
benvin a626d29aff Merge pull request 'fix: preserve empty list vs null for optional list attributes' (#1) from benvin/fix-empty-list-null-inconsistency into main
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
Reviewed-on: #1
2026-06-21 18:51:31 +10:00
unkinben d9d8cc7b6d fix: preserve empty list vs null distinction for optional list attributes
ci/woodpecker/push/build Pipeline was successful
ci/woodpecker/pr/build Pipeline was successful
ci/woodpecker/push/test Pipeline was successful
ci/woodpecker/pr/test Pipeline was successful
The API returns null for empty arrays, but OpenTofu requires that the
state match the plan exactly — an empty list [] in the plan must remain
[] in the state, not become null. This caused "inconsistent result after
apply" errors on every resource with empty optional list fields like
mutable_patterns and ban_tags.
2026-06-21 18:42:14 +10:00
16 changed files with 727 additions and 11 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
when:
- event: [push, pull_request]
- event: pull_request
steps:
- name: build
+18
View File
@@ -0,0 +1,18 @@
when:
- event: pull_request
steps:
- name: pre-commit
image: git.unkin.net/unkin/almalinux9-gobuilder:20260606
commands:
- uvx pre-commit run --all-files
backend_options:
kubernetes:
serviceAccountName: default
resources:
requests:
memory: 512Mi
cpu: 1
limits:
memory: 2Gi
cpu: 2
+19
View File
@@ -0,0 +1,19 @@
when:
- event: tag
steps:
- name: package
image: git.unkin.net/unkin/almalinux9-gobuilder:20260606
commands:
- make package VERSION=${CI_COMMIT_TAG}
- name: upload
image: git.unkin.net/unkin/almalinux9-base:20260606
commands:
- |
VERSION=$$(echo ${CI_COMMIT_TAG} | sed 's/^v//')
FILE="terraform-provider-artifactapi_$${VERSION}_linux_amd64.zip"
curl -f -X PUT \
"https://artifactapi3.k8s.syd1.au.unkin.net/api/v2/remotes/terraform-unkin/files/unkin/artifactapi/$${FILE}" \
-H "Content-Type: application/zip" \
--data-binary @"$${FILE}"
+1 -1
View File
@@ -1,5 +1,5 @@
when:
- event: [push, pull_request]
- event: pull_request
steps:
- name: lint
+29 -4
View File
@@ -1,9 +1,11 @@
.PHONY: build install test lint fmt clean tidy
.PHONY: build install test lint fmt clean tidy patch minor major package
BINARY := terraform-provider-artifactapi
VERSION ?= 0.0.1
VERSION ?= $(shell git describe --tags --always --dirty 2>/dev/null || echo "0.0.0-dev")
OS_ARCH := linux_amd64
INSTALL_DIR := ~/.terraform.d/plugins/git.unkin.net/unkin/artifactapi/$(VERSION)/$(OS_ARCH)
INSTALL_VERSION := $(shell echo $(VERSION) | sed 's/^v//')
INSTALL_DIR := ~/.terraform.d/plugins/git.unkin.net/unkin/artifactapi/$(INSTALL_VERSION)/$(OS_ARCH)
ZIP := $(BINARY)_$(INSTALL_VERSION)_$(OS_ARCH).zip
GO_VERSION_REQUIRED := 1.23
GO_VERSION_ACTUAL := $(shell go version | sed 's/go version go\([0-9]*\.[0-9]*\).*/\1/')
@@ -29,8 +31,31 @@ lint: check-go
fmt: check-go
gofmt -w .
package: build
cp $(BINARY) $(BINARY)_v$(INSTALL_VERSION)
python3 -c "import zipfile,sys; z=zipfile.ZipFile(sys.argv[1],'w',zipfile.ZIP_DEFLATED); z.write(sys.argv[2]); z.close()" $(ZIP) $(BINARY)_v$(INSTALL_VERSION)
rm $(BINARY)_v$(INSTALL_VERSION)
clean:
rm -f $(BINARY)
rm -f $(BINARY) *.zip
tidy:
go mod tidy
_LATEST := $(shell git tag --sort=-v:refname | grep -E '^v[0-9]+\.[0-9]+\.[0-9]+$$' | head -1)
_BASE := $(if $(_LATEST),$(_LATEST),v0.0.0)
_MAJ := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f1)
_MIN := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f2)
_PAT := $(shell echo $(_BASE) | sed 's/^v//' | cut -d. -f3)
patch:
@NEW=v$(_MAJ).$(_MIN).$(shell expr $(_PAT) + 1); \
git tag $$NEW && echo "Tagged $$NEW" && git push origin $$NEW
minor:
@NEW=v$(_MAJ).$(shell expr $(_MIN) + 1).0; \
git tag $$NEW && echo "Tagged $$NEW" && git push origin $$NEW
major:
@NEW=v$(shell expr $(_MAJ) + 1).0.0; \
git tag $$NEW && echo "Tagged $$NEW" && git push origin $$NEW
@@ -0,0 +1,4 @@
resource "artifactapi_local_pypi" "internal" {
name = "pypi-internal"
description = "Internal PyPI package registry"
}
@@ -0,0 +1,4 @@
resource "artifactapi_local_rpm" "internal" {
name = "rpm-internal"
description = "Internal RPM package repository"
}
+12 -1
View File
@@ -16,7 +16,7 @@ func listToStrings(ctx context.Context, l types.List) []string {
}
func stringsToList(ctx context.Context, ss []string) types.List {
if len(ss) == 0 {
if ss == nil {
return types.ListNull(types.StringType)
}
elems := make([]types.String, len(ss))
@@ -26,3 +26,14 @@ func stringsToList(ctx context.Context, ss []string) types.List {
list, _ := types.ListValueFrom(ctx, types.StringType, elems)
return list
}
// preserveListNullEmptySemantics keeps the prior null/empty distinction when
// the API returns null for a field that was previously an empty list.
// Without this, OpenTofu reports "inconsistent result after apply" because
// the plan/state had [] but the provider returned null.
func preserveListNullEmptySemantics(prior, current types.List) types.List {
if current.IsNull() && !prior.IsNull() && len(prior.Elements()) == 0 {
return prior
}
return current
}
+44 -2
View File
@@ -63,8 +63,11 @@ func TestListToStrings_WithValues(t *testing.T) {
func TestStringsToList_EmptySlice(t *testing.T) {
ctx := context.Background()
result := stringsToList(ctx, []string{})
if !result.IsNull() {
t.Fatalf("expected null list for empty slice, got %v", result)
if result.IsNull() {
t.Fatalf("expected empty list for empty slice, got null")
}
if len(result.Elements()) != 0 {
t.Fatalf("expected 0 elements, got %d", len(result.Elements()))
}
}
@@ -103,3 +106,42 @@ func TestStringsToList_SingleValue(t *testing.T) {
t.Fatalf("expected [\"solo\"], got %v", back)
}
}
func TestPreserveListNullEmptySemantics(t *testing.T) {
ctx := context.Background()
emptyList, _ := types.ListValueFrom(ctx, types.StringType, []types.String{})
nullList := types.ListNull(types.StringType)
populatedList := stringsToList(ctx, []string{"a"})
t.Run("prior empty + current null → preserves empty", func(t *testing.T) {
result := preserveListNullEmptySemantics(emptyList, nullList)
if result.IsNull() {
t.Fatal("expected empty list, got null")
}
if len(result.Elements()) != 0 {
t.Fatalf("expected 0 elements, got %d", len(result.Elements()))
}
})
t.Run("prior null + current null → stays null", func(t *testing.T) {
result := preserveListNullEmptySemantics(nullList, nullList)
if !result.IsNull() {
t.Fatal("expected null, got non-null")
}
})
t.Run("prior empty + current populated → uses current", func(t *testing.T) {
result := preserveListNullEmptySemantics(emptyList, populatedList)
elems := listToStrings(ctx, result)
if len(elems) != 1 || elems[0] != "a" {
t.Fatalf("expected [a], got %v", elems)
}
})
t.Run("prior populated + current null → stays null", func(t *testing.T) {
result := preserveListNullEmptySemantics(populatedList, nullList)
if !result.IsNull() {
t.Fatal("expected null (prior was populated, not empty — no preservation)")
}
})
}
+2
View File
@@ -69,6 +69,8 @@ func (p *ArtifactAPIProvider) Resources(_ context.Context) []func() resource.Res
newRemoteResource("goproxy"),
NewVirtualResource,
NewLocalTerraformResource,
NewLocalPyPIResource,
NewLocalRPMResource,
}
}
+4 -2
View File
@@ -66,8 +66,8 @@ func TestProvider_Resources(t *testing.T) {
p := &ArtifactAPIProvider{version: "1.0.0"}
resources := p.Resources(context.Background())
// 10 remote resource types + 1 virtual + 1 local_terraform = 12
expectedCount := 12
// 10 remote resource types + 1 virtual + 1 local_terraform + 1 local_pypi + 1 local_rpm = 14
expectedCount := 14
if len(resources) != expectedCount {
t.Fatalf("expected %d resources, got %d", expectedCount, len(resources))
}
@@ -108,6 +108,8 @@ func TestProvider_Resources_ContainsExpectedTypes(t *testing.T) {
"artifactapi_remote_goproxy",
"artifactapi_virtual",
"artifactapi_local_terraform",
"artifactapi_local_pypi",
"artifactapi_local_rpm",
}
for _, name := range expected {
+164
View File
@@ -0,0 +1,164 @@
package provider
import (
"context"
"fmt"
"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/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &localPyPIResource{}
_ resource.ResourceWithImportState = &localPyPIResource{}
)
type localPyPIResource struct {
client *apiClient
}
type localPyPIResourceModel struct {
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
}
func NewLocalPyPIResource() resource.Resource {
return &localPyPIResource{}
}
func (r *localPyPIResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_local_pypi"
}
func (r *localPyPIResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a local ArtifactAPI PyPI repository for hosting Python packages directly.",
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "Unique name of the local PyPI repository.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"description": schema.StringAttribute{
Description: "Human-readable description.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
},
},
}
}
func (r *localPyPIResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *localPyPIResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan localPyPIResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
api := localPyPIModelToAPI(plan)
api.ManagedBy = "terraform"
var created remoteAPI
if err := r.client.post(ctx, "/api/v2/remotes", api, &created); err != nil {
resp.Diagnostics.AddError("create local pypi failed", err.Error())
return
}
state := localPyPIAPIToModel(created)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *localPyPIResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state localPyPIResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var remote remoteAPI
err := r.client.get(ctx, "/api/v2/remotes/"+state.Name.ValueString(), &remote)
if err != nil {
if isNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("read local pypi failed", err.Error())
return
}
newState := localPyPIAPIToModel(remote)
resp.Diagnostics.Append(resp.State.Set(ctx, newState)...)
}
func (r *localPyPIResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan localPyPIResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
api := localPyPIModelToAPI(plan)
api.ManagedBy = "terraform"
var updated remoteAPI
if err := r.client.put(ctx, "/api/v2/remotes/"+plan.Name.ValueString(), api, &updated); err != nil {
resp.Diagnostics.AddError("update local pypi failed", err.Error())
return
}
state := localPyPIAPIToModel(updated)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *localPyPIResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state localPyPIResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.del(ctx, "/api/v2/remotes/"+state.Name.ValueString()); err != nil {
resp.Diagnostics.AddError("delete local pypi failed", err.Error())
return
}
}
func (r *localPyPIResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
func localPyPIModelToAPI(m localPyPIResourceModel) remoteAPI {
return remoteAPI{
Name: m.Name.ValueString(),
PackageType: "pypi",
RepoType: "local",
Description: m.Description.ValueString(),
}
}
func localPyPIAPIToModel(api remoteAPI) localPyPIResourceModel {
return localPyPIResourceModel{
Name: types.StringValue(api.Name),
Description: types.StringValue(api.Description),
}
}
@@ -0,0 +1,125 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestLocalPyPIModelToAPI(t *testing.T) {
model := localPyPIResourceModel{
Name: types.StringValue("pypi-internal"),
Description: types.StringValue("Internal PyPI registry"),
}
api := localPyPIModelToAPI(model)
if api.Name != "pypi-internal" {
t.Errorf("Name: expected pypi-internal, got %s", api.Name)
}
if api.PackageType != "pypi" {
t.Errorf("PackageType: expected pypi, got %s", api.PackageType)
}
if api.RepoType != "local" {
t.Errorf("RepoType: expected local, got %s", api.RepoType)
}
if api.Description != "Internal PyPI registry" {
t.Errorf("Description: expected 'Internal PyPI registry', got %s", api.Description)
}
}
func TestLocalPyPIModelToAPI_EmptyDescription(t *testing.T) {
model := localPyPIResourceModel{
Name: types.StringValue("pypi-empty"),
Description: types.StringValue(""),
}
api := localPyPIModelToAPI(model)
if api.Name != "pypi-empty" {
t.Errorf("Name: expected pypi-empty, got %s", api.Name)
}
if api.Description != "" {
t.Errorf("Description: expected empty string, got %s", api.Description)
}
if api.PackageType != "pypi" {
t.Errorf("PackageType: expected pypi, got %s", api.PackageType)
}
if api.RepoType != "local" {
t.Errorf("RepoType: expected local, got %s", api.RepoType)
}
}
func TestLocalPyPIAPIToModel(t *testing.T) {
api := remoteAPI{
Name: "pypi-internal",
PackageType: "pypi",
RepoType: "local",
Description: "Internal PyPI registry",
ManagedBy: "terraform",
}
model := localPyPIAPIToModel(api)
if model.Name.ValueString() != "pypi-internal" {
t.Errorf("Name: expected pypi-internal, got %s", model.Name.ValueString())
}
if model.Description.ValueString() != "Internal PyPI registry" {
t.Errorf("Description: expected 'Internal PyPI registry', got %s", model.Description.ValueString())
}
}
func TestLocalPyPIRoundTrip(t *testing.T) {
original := localPyPIResourceModel{
Name: types.StringValue("roundtrip-pypi"),
Description: types.StringValue("Round trip test"),
}
api := localPyPIModelToAPI(original)
result := localPyPIAPIToModel(api)
if result.Name.ValueString() != original.Name.ValueString() {
t.Errorf("Name: expected %s, got %s", original.Name.ValueString(), result.Name.ValueString())
}
if result.Description.ValueString() != original.Description.ValueString() {
t.Errorf("Description: expected %s, got %s", original.Description.ValueString(), result.Description.ValueString())
}
}
func TestLocalPyPIResource_Metadata(t *testing.T) {
r := NewLocalPyPIResource()
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
var resp resource.MetadataResponse
r.Metadata(context.Background(), req, &resp)
if resp.TypeName != "artifactapi_local_pypi" {
t.Errorf("expected artifactapi_local_pypi, got %s", resp.TypeName)
}
}
func TestLocalPyPIResource_Schema(t *testing.T) {
r := NewLocalPyPIResource()
req := resource.SchemaRequest{}
var resp resource.SchemaResponse
r.Schema(context.Background(), req, &resp)
expectedAttrs := []string{"name", "description"}
for _, attr := range expectedAttrs {
if _, ok := resp.Schema.Attributes[attr]; !ok {
t.Errorf("missing expected attribute: %s", attr)
}
}
if len(resp.Schema.Attributes) != len(expectedAttrs) {
t.Errorf("expected %d attributes, got %d", len(expectedAttrs), len(resp.Schema.Attributes))
}
}
func TestNewLocalPyPIResource_Type(t *testing.T) {
r := NewLocalPyPIResource()
_, ok := r.(*localPyPIResource)
if !ok {
t.Error("expected *localPyPIResource")
}
}
+164
View File
@@ -0,0 +1,164 @@
package provider
import (
"context"
"fmt"
"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/planmodifier"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringdefault"
"github.com/hashicorp/terraform-plugin-framework/resource/schema/stringplanmodifier"
"github.com/hashicorp/terraform-plugin-framework/types"
)
var (
_ resource.Resource = &localRPMResource{}
_ resource.ResourceWithImportState = &localRPMResource{}
)
type localRPMResource struct {
client *apiClient
}
type localRPMResourceModel struct {
Name types.String `tfsdk:"name"`
Description types.String `tfsdk:"description"`
}
func NewLocalRPMResource() resource.Resource {
return &localRPMResource{}
}
func (r *localRPMResource) Metadata(_ context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
resp.TypeName = req.ProviderTypeName + "_local_rpm"
}
func (r *localRPMResource) Schema(_ context.Context, _ resource.SchemaRequest, resp *resource.SchemaResponse) {
resp.Schema = schema.Schema{
Description: "Manages a local ArtifactAPI RPM repository for hosting RPM packages directly.",
Attributes: map[string]schema.Attribute{
"name": schema.StringAttribute{
Description: "Unique name of the local RPM repository.",
Required: true,
PlanModifiers: []planmodifier.String{
stringplanmodifier.RequiresReplace(),
},
},
"description": schema.StringAttribute{
Description: "Human-readable description.",
Optional: true,
Computed: true,
Default: stringdefault.StaticString(""),
},
},
}
}
func (r *localRPMResource) Configure(_ context.Context, req resource.ConfigureRequest, resp *resource.ConfigureResponse) {
if req.ProviderData == nil {
return
}
client, ok := req.ProviderData.(*apiClient)
if !ok {
resp.Diagnostics.AddError("unexpected provider data type", fmt.Sprintf("got %T", req.ProviderData))
return
}
r.client = client
}
func (r *localRPMResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
var plan localRPMResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
api := localRPMModelToAPI(plan)
api.ManagedBy = "terraform"
var created remoteAPI
if err := r.client.post(ctx, "/api/v2/remotes", api, &created); err != nil {
resp.Diagnostics.AddError("create local rpm failed", err.Error())
return
}
state := localRPMAPIToModel(created)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *localRPMResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
var state localRPMResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
var remote remoteAPI
err := r.client.get(ctx, "/api/v2/remotes/"+state.Name.ValueString(), &remote)
if err != nil {
if isNotFound(err) {
resp.State.RemoveResource(ctx)
return
}
resp.Diagnostics.AddError("read local rpm failed", err.Error())
return
}
newState := localRPMAPIToModel(remote)
resp.Diagnostics.Append(resp.State.Set(ctx, newState)...)
}
func (r *localRPMResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
var plan localRPMResourceModel
resp.Diagnostics.Append(req.Plan.Get(ctx, &plan)...)
if resp.Diagnostics.HasError() {
return
}
api := localRPMModelToAPI(plan)
api.ManagedBy = "terraform"
var updated remoteAPI
if err := r.client.put(ctx, "/api/v2/remotes/"+plan.Name.ValueString(), api, &updated); err != nil {
resp.Diagnostics.AddError("update local rpm failed", err.Error())
return
}
state := localRPMAPIToModel(updated)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
func (r *localRPMResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
var state localRPMResourceModel
resp.Diagnostics.Append(req.State.Get(ctx, &state)...)
if resp.Diagnostics.HasError() {
return
}
if err := r.client.del(ctx, "/api/v2/remotes/"+state.Name.ValueString()); err != nil {
resp.Diagnostics.AddError("delete local rpm failed", err.Error())
return
}
}
func (r *localRPMResource) ImportState(ctx context.Context, req resource.ImportStateRequest, resp *resource.ImportStateResponse) {
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
func localRPMModelToAPI(m localRPMResourceModel) remoteAPI {
return remoteAPI{
Name: m.Name.ValueString(),
PackageType: "rpm",
RepoType: "local",
Description: m.Description.ValueString(),
}
}
func localRPMAPIToModel(api remoteAPI) localRPMResourceModel {
return localRPMResourceModel{
Name: types.StringValue(api.Name),
Description: types.StringValue(api.Description),
}
}
@@ -0,0 +1,125 @@
package provider
import (
"context"
"testing"
"github.com/hashicorp/terraform-plugin-framework/resource"
"github.com/hashicorp/terraform-plugin-framework/types"
)
func TestLocalRPMModelToAPI(t *testing.T) {
model := localRPMResourceModel{
Name: types.StringValue("rpm-internal"),
Description: types.StringValue("Internal RPM repository"),
}
api := localRPMModelToAPI(model)
if api.Name != "rpm-internal" {
t.Errorf("Name: expected rpm-internal, got %s", api.Name)
}
if api.PackageType != "rpm" {
t.Errorf("PackageType: expected rpm, got %s", api.PackageType)
}
if api.RepoType != "local" {
t.Errorf("RepoType: expected local, got %s", api.RepoType)
}
if api.Description != "Internal RPM repository" {
t.Errorf("Description: expected 'Internal RPM repository', got %s", api.Description)
}
}
func TestLocalRPMModelToAPI_EmptyDescription(t *testing.T) {
model := localRPMResourceModel{
Name: types.StringValue("rpm-empty"),
Description: types.StringValue(""),
}
api := localRPMModelToAPI(model)
if api.Name != "rpm-empty" {
t.Errorf("Name: expected rpm-empty, got %s", api.Name)
}
if api.Description != "" {
t.Errorf("Description: expected empty string, got %s", api.Description)
}
if api.PackageType != "rpm" {
t.Errorf("PackageType: expected rpm, got %s", api.PackageType)
}
if api.RepoType != "local" {
t.Errorf("RepoType: expected local, got %s", api.RepoType)
}
}
func TestLocalRPMAPIToModel(t *testing.T) {
api := remoteAPI{
Name: "rpm-internal",
PackageType: "rpm",
RepoType: "local",
Description: "Internal RPM repository",
ManagedBy: "terraform",
}
model := localRPMAPIToModel(api)
if model.Name.ValueString() != "rpm-internal" {
t.Errorf("Name: expected rpm-internal, got %s", model.Name.ValueString())
}
if model.Description.ValueString() != "Internal RPM repository" {
t.Errorf("Description: expected 'Internal RPM repository', got %s", model.Description.ValueString())
}
}
func TestLocalRPMRoundTrip(t *testing.T) {
original := localRPMResourceModel{
Name: types.StringValue("roundtrip-rpm"),
Description: types.StringValue("Round trip test"),
}
api := localRPMModelToAPI(original)
result := localRPMAPIToModel(api)
if result.Name.ValueString() != original.Name.ValueString() {
t.Errorf("Name: expected %s, got %s", original.Name.ValueString(), result.Name.ValueString())
}
if result.Description.ValueString() != original.Description.ValueString() {
t.Errorf("Description: expected %s, got %s", original.Description.ValueString(), result.Description.ValueString())
}
}
func TestLocalRPMResource_Metadata(t *testing.T) {
r := NewLocalRPMResource()
req := resource.MetadataRequest{ProviderTypeName: "artifactapi"}
var resp resource.MetadataResponse
r.Metadata(context.Background(), req, &resp)
if resp.TypeName != "artifactapi_local_rpm" {
t.Errorf("expected artifactapi_local_rpm, got %s", resp.TypeName)
}
}
func TestLocalRPMResource_Schema(t *testing.T) {
r := NewLocalRPMResource()
req := resource.SchemaRequest{}
var resp resource.SchemaResponse
r.Schema(context.Background(), req, &resp)
expectedAttrs := []string{"name", "description"}
for _, attr := range expectedAttrs {
if _, ok := resp.Schema.Attributes[attr]; !ok {
t.Errorf("missing expected attribute: %s", attr)
}
}
if len(resp.Schema.Attributes) != len(expectedAttrs) {
t.Errorf("expected %d attributes, got %d", len(expectedAttrs), len(resp.Schema.Attributes))
}
}
func TestNewLocalRPMResource_Type(t *testing.T) {
r := NewLocalRPMResource()
_, ok := r.(*localRPMResource)
if !ok {
t.Error("expected *localRPMResource")
}
}
+11
View File
@@ -181,6 +181,7 @@ func (r *remoteResource) Create(ctx context.Context, req resource.CreateRequest,
}
state := r.apiToModel(ctx, created)
reconcileOptionalLists(&plan, &state)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
@@ -203,6 +204,7 @@ func (r *remoteResource) Read(ctx context.Context, req resource.ReadRequest, res
}
newState := r.apiToModel(ctx, remote)
reconcileOptionalLists(&state, &newState)
resp.Diagnostics.Append(resp.State.Set(ctx, newState)...)
}
@@ -223,6 +225,7 @@ func (r *remoteResource) Update(ctx context.Context, req resource.UpdateRequest,
}
state := r.apiToModel(ctx, updated)
reconcileOptionalLists(&plan, &state)
resp.Diagnostics.Append(resp.State.Set(ctx, state)...)
}
@@ -243,6 +246,14 @@ func (r *remoteResource) ImportState(ctx context.Context, req resource.ImportSta
resource.ImportStatePassthroughID(ctx, path.Root("name"), req, resp)
}
func reconcileOptionalLists(prior, current *remoteResourceModel) {
current.Patterns = preserveListNullEmptySemantics(prior.Patterns, current.Patterns)
current.Blocklist = preserveListNullEmptySemantics(prior.Blocklist, current.Blocklist)
current.MutablePatterns = preserveListNullEmptySemantics(prior.MutablePatterns, current.MutablePatterns)
current.ImmutablePatterns = preserveListNullEmptySemantics(prior.ImmutablePatterns, current.ImmutablePatterns)
current.BanTags = preserveListNullEmptySemantics(prior.BanTags, current.BanTags)
}
func (r *remoteResource) modelToAPI(ctx context.Context, m remoteResourceModel) remoteAPI {
api := remoteAPI{
Name: m.Name.ValueString(),