Autogenerate google_sourcerepo_repository (#2797)

This commit is contained in:
The Magician 2019-01-03 16:53:43 -08:00 committed by Riley Karson
parent 6b29503ef5
commit 181dafe6d7
6 changed files with 300 additions and 141 deletions

View File

@ -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),

View File

@ -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(),
}

View File

@ -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,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
"project": {
Type: schema.TypeString,
Optional: true,
Computed: true,
ForceNew: true,
},
"size": {
Type: schema.TypeInt,
Computed: true,
},
"url": {
Type: schema.TypeString,
Computed: true,
},
},
}
}
func resourceSourceRepoRepositoryCreate(d *schema.ResourceData, meta interface{}) error {
func resourceSourcerepoRepositoryCreate(d *schema.ResourceData, meta interface{}) error {
config := meta.(*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
}
url, err := replaceVars(d, config, "https://sourcerepo.googleapis.com/v1/projects/{{project}}/repos")
if err != nil {
return err
}
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)
}
// Store the ID now
id, err := replaceVars(d, config, "{{project}}/{{name}}")
if err != nil {
return fmt.Errorf("Error constructing id: %s", err)
}
d.SetId(id)
log.Printf("[DEBUG] Finished creating Repository %q: %#v", d.Id(), res)
return resourceSourcerepoRepositoryRead(d, meta)
}
func resourceSourcerepoRepositoryRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
url, err := replaceVars(d, config, "https://sourcerepo.googleapis.com/v1/projects/{{project}}/repos/{{name}}")
if err != nil {
return err
}
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 err
}
repoName := d.Get("name").(string)
name := buildRepositoryName(project, repoName)
repo := &sourcerepo.Repo{
Name: name,
if err := d.Set("project", project); err != nil {
return fmt.Errorf("Error reading Repository: %s", err)
}
parent := "projects/" + project
op, err := config.clientSourceRepo.Projects.Repos.Create(parent, repo).Do()
if err != nil {
return fmt.Errorf("Error creating the Source Repo: %s", err)
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)
}
d.SetId(op.Name)
return nil
}
func resourceSourceRepoRepositoryRead(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)
repo, err := config.clientSourceRepo.Projects.Repos.Get(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 handleNotFoundError(err, d, fmt.Sprintf("Source Repo %q", d.Id()))
return handleNotFoundError(err, d, "Repository")
}
d.Set("size", repo.Size)
d.Set("project", project)
d.Set("url", repo.Url)
log.Printf("[DEBUG] Finished deleting Repository %q: %#v", d.Id(), res)
return nil
}
func resourceSourceRepoRepositoryDelete(d *schema.ResourceData, meta interface{}) error {
func resourceSourcerepoRepositoryImport(d *schema.ResourceData, meta interface{}) ([]*schema.ResourceData, error) {
config := meta.(*Config)
project, err := getProject(d, config)
if err != nil {
return err
if err := parseImportId([]string{"projects/(?P<project>[^/]+)/repos/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config); err != nil {
return nil, err
}
repoName := d.Get("name").(string)
name := buildRepositoryName(project, repoName)
_, err = config.clientSourceRepo.Projects.Repos.Delete(name).Do()
if err != nil {
return fmt.Errorf("Error deleting the Source Repo: %s", err)
}
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) {
config := meta.(*Config)
parseImportId([]string{"projects/(?P<project>[^/]+)/repos/(?P<name>[^/]+)", "(?P<project>[^/]+)/(?P<name>[^/]+)", "(?P<name>[^/]+)"}, d, config)
// 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}}")
}

View File

@ -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
}

View File

@ -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)
}

View File

@ -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/)
<div class = "oics-button" style="float: right; margin: 0 0 -15px">
<a href="https://console.cloud.google.com/cloudshell/open?cloudshell_git_repo=https%3A%2F%2Fgithub.com%2Fterraform-google-modules%2Fdocs-examples.git&cloudshell_working_dir=sourcerepo_repository_basic&cloudshell_image=gcr.io%2Fgraphite-cloud-shell-images%2Fterraform%3Alatest&open_in_editor=main.tf&cloudshell_print=.%2Fmotd&cloudshell_tutorial=.%2Ftutorial.md" target="_blank">
<img alt="Open in Cloud Shell" src="//gstatic.com/cloudssh/images/open-btn.svg" style="max-height: 44px; margin: 32px auto; max-width: 100%;">
</a>
</div>
## 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.