Skip to content

Commit

Permalink
Autogenerate google_sourcerepo_repository (#2797)
Browse files Browse the repository at this point in the history
  • Loading branch information
modular-magician authored and rileykarson committed Jan 4, 2019
1 parent 6b29503 commit 181dafe
Show file tree
Hide file tree
Showing 6 changed files with 284 additions and 125 deletions.
2 changes: 1 addition & 1 deletion google/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,6 +120,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) {
GeneratedDnsResourcesMap,
GeneratedRedisResourcesMap,
GeneratedResourceManagerResourcesMap,
GeneratedSourcerepoResourcesMap,
GeneratedStorageResourcesMap,
GeneratedMonitoringResourcesMap,
map[string]*schema.Resource{
Expand Down Expand Up @@ -183,7 +184,6 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) {
"google_kms_crypto_key": resourceKmsCryptoKey(),
"google_kms_crypto_key_iam_binding": ResourceIamBindingWithImport(IamKmsCryptoKeySchema, NewKmsCryptoKeyIamUpdater, CryptoIdParseFunc),
"google_kms_crypto_key_iam_member": ResourceIamMemberWithImport(IamKmsCryptoKeySchema, NewKmsCryptoKeyIamUpdater, CryptoIdParseFunc),
"google_sourcerepo_repository": resourceSourceRepoRepository(),
"google_spanner_instance": resourceSpannerInstance(),
"google_spanner_instance_iam_binding": ResourceIamBindingWithImport(IamSpannerInstanceSchema, NewSpannerInstanceIamUpdater, SpannerInstanceIdParseFunc),
"google_spanner_instance_iam_member": ResourceIamMemberWithImport(IamSpannerInstanceSchema, NewSpannerInstanceIamUpdater, SpannerInstanceIdParseFunc),
Expand Down
21 changes: 21 additions & 0 deletions google/provider_sourcerepo_gen.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------

package google

import "github.com/hashicorp/terraform/helper/schema"

var GeneratedSourcerepoResourcesMap = map[string]*schema.Resource{
"google_sourcerepo_repository": resourceSourcerepoRepository(),
}
168 changes: 115 additions & 53 deletions google/resource_sourcerepo_repository.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,43 @@
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------

package google

import (
"fmt"
"log"
"reflect"
"strconv"
"strings"
"time"

"github.com/hashicorp/terraform/helper/schema"
"google.golang.org/api/sourcerepo/v1"
)

func resourceSourceRepoRepository() *schema.Resource {
func resourceSourcerepoRepository() *schema.Resource {
return &schema.Resource{
Create: resourceSourceRepoRepositoryCreate,
Read: resourceSourceRepoRepositoryRead,
Delete: resourceSourceRepoRepositoryDelete,
//Update: not supported,
Create: resourceSourcerepoRepositoryCreate,
Read: resourceSourcerepoRepositoryRead,
Delete: resourceSourcerepoRepositoryDelete,

Importer: &schema.ResourceImporter{
State: resourceSourceRepoRepositoryImport,
State: resourceSourcerepoRepositoryImport,
},

Timeouts: &schema.ResourceTimeout{
Create: schema.DefaultTimeout(240 * time.Second),
Delete: schema.DefaultTimeout(240 * time.Second),
},

Schema: map[string]*schema.Schema{
Expand All @@ -24,111 +46,151 @@ func resourceSourceRepoRepository() *schema.Resource {
Required: true,
ForceNew: true,
},

"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},

"size": {
Type: schema.TypeInt,
Computed: true,
},

"url": {
Type: schema.TypeString,
Computed: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
},
}
}

func resourceSourceRepoRepositoryCreate(d *schema.ResourceData, meta interface{}) error {
func resourceSourcerepoRepositoryCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

project, err := getProject(d, config)
obj := make(map[string]interface{})
nameProp, err := expandSourcerepoRepositoryName(d.Get("name"), d, config)
if err != nil {
return err
} else if v, ok := d.GetOkExists("name"); !isEmptyValue(reflect.ValueOf(nameProp)) && (ok || !reflect.DeepEqual(v, nameProp)) {
obj["name"] = nameProp
}

repoName := d.Get("name").(string)
name := buildRepositoryName(project, repoName)

repo := &sourcerepo.Repo{
Name: name,
url, err := replaceVars(d, config, "https://sourcerepo.googleapis.com/v1/projects/{{project}}/repos")
if err != nil {
return err
}

parent := "projects/" + project
log.Printf("[DEBUG] Creating new Repository: %#v", obj)
res, err := sendRequestWithTimeout(config, "POST", url, obj, d.Timeout(schema.TimeoutCreate))
if err != nil {
return fmt.Errorf("Error creating Repository: %s", err)
}

op, err := config.clientSourceRepo.Projects.Repos.Create(parent, repo).Do()
// Store the ID now
id, err := replaceVars(d, config, "{{project}}/{{name}}")
if err != nil {
return fmt.Errorf("Error creating the Source Repo: %s", err)
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(op.Name)
d.SetId(id)

return nil
log.Printf("[DEBUG] Finished creating Repository %q: %#v", d.Id(), res)

return resourceSourcerepoRepositoryRead(d, meta)
}

func resourceSourceRepoRepositoryRead(d *schema.ResourceData, meta interface{}) error {
func resourceSourcerepoRepositoryRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

project, err := getProject(d, config)
url, err := replaceVars(d, config, "https://sourcerepo.googleapis.com/v1/projects/{{project}}/repos/{{name}}")
if err != nil {
return err
}

repoName := d.Get("name").(string)
name := buildRepositoryName(project, repoName)

repo, err := config.clientSourceRepo.Projects.Repos.Get(name).Do()
res, err := sendRequest(config, "GET", url, nil)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("SourcerepoRepository %q", d.Id()))
}

project, err := getProject(d, config)
if err != nil {
return handleNotFoundError(err, d, fmt.Sprintf("Source Repo %q", d.Id()))
return err
}
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Repository: %s", err)
}

d.Set("size", repo.Size)
d.Set("project", project)
d.Set("url", repo.Url)
if err := d.Set("name", flattenSourcerepoRepositoryName(res["name"], d)); err != nil {
return fmt.Errorf("Error reading Repository: %s", err)
}
if err := d.Set("url", flattenSourcerepoRepositoryUrl(res["url"], d)); err != nil {
return fmt.Errorf("Error reading Repository: %s", err)
}
if err := d.Set("size", flattenSourcerepoRepositorySize(res["size"], d)); err != nil {
return fmt.Errorf("Error reading Repository: %s", err)
}

return nil
}

func resourceSourceRepoRepositoryDelete(d *schema.ResourceData, meta interface{}) error {
func resourceSourcerepoRepositoryDelete(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)

project, err := getProject(d, config)
url, err := replaceVars(d, config, "https://sourcerepo.googleapis.com/v1/projects/{{project}}/repos/{{name}}")
if err != nil {
return err
}

repoName := d.Get("name").(string)
name := buildRepositoryName(project, repoName)

_, err = config.clientSourceRepo.Projects.Repos.Delete(name).Do()
var obj map[string]interface{}
log.Printf("[DEBUG] Deleting Repository %q", d.Id())
res, err := sendRequestWithTimeout(config, "DELETE", url, obj, d.Timeout(schema.TimeoutDelete))
if err != nil {
return fmt.Errorf("Error deleting the Source Repo: %s", err)
return handleNotFoundError(err, d, "Repository")
}

log.Printf("[DEBUG] Finished deleting Repository %q: %#v", d.Id(), res)
return nil
}

func buildRepositoryName(project, name string) string {
repositoryName := "projects/" + project + "/repos/" + name
return repositoryName
}

func resourceSourceRepoRepositoryImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
func resourceSourcerepoRepositoryImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
parseImportId([]string{"projects/(?P<project>[^/]+)/repos/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config)
if err := parseImportId([]string{"projects/(?P<project>[^/]+)/repos/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config); err != nil {
return nil, err
}

// Replace import id for the resource id
id, err := replaceVars(d, config, "projects/{{project}}/repos/{{name}}")
id, err := replaceVars(d, config, "{{project}}/{{name}}")
if err != nil {
return nil, fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)

return []*schema.ResourceData{d}, nil
}

func flattenSourcerepoRepositoryName(v interface{}, d *schema.ResourceData) interface{} {
if v == nil {
return v
}

// We can't use a standard name_from_self_link because the name can include /'s
parts := strings.SplitAfterN(v.(string), "/", 4)
return parts[3]
}

func flattenSourcerepoRepositoryUrl(v interface{}, d *schema.ResourceData) interface{} {
return v
}

func flattenSourcerepoRepositorySize(v interface{}, d *schema.ResourceData) interface{} {
// Handles the string fixed64 format
if strVal, ok := v.(string); ok {
if intVal, err := strconv.ParseInt(strVal, 10, 64); err == nil {
return intVal
} // let terraform core handle it if we can't convert the string to an int.
}
return v
}

func expandSourcerepoRepositoryName(v interface{}, d *schema.ResourceData, config *Config) (interface{}, error) {
return replaceVars(d, config, "projects/{{project}}/repos/{{name}}")
}
82 changes: 82 additions & 0 deletions google/resource_sourcerepo_repository_generated_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
// ----------------------------------------------------------------------------
//
// *** AUTO GENERATED CODE *** AUTO GENERATED CODE ***
//
// ----------------------------------------------------------------------------
//
// This file is automatically generated by Magic Modules and manual
// changes will be clobbered when the file is regenerated.
//
// Please read more about how to change this file in
// .github/CONTRIBUTING.md.
//
// ----------------------------------------------------------------------------

package google

import (
"fmt"
"strings"
"testing"

"github.com/hashicorp/terraform/helper/acctest"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/terraform"
)

func TestAccSourcerepoRepository_sourcerepoRepositoryBasicExample(t *testing.T) {
t.Parallel()

context := map[string]interface{}{
"random_suffix": acctest.RandString(10),
}

resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: testAccProviders,
CheckDestroy: testAccCheckSourcerepoRepositoryDestroy,
Steps: []resource.TestStep{
{
Config: testAccSourcerepoRepository_sourcerepoRepositoryBasicExample(context),
},
{
ResourceName: "google_sourcerepo_repository.my-repo",
ImportState: true,
ImportStateVerify: true,
},
},
})
}

func testAccSourcerepoRepository_sourcerepoRepositoryBasicExample(context map[string]interface{}) string {
return Nprintf(`
resource "google_sourcerepo_repository" "my-repo" {
name = "my-repository-%{random_suffix}"
}
`, context)
}

func testAccCheckSourcerepoRepositoryDestroy(s *terraform.State) error {
for name, rs := range s.RootModule().Resources {
if rs.Type != "google_sourcerepo_repository" {
continue
}
if strings.HasPrefix(name, "data.") {
continue
}

config := testAccProvider.Meta().(*Config)

url, err := replaceVarsForTest(rs, "https://sourcerepo.googleapis.com/v1/projects/{{project}}/repos/{{name}}")
if err != nil {
return err
}

_, err = sendRequest(config, "GET", url, nil)
if err == nil {
return fmt.Errorf("SourcerepoRepository still exists at %s", url)
}
}

return nil
}
Loading

0 comments on commit 181dafe

Please sign in to comment.