From 181dafe6d7032f23c9c65c853899741ae1048fac Mon Sep 17 00:00:00 2001 From: The Magician Date: Thu, 3 Jan 2019 16:53:43 -0800 Subject: [PATCH] Autogenerate google_sourcerepo_repository (#2797) --- google/provider.go | 2 +- google/provider_sourcerepo_gen.go | 21 +++ google/resource_sourcerepo_repository.go | 168 ++++++++++++------ ...ce_sourcerepo_repository_generated_test.go | 82 +++++++++ google/resource_sourcerepo_repository_test.go | 60 +------ .../r/sourcerepo_repository.html.markdown | 76 ++++++-- 6 files changed, 284 insertions(+), 125 deletions(-) create mode 100644 google/provider_sourcerepo_gen.go create mode 100644 google/resource_sourcerepo_repository_generated_test.go diff --git a/google/provider.go b/google/provider.go index bd1cacb461f..8deade14d6e 100644 --- a/google/provider.go +++ b/google/provider.go @@ -120,6 +120,7 @@ func ResourceMapWithErrors() (map[string]*schema.Resource, error) { GeneratedDnsResourcesMap, GeneratedRedisResourcesMap, GeneratedResourceManagerResourcesMap, + GeneratedSourcerepoResourcesMap, GeneratedStorageResourcesMap, GeneratedMonitoringResourcesMap, map[string]*schema.Resource{ @@ -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), diff --git a/google/provider_sourcerepo_gen.go b/google/provider_sourcerepo_gen.go new file mode 100644 index 00000000000..ee00b85a2bf --- /dev/null +++ b/google/provider_sourcerepo_gen.go @@ -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(), +} diff --git a/google/resource_sourcerepo_repository.go b/google/resource_sourcerepo_repository.go index bf37b02a81a..a14bfe36044 100644 --- a/google/resource_sourcerepo_repository.go +++ b/google/resource_sourcerepo_repository.go @@ -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{ @@ -24,107 +46,119 @@ 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[^/]+)/repos/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, d, config) + if err := parseImportId([]string{"projects/(?P[^/]+)/repos/(?P[^/]+)", "(?P[^/]+)/(?P[^/]+)", "(?P[^/]+)"}, 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) } @@ -132,3 +166,31 @@ func resourceSourceRepoRepositoryImport(d *schema.ResourceData, meta interface{} 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}}") +} diff --git a/google/resource_sourcerepo_repository_generated_test.go b/google/resource_sourcerepo_repository_generated_test.go new file mode 100644 index 00000000000..13e89c5daca --- /dev/null +++ b/google/resource_sourcerepo_repository_generated_test.go @@ -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 +} diff --git a/google/resource_sourcerepo_repository_test.go b/google/resource_sourcerepo_repository_test.go index 9de7dbe7e38..9115f77c82f 100644 --- a/google/resource_sourcerepo_repository_test.go +++ b/google/resource_sourcerepo_repository_test.go @@ -6,24 +6,19 @@ import ( "github.com/hashicorp/terraform/helper/acctest" "github.com/hashicorp/terraform/helper/resource" - "github.com/hashicorp/terraform/terraform" ) -func TestAccSourceRepoRepository_basic(t *testing.T) { +func TestAccSourcerepoRepository_basic(t *testing.T) { t.Parallel() repositoryName := fmt.Sprintf("source-repo-repository-test-%s", acctest.RandString(10)) resource.Test(t, resource.TestCase{ PreCheck: func() { testAccPreCheck(t) }, Providers: testAccProviders, - CheckDestroy: testAccCheckSourceRepoRepositoryDestroy, + CheckDestroy: testAccCheckSourcerepoRepositoryDestroy, Steps: []resource.TestStep{ { Config: testAccSourceRepoRepository_basic(repositoryName), - Check: resource.ComposeTestCheckFunc( - testAccCheckSourceRepoRepositoryExists( - "google_sourcerepo_repository.acceptance", repositoryName), - ), }, { ResourceName: "google_sourcerepo_repository.acceptance", @@ -34,55 +29,10 @@ func TestAccSourceRepoRepository_basic(t *testing.T) { }) } -func testAccCheckSourceRepoRepositoryDestroy(s *terraform.State) error { - config := testAccProvider.Meta().(*Config) - - for _, rs := range s.RootModule().Resources { - if rs.Type == "google_sourcerepo_repository" { - repositoryName := buildRepositoryName(config.Project, rs.Primary.Attributes["name"]) - - _, err := config.clientSourceRepo.Projects.Repos.Get(repositoryName).Do() - if err == nil { - return fmt.Errorf(repositoryName + "Source Repository still exists") - } - } - } - - return nil -} - -func testAccCheckSourceRepoRepositoryExists(resourceType, resourceName string) resource.TestCheckFunc { - return func(s *terraform.State) error { - rs, ok := s.RootModule().Resources[resourceType] - if !ok { - return fmt.Errorf("Not found: %s", resourceName) - } - - if rs.Primary.ID == "" { - return fmt.Errorf("No ID is set") - } - - config := testAccProvider.Meta().(*Config) - - repositoryName := buildRepositoryName(config.Project, resourceName) - - resp, err := config.clientSourceRepo.Projects.Repos.Get(repositoryName).Do() - - if err != nil { - return fmt.Errorf("Error confirming Source Repository existence: %#v", err) - } - - if resp.Name != repositoryName { - return fmt.Errorf("Failed to verify Source Repository by name") - } - return nil - } -} - func testAccSourceRepoRepository_basic(repositoryName string) string { return fmt.Sprintf(` - resource "google_sourcerepo_repository" "acceptance" { - name = "%s" - } +resource "google_sourcerepo_repository" "acceptance" { + name = "%s" +} `, repositoryName) } diff --git a/website/docs/r/sourcerepo_repository.html.markdown b/website/docs/r/sourcerepo_repository.html.markdown index 68daab13179..201c24ca2e1 100644 --- a/website/docs/r/sourcerepo_repository.html.markdown +++ b/website/docs/r/sourcerepo_repository.html.markdown @@ -1,24 +1,46 @@ --- +# ---------------------------------------------------------------------------- +# +# *** 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. +# +# ---------------------------------------------------------------------------- layout: "google" page_title: "Google: google_sourcerepo_repository" -sidebar_current: "docs-google-sourcerepo_repository" +sidebar_current: "docs-google-sourcerepo-repository" description: |- - Manages repositories within Google Cloud Source Repositories. + A repository (or repo) is a Git repository storing versioned source content. --- # google\_sourcerepo\_repository -For more information, see [the official -documentation](https://cloud.google.com/source-repositories/) and -[API](https://cloud.google.com/source-repositories/docs/reference/rest/v1/projects.repos) +A repository (or repo) is a Git repository storing versioned source content. -## Example Usage -This example is the common case of creating a repository within Google Cloud Source Repositories: +To get more information about Repository, see: + +* [API documentation](https://cloud.google.com/source-repositories/docs/reference/rest/v1/projects.repos) +* How-to Guides + * [Official Documentation](https://cloud.google.com/source-repositories/) + + +## Example Usage - Sourcerepo Repository Basic + ```hcl -resource "google_sourcerepo_repository" "frontend" { - name = "frontend" +resource "google_sourcerepo_repository" "my-repo" { + name = "my-repository" } ``` @@ -26,26 +48,48 @@ resource "google_sourcerepo_repository" "frontend" { The following arguments are supported: -* `name` - (Required) The name of the repository that will be created. + +* `name` - + (Required) + Resource name of the repository, of the form `{{repo}}`. + The repo name may contain slashes. eg, `name/with/slash` + - - - -* `project` - (Optional) The ID of the project in which the resource belongs. If it - is not provided, the provider project is used. +* `project` - (Optional) The ID of the project in which the resource belongs. + If it is not provided, the provider project is used. + ## Attributes Reference -The following attributes are exported: +In addition to the arguments listed above, the following computed attributes are exported: + -* `size` - The size of the repository. -* `url` - The url to clone the repository. +* `url` - + URL to clone the repository from Google Cloud Source Repositories. + +* `size` - + The disk usage of the repo, in bytes. + + +## Timeouts + +This resource provides the following +[Timeouts](/docs/configuration/resources.html#timeouts) configuration options: + +- `create` - Default is 4 minutes. +- `delete` - Default is 4 minutes. ## Import -Google Cloud Source Repositories can be imported using any of these accepted formats: +Repository can be imported using any of these accepted formats: ``` $ terraform import google_sourcerepo_repository.default projects/{{project}}/repos/{{name}} $ terraform import google_sourcerepo_repository.default {{project}}/{{name}} $ terraform import google_sourcerepo_repository.default {{name}} ``` + +-> If you're importing a resource with beta features, make sure to include `-provider=google-beta` +as an argument so that Terraform uses the correct provider to import your resource.