Skip to content

Commit 2f7a0a4

Browse files
Split some functions and tests into differnt files (#7684) (#848)
Signed-off-by: Modular Magician <[email protected]>
1 parent 22d8701 commit 2f7a0a4

File tree

8 files changed

+186
-153
lines changed

8 files changed

+186
-153
lines changed

go.mod

+15-14
Original file line numberDiff line numberDiff line change
@@ -16,25 +16,25 @@ require (
1616
github.com/hashicorp/terraform-json v0.14.0
1717
github.com/hashicorp/terraform-plugin-framework v1.1.1
1818
github.com/hashicorp/terraform-plugin-sdk/v2 v2.24.0
19-
github.com/hashicorp/terraform-provider-google v1.20.1-0.20230411211055-4a9c2062b283
19+
github.com/hashicorp/terraform-provider-google v1.20.1-0.20230411230403-559d509a0752
2020
github.com/mitchellh/go-homedir v1.1.0
2121
github.com/pkg/errors v0.9.1
2222
github.com/sirupsen/logrus v1.8.1
2323
github.com/stretchr/testify v1.8.1
2424
github.com/zclconf/go-cty v1.11.0
2525
go.uber.org/zap v1.21.0
26-
golang.org/x/oauth2 v0.6.0
27-
google.golang.org/api v0.114.0
28-
google.golang.org/genproto v0.0.0-20230306155012-7f2fa6fef1f4
29-
google.golang.org/grpc v1.53.0
26+
golang.org/x/oauth2 v0.7.0
27+
google.golang.org/api v0.117.0
28+
google.golang.org/genproto v0.0.0-20230403163135-c38d8f061ccd
29+
google.golang.org/grpc v1.54.0
3030
)
3131

3232
require (
3333
bitbucket.org/creachadair/stringset v0.0.8 // indirect
3434
cloud.google.com/go v0.110.0 // indirect
35-
cloud.google.com/go/compute v1.18.0 // indirect
35+
cloud.google.com/go/compute v1.19.0 // indirect
3636
cloud.google.com/go/compute/metadata v0.2.3 // indirect
37-
cloud.google.com/go/iam v0.12.0 // indirect
37+
cloud.google.com/go/iam v0.13.0 // indirect
3838
cloud.google.com/go/longrunning v0.4.1 // indirect
3939
github.com/GoogleCloudPlatform/declarative-resource-client-library v1.37.0 // indirect
4040
github.com/agext/levenshtein v1.2.2 // indirect
@@ -53,11 +53,12 @@ require (
5353
github.com/gammazero/workerpool v0.0.0-20181230203049-86a96b5d5d92 // indirect
5454
github.com/golang/glog v1.0.0 // indirect
5555
github.com/golang/groupcache v0.0.0-20210331224755-41bb18bfe9da // indirect
56-
github.com/golang/protobuf v1.5.2 // indirect
56+
github.com/golang/protobuf v1.5.3 // indirect
5757
github.com/google/go-cpy v0.0.0-20211218193943-a9c933c06932 // indirect
58+
github.com/google/s2a-go v0.1.0 // indirect
5859
github.com/google/uuid v1.3.0 // indirect
5960
github.com/googleapis/enterprise-certificate-proxy v0.2.3 // indirect
60-
github.com/googleapis/gax-go/v2 v2.7.1 // indirect
61+
github.com/googleapis/gax-go/v2 v2.8.0 // indirect
6162
github.com/hashicorp/go-checkpoint v0.5.0 // indirect
6263
github.com/hashicorp/go-hclog v1.2.1 // indirect
6364
github.com/hashicorp/go-multierror v1.1.1 // indirect
@@ -91,13 +92,13 @@ require (
9192
go.opencensus.io v0.24.0 // indirect
9293
go.uber.org/atomic v1.9.0 // indirect
9394
go.uber.org/multierr v1.7.0 // indirect
94-
golang.org/x/crypto v0.0.0-20220517005047-85d78b3ac167 // indirect
95-
golang.org/x/net v0.8.0 // indirect
96-
golang.org/x/sys v0.6.0 // indirect
97-
golang.org/x/text v0.8.0 // indirect
95+
golang.org/x/crypto v0.1.0 // indirect
96+
golang.org/x/net v0.9.0 // indirect
97+
golang.org/x/sys v0.7.0 // indirect
98+
golang.org/x/text v0.9.0 // indirect
9899
golang.org/x/xerrors v0.0.0-20220907171357-04be3eba64a2 // indirect
99100
google.golang.org/appengine v1.6.7 // indirect
100-
google.golang.org/protobuf v1.29.1 // indirect
101+
google.golang.org/protobuf v1.30.0 // indirect
101102
gopkg.in/yaml.v2 v2.4.0 // indirect
102103
gopkg.in/yaml.v3 v3.0.1 // indirect
103104
)

go.sum

+36-29
Large diffs are not rendered by default.

tfplan2cai/converters/google/resources/config.go

+29
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import (
77
"fmt"
88
"log"
99
"net/http"
10+
"os"
1011
"regexp"
1112
"strconv"
1213
"strings"
@@ -1918,3 +1919,31 @@ func ConfigureBasePaths(c *Config) {
19181919
c.BigtableAdminBasePath = DefaultBasePaths[BigtableAdminBasePathKey]
19191920
c.TagsLocationBasePath = DefaultBasePaths[TagsLocationBasePathKey]
19201921
}
1922+
1923+
func GetCurrentUserEmail(config *Config, userAgent string) (string, error) {
1924+
// When environment variables UserProjectOverride and BillingProject are set for the provider,
1925+
// the header X-Goog-User-Project is set for the API requests.
1926+
// But it causes an error when calling GetCurrentUserEmail. Set the project to be "NO_BILLING_PROJECT_OVERRIDE".
1927+
// And then it triggers the header X-Goog-User-Project to be set to empty string.
1928+
1929+
// See https://github.com/golang/oauth2/issues/306 for a recommendation to do this from a Go maintainer
1930+
// URL retrieved from https://accounts.google.com/.well-known/openid-configuration
1931+
res, err := SendRequest(config, "GET", "NO_BILLING_PROJECT_OVERRIDE", "https://openidconnect.googleapis.com/v1/userinfo", userAgent, nil)
1932+
1933+
if err != nil {
1934+
return "", fmt.Errorf("error retrieving userinfo for your provider credentials. have you enabled the 'https://www.googleapis.com/auth/userinfo.email' scope? error: %s", err)
1935+
}
1936+
if res["email"] == nil {
1937+
return "", fmt.Errorf("error retrieving email from userinfo. email was nil in the response.")
1938+
}
1939+
return res["email"].(string), nil
1940+
}
1941+
1942+
func MultiEnvSearch(ks []string) string {
1943+
for _, k := range ks {
1944+
if v := os.Getenv(k); v != "" {
1945+
return v
1946+
}
1947+
}
1948+
return ""
1949+
}

tfplan2cai/converters/google/resources/config_test_utils.go

+3
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ import (
55
"strings"
66
)
77

8+
const testFakeCredentialsPath = "./test-fixtures/fake_account.json"
9+
const testOauthScope = "https://www.googleapis.com/auth/compute"
10+
811
// NewTestConfig create a config using the http test server.
912
func NewTestConfig(server *httptest.Server) *Config {
1013
cfg := &Config{}

tfplan2cai/converters/google/resources/iam.go

+12
Original file line numberDiff line numberDiff line change
@@ -466,3 +466,15 @@ func IamWithDeprecationMessage(message string) func(s *IamSettings) {
466466
func IamWithGAResourceDeprecation() func(s *IamSettings) {
467467
return IamWithDeprecationMessage("This resource has been deprecated in the google (GA) provider, and will only be available in the google-beta provider in a future release.")
468468
}
469+
470+
// Util to deref and print auditConfigs
471+
func debugPrintAuditConfigs(bs []*cloudresourcemanager.AuditConfig) string {
472+
v, _ := json.MarshalIndent(bs, "", "\t")
473+
return string(v)
474+
}
475+
476+
// Util to deref and print bindings
477+
func debugPrintBindings(bs []*cloudresourcemanager.Binding) string {
478+
v, _ := json.MarshalIndent(bs, "", "\t")
479+
return string(v)
480+
}

tfplan2cai/converters/google/resources/transport.go

+40-22
Original file line numberDiff line numberDiff line change
@@ -5,40 +5,21 @@ import (
55
"encoding/json"
66
"errors"
77
"fmt"
8+
"log"
89
"net/http"
910
"net/url"
1011
"reflect"
1112
"regexp"
1213
"strings"
1314
"time"
1415

16+
"github.com/hashicorp/errwrap"
17+
"github.com/hashicorp/terraform-plugin-sdk/v2/helper/schema"
1518
"google.golang.org/api/googleapi"
1619
)
1720

1821
var DefaultRequestTimeout = 5 * time.Minute
1922

20-
func isEmptyValue(v reflect.Value) bool {
21-
if !v.IsValid() {
22-
return true
23-
}
24-
25-
switch v.Kind() {
26-
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
27-
return v.Len() == 0
28-
case reflect.Bool:
29-
return !v.Bool()
30-
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
31-
return v.Int() == 0
32-
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
33-
return v.Uint() == 0
34-
case reflect.Float32, reflect.Float64:
35-
return v.Float() == 0
36-
case reflect.Interface, reflect.Ptr:
37-
return v.IsNil()
38-
}
39-
return false
40-
}
41-
4223
func SendRequest(config *Config, method, project, rawurl, userAgent string, body map[string]interface{}, errorRetryPredicates ...RetryErrorPredicateFunc) (map[string]interface{}, error) {
4324
return SendRequestWithTimeout(config, method, project, rawurl, userAgent, body, DefaultRequestTimeout, errorRetryPredicates...)
4425
}
@@ -263,3 +244,40 @@ func buildReplacementFunc(re *regexp.Regexp, d TerraformResourceData, config *Co
263244

264245
return f, nil
265246
}
247+
248+
func handleNotFoundError(err error, d *schema.ResourceData, resource string) error {
249+
if IsGoogleApiErrorWithCode(err, 404) {
250+
log.Printf("[WARN] Removing %s because it's gone", resource)
251+
// The resource doesn't exist anymore
252+
d.SetId("")
253+
254+
return nil
255+
}
256+
257+
return errwrap.Wrapf(
258+
fmt.Sprintf("Error when reading or editing %s: {{err}}", resource), err)
259+
}
260+
261+
func IsGoogleApiErrorWithCode(err error, errCode int) bool {
262+
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
263+
return ok && gerr != nil && gerr.Code == errCode
264+
}
265+
266+
func isApiNotEnabledError(err error) bool {
267+
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
268+
if !ok {
269+
return false
270+
}
271+
if gerr == nil {
272+
return false
273+
}
274+
if gerr.Code != 403 {
275+
return false
276+
}
277+
for _, e := range gerr.Errors {
278+
if e.Reason == "accessNotConfigured" {
279+
return true
280+
}
281+
}
282+
return false
283+
}

tfplan2cai/converters/google/resources/utils.go

+23-88
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@ package google
44

55
import (
66
"fmt"
7-
"log"
87
"os"
8+
"reflect"
99
"regexp"
1010
"sort"
1111
"strconv"
@@ -100,43 +100,6 @@ func getRouterLockName(region string, router string) string {
100100
return fmt.Sprintf("router/%s/%s", region, router)
101101
}
102102

103-
func handleNotFoundError(err error, d *schema.ResourceData, resource string) error {
104-
if IsGoogleApiErrorWithCode(err, 404) {
105-
log.Printf("[WARN] Removing %s because it's gone", resource)
106-
// The resource doesn't exist anymore
107-
d.SetId("")
108-
109-
return nil
110-
}
111-
112-
return errwrap.Wrapf(
113-
fmt.Sprintf("Error when reading or editing %s: {{err}}", resource), err)
114-
}
115-
116-
func IsGoogleApiErrorWithCode(err error, errCode int) bool {
117-
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
118-
return ok && gerr != nil && gerr.Code == errCode
119-
}
120-
121-
func isApiNotEnabledError(err error) bool {
122-
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
123-
if !ok {
124-
return false
125-
}
126-
if gerr == nil {
127-
return false
128-
}
129-
if gerr.Code != 403 {
130-
return false
131-
}
132-
for _, e := range gerr.Errors {
133-
if e.Reason == "accessNotConfigured" {
134-
return true
135-
}
136-
}
137-
return false
138-
}
139-
140103
func isFailedPreconditionError(err error) bool {
141104
gerr, ok := errwrap.GetType(err, &googleapi.Error{}).(*googleapi.Error)
142105
if !ok {
@@ -307,28 +270,6 @@ func mergeSchemas(a, b map[string]*schema.Schema) map[string]*schema.Schema {
307270
return merged
308271
}
309272

310-
func mergeResourceMaps(ms ...map[string]*schema.Resource) (map[string]*schema.Resource, error) {
311-
merged := make(map[string]*schema.Resource)
312-
duplicates := []string{}
313-
314-
for _, m := range ms {
315-
for k, v := range m {
316-
if _, ok := merged[k]; ok {
317-
duplicates = append(duplicates, k)
318-
}
319-
320-
merged[k] = v
321-
}
322-
}
323-
324-
var err error
325-
if len(duplicates) > 0 {
326-
err = fmt.Errorf("saw duplicates in mergeResourceMaps: %v", duplicates)
327-
}
328-
329-
return merged, err
330-
}
331-
332273
func StringToFixed64(v string) (int64, error) {
333274
return strconv.ParseInt(v, 10, 64)
334275
}
@@ -509,34 +450,6 @@ func SnakeToPascalCase(s string) string {
509450
return strings.Join(split, "")
510451
}
511452

512-
func MultiEnvSearch(ks []string) string {
513-
for _, k := range ks {
514-
if v := os.Getenv(k); v != "" {
515-
return v
516-
}
517-
}
518-
return ""
519-
}
520-
521-
func GetCurrentUserEmail(config *Config, userAgent string) (string, error) {
522-
// When environment variables UserProjectOverride and BillingProject are set for the provider,
523-
// the header X-Goog-User-Project is set for the API requests.
524-
// But it causes an error when calling GetCurrentUserEmail. Set the project to be "NO_BILLING_PROJECT_OVERRIDE".
525-
// And then it triggers the header X-Goog-User-Project to be set to empty string.
526-
527-
// See https://github.com/golang/oauth2/issues/306 for a recommendation to do this from a Go maintainer
528-
// URL retrieved from https://accounts.google.com/.well-known/openid-configuration
529-
res, err := SendRequest(config, "GET", "NO_BILLING_PROJECT_OVERRIDE", "https://openidconnect.googleapis.com/v1/userinfo", userAgent, nil)
530-
531-
if err != nil {
532-
return "", fmt.Errorf("error retrieving userinfo for your provider credentials. have you enabled the 'https://www.googleapis.com/auth/userinfo.email' scope? error: %s", err)
533-
}
534-
if res["email"] == nil {
535-
return "", fmt.Errorf("error retrieving email from userinfo. email was nil in the response.")
536-
}
537-
return res["email"].(string), nil
538-
}
539-
540453
func checkStringMap(v interface{}) map[string]string {
541454
m, ok := v.(map[string]string)
542455
if ok {
@@ -634,3 +547,25 @@ func frameworkDiagsToSdkDiags(fwD fwDiags.Diagnostics) *diag.Diagnostics {
634547

635548
return &diags
636549
}
550+
551+
func isEmptyValue(v reflect.Value) bool {
552+
if !v.IsValid() {
553+
return true
554+
}
555+
556+
switch v.Kind() {
557+
case reflect.Array, reflect.Map, reflect.Slice, reflect.String:
558+
return v.Len() == 0
559+
case reflect.Bool:
560+
return !v.Bool()
561+
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
562+
return v.Int() == 0
563+
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
564+
return v.Uint() == 0
565+
case reflect.Float32, reflect.Float64:
566+
return v.Float() == 0
567+
case reflect.Interface, reflect.Ptr:
568+
return v.IsNil()
569+
}
570+
return false
571+
}

tfplan2cai/converters/google/resources/validation.go

+28
Original file line numberDiff line numberDiff line change
@@ -355,3 +355,31 @@ func validateADDomainName() schema.SchemaValidateFunc {
355355
return
356356
}
357357
}
358+
359+
func testStringValidationCases(cases []StringValidationTestCase, validationFunc schema.SchemaValidateFunc) []error {
360+
es := make([]error, 0)
361+
for _, c := range cases {
362+
es = append(es, testStringValidation(c, validationFunc)...)
363+
}
364+
365+
return es
366+
}
367+
368+
func testStringValidation(testCase StringValidationTestCase, validationFunc schema.SchemaValidateFunc) []error {
369+
_, es := validationFunc(testCase.Value, testCase.TestName)
370+
if testCase.ExpectError {
371+
if len(es) > 0 {
372+
return nil
373+
} else {
374+
return []error{fmt.Errorf("Didn't see expected error in case \"%s\" with string \"%s\"", testCase.TestName, testCase.Value)}
375+
}
376+
}
377+
378+
return es
379+
}
380+
381+
type StringValidationTestCase struct {
382+
TestName string
383+
Value string
384+
ExpectError bool
385+
}

0 commit comments

Comments
 (0)