Skip to content

Commit

Permalink
Merge branch 'main' into fix-agent-project-assignment-#914
Browse files Browse the repository at this point in the history
  • Loading branch information
TomerHeber authored Aug 22, 2024
2 parents 6e39397 + 4de999d commit 8dd28ed
Show file tree
Hide file tree
Showing 24 changed files with 501 additions and 216 deletions.
2 changes: 2 additions & 0 deletions .golangci.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ linters-settings:
errcheck:
exclude-functions:
- (*github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema.ResourceData).Set
goconst:
ignore-tests: true
4 changes: 0 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,3 @@ repos:
- id: go-vet
- id: go-imports
- id: go-mod-tidy
- repo: https://github.com/TekWizely/pre-commit-golang
rev: v1.0.0-beta.5
hooks:
- id: go-staticcheck-mod
1 change: 1 addition & 0 deletions client/api_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,7 @@ type ApiClientInterface interface {
CloudAccountDelete(id string) error
CloudAccount(id string) (*CloudAccount, error)
CloudAccounts() ([]CloudAccount, error)
VcsToken(vcsType string, repository string) (*VscToken, error)
}

func NewApiClient(client http.HttpClientInterface, defaultOrganizationId string) ApiClientInterface {
Expand Down
16 changes: 16 additions & 0 deletions client/api_client_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion client/configuration_variable.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func (c *ConfigurationVariableSchema) ResourceDataSliceStructValueWrite(values m

type ConfigurationVariable struct {
ScopeId string `json:"scopeId,omitempty"`
Value string `json:"value"`
Value string `json:"value" tfschema:"-"`
OrganizationId string `json:"organizationId,omitempty"`
UserId string `json:"userId,omitempty"`
IsSensitive *bool `json:"isSensitive,omitempty"`
Expand Down
1 change: 1 addition & 0 deletions client/http/client_mock.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

46 changes: 46 additions & 0 deletions client/vcs_token_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package client_test

import (
. "github.com/env0/terraform-provider-env0/client"
. "github.com/onsi/ginkgo"
. "github.com/onsi/gomega"
"go.uber.org/mock/gomock"
)

var _ = Describe("VCSToken", func() {
vcsType := "github"
repository := "http://myrepo.com/"

mockVcsToken := VscToken{
Token: 12345,
}

Describe("get", func() {
var ret *VscToken
var err error

BeforeEach(func() {
mockOrganizationIdCall(organizationId)

httpCall = mockHttpClient.EXPECT().
Get("/vcs-token/"+vcsType, map[string]string{
"organizationId": organizationId,
"repository": repository,
}, gomock.Any()).
Do(func(path string, request interface{}, response *VscToken) {
*response = mockVcsToken
}).Times(1)

ret, err = apiClient.VcsToken(vcsType, repository)
})

It("should return vcs token", func() {
Expect(*ret).To(Equal(mockVcsToken))
})

It("should not return error", func() {
Expect(err).To(BeNil())
})
})

})
22 changes: 22 additions & 0 deletions client/vsc_token.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package client

type VscToken struct {
Token int `json:"token"`
}

func (client *ApiClient) VcsToken(vcsType string, repository string) (*VscToken, error) {
organizationId, err := client.OrganizationId()
if err != nil {
return nil, err
}

var result VscToken
if err := client.http.Get("/vcs-token/"+vcsType, map[string]string{
"organizationId": organizationId,
"repository": repository,
}, &result); err != nil {
return nil, err
}

return &result, nil
}
35 changes: 35 additions & 0 deletions docs/data-sources/github_installation_id.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
---
# generated by https://github.com/hashicorp/terraform-plugin-docs
page_title: "env0_github_installation_id Data Source - terraform-provider-env0"
subcategory: ""
description: |-
returns the github installation id of a git hub repositroy
---

# env0_github_installation_id (Data Source)

returns the github installation id of a git hub repositroy

## Example Usage

```terraform
data "env0_github_installation_id" "example" {
repository = "https://github.com/env0/templates"
}
output "github_installation_id" {
value = data.env0_github_installation_id.example.github_installation_id
}
```

<!-- schema generated by tfplugindocs -->
## Schema

### Required

- `repository` (String) the name of the repository

### Read-Only

- `github_installation_id` (Number) the github installation id
- `id` (String) The ID of this resource.
4 changes: 4 additions & 0 deletions env0/data_configuration_variable.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ func dataConfigurationVariableRead(ctx context.Context, d *schema.ResourceData,
return diag.Errorf("schema resource data serialization failed: %v", err)
}

if variable.IsSensitive == nil || !*variable.IsSensitive {
d.Set("value", variable.Value)
}

d.Set("enum", variable.Schema.Enum)

if variable.Schema.Format != client.Text {
Expand Down
46 changes: 46 additions & 0 deletions env0/data_github_installation_id.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
package env0

import (
"context"

"github.com/env0/terraform-provider-env0/client"
"github.com/hashicorp/terraform-plugin-sdk/v2/diag"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

func dataGithubInstallationId() *schema.Resource {
return &schema.Resource{
Description: "returns the github installation id of a git hub repositroy",

ReadContext: dataGithubInstallationIdRead,

Schema: map[string]*schema.Schema{
"repository": {
Type: schema.TypeString,
Description: "the name of the repository",
Required: true,
},
"github_installation_id": {
Type: schema.TypeInt,
Description: "the github installation id",
Computed: true,
},
},
}
}

func dataGithubInstallationIdRead(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
apiClient := meta.(client.ApiClientInterface)

repositroy := d.Get("repository").(string)

token, err := apiClient.VcsToken("github", repositroy)
if err != nil {
return diag.Errorf("failed to get github installation id: %v", err)
}

d.Set("github_installation_id", token.Token)
d.SetId(repositroy)

return nil
}
69 changes: 69 additions & 0 deletions env0/data_github_installation_id_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
package env0

import (
"errors"
"regexp"
"strconv"
"testing"

"github.com/env0/terraform-provider-env0/client"
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
)

func TestGithubInstallationIdDataSource(t *testing.T) {
mockToken := client.VscToken{
Token: 12345,
}

mockRepositroy := "http://myrepo.com"

resourceType := "env0_github_installation_id"
resourceName := "test"
accessor := dataSourceAccessor(resourceType, resourceName)

getValidTestCase := func(repository string) resource.TestCase {
return resource.TestCase{
Steps: []resource.TestStep{
{
Config: dataSourceConfigCreate(resourceType, resourceName, map[string]interface{}{
"repository": repository,
}),
Check: resource.ComposeAggregateTestCheckFunc(
resource.TestCheckResourceAttr(accessor, "github_installation_id", strconv.Itoa(mockToken.Token)),
),
},
},
}
}

getErrorTestCase := func(repository string, expectedError string) resource.TestCase {
return resource.TestCase{
Steps: []resource.TestStep{
{
Config: dataSourceConfigCreate(resourceType, resourceName, map[string]interface{}{
"repository": repository,
}),
ExpectError: regexp.MustCompile(expectedError),
},
},
}
}

t.Run("get by repository", func(t *testing.T) {
runUnitTest(t,
getValidTestCase(mockRepositroy),
func(mock *client.MockApiClientInterface) {
mock.EXPECT().VcsToken("github", mockRepositroy).Return(&mockToken, nil).AnyTimes()
},
)
})

t.Run("get by repository - failed", func(t *testing.T) {
runUnitTest(t,
getErrorTestCase(mockRepositroy, "failed to get github installation id: error"),
func(mock *client.MockApiClientInterface) {
mock.EXPECT().VcsToken("github", mockRepositroy).Return(nil, errors.New("error")).AnyTimes()
},
)
})
}
12 changes: 11 additions & 1 deletion env0/data_source_code_variables.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,10 +76,20 @@ func dataSourceCodeVariablesRead(ctx context.Context, d *schema.ResourceData, me
return diag.Errorf("failed to extract variables from repository: %v", err)
}

if err := writeResourceDataSlice(variables, "variables", d); err != nil {
ivalues, err := writeResourceDataGetSliceValues(variables, "variables", d)
if err != nil {
return diag.Errorf("schema slice resource data serialization failed: %v", err)
}

for i, ivalue := range ivalues {
if variables[i].IsSensitive == nil || !*variables[i].IsSensitive {
ivariable := ivalue.(map[string]interface{})
ivariable["value"] = variables[i].Value
}
}

d.Set("variables", ivalues)

d.SetId(templateId)

return nil
Expand Down
2 changes: 2 additions & 0 deletions env0/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ import (
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
)

var ErrNoChanges = errors.New("no changes")

func driftDetected(err error) bool {
var failedResponseError *http.FailedResponseError
if errors.As(err, &failedResponseError) && failedResponseError.NotFound() {
Expand Down
1 change: 1 addition & 0 deletions env0/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,7 @@ func Provider(version string) plugin.ProviderFunc {
"env0_projects": dataProjects(),
"env0_module_testing_project": dataModuleTestingProject(),
"env0_variable_set": dataVariableSet(),
"env0_github_installation_id": dataGithubInstallationId(),
},
ResourcesMap: map[string]*schema.Resource{
"env0_project": resourceProject(),
Expand Down
12 changes: 9 additions & 3 deletions env0/resource_configuration_variable.go
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,7 @@ func getConfigurationVariableCreateParams(d *schema.ResourceData) (*client.Confi
func resourceConfigurationVariableCreate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
params, err := getConfigurationVariableCreateParams(d)
if err != nil {
return diag.Errorf(err.Error())
return diag.FromErr(err)
}

apiClient := meta.(client.ApiClientInterface)
Expand All @@ -195,7 +195,9 @@ func getEnum(d *schema.ResourceData, selectedValue string) ([]string, error) {
if enumValue == nil {
return nil, fmt.Errorf("an empty enum value is not allowed (at index %d)", i)
}

actualEnumValues = append(actualEnumValues, enumValue.(string))

if enumValue == selectedValue {
valueExists = true
}
Expand Down Expand Up @@ -223,13 +225,17 @@ func resourceConfigurationVariableRead(ctx context.Context, d *schema.ResourceDa
return diag.Errorf("schema resource data serialization failed: %v", err)
}

if variable.IsSensitive == nil || !*variable.IsSensitive {
d.Set("value", variable.Value)
}

return nil
}

func resourceConfigurationVariableUpdate(ctx context.Context, d *schema.ResourceData, meta interface{}) diag.Diagnostics {
params, err := getConfigurationVariableCreateParams(d)
if err != nil {
return diag.Errorf(err.Error())
return diag.FromErr(err)
}

apiClient := meta.(client.ApiClientInterface)
Expand Down Expand Up @@ -280,7 +286,7 @@ func resourceConfigurationVariableImport(ctx context.Context, d *schema.Resource
var scopeName string

if variable.Scope == client.ScopeTemplate {
scopeName = strings.ToLower(fmt.Sprintf("%s_id", templateScope))
scopeName = strings.ToLower(templateScope + "_id")
} else {
scopeName = strings.ToLower(fmt.Sprintf("%s_id", variable.Scope))
}
Expand Down
Loading

0 comments on commit 8dd28ed

Please sign in to comment.