Skip to content

Commit

Permalink
move local variables in resource.erb (GoogleCloudPlatform#9735)
Browse files Browse the repository at this point in the history
  • Loading branch information
c2thorn authored Jan 3, 2024
1 parent ddc054c commit 163480b
Show file tree
Hide file tree
Showing 18 changed files with 248 additions and 223 deletions.
46 changes: 46 additions & 0 deletions mmv1/api/resource.rb
Original file line number Diff line number Diff line change
Expand Up @@ -647,6 +647,52 @@ def delete_uri
end
end

def resource_name
__product.name + name
end

# Filter the properties to keep only the ones don't have custom update
# method and group them by update url & verb.
def properties_without_custom_update(properties)
properties.select do |p|
p.update_url.nil? || p.update_verb.nil? || p.update_verb == :NOOP
end
end

def update_body_properties
update_prop = properties_without_custom_update(settable_properties)
update_prop = update_prop.reject(&:immutable) if update_verb == :PATCH
update_prop
end

# Handwritten TF Operation objects will be shaped like accessContextManager
# while the Google Go Client will have a name like accesscontextmanager
def client_name_pascal
client_name = __product.client_name || __product.name
client_name.camelize(:upper)
end

# In order of preference, use TF override,
# general defined timeouts, or default Timeouts
def timeouts
timeouts_filtered = @timeouts
timeouts_filtered ||= async&.operation&.timeouts
timeouts_filtered ||= Api::Timeouts.new
timeouts_filtered
end

def project?
base_url.include?('{{project}}') || create_url&.include?('{{project}}')
end

def region?
base_url.include?('{{region}}') && parameters.any? { |p| p.name == 'region' && p.ignore_read }
end

def zone?
base_url.include?('{{zone}}') && parameters.any? { |p| p.name == 'zone' && p.ignore_read }
end

def merge(other)
result = self.class.new
instance_variables.each do |v|
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
func <%= resource_name -%>DiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
func <%= object.resource_name -%>DiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
newParts := strings.Split(new, "appengine-")

if len(newParts) == 1 {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
func <%= resource_name -%>DiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
func <%= object.resource_name -%>DiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
oldParts := regexp.MustCompile("projects/[^/]+/repos/").Split(old, -1)
if len(oldParts) == 2 {
return oldParts[1] == new
Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
func <%= resource_name -%>DiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
func <%= object.resource_name -%>DiffSuppress(_, old, new string, _ *schema.ResourceData) bool {
return tpgresource.CompareResourceNames("", old, new, nil)
}
26 changes: 13 additions & 13 deletions mmv1/templates/terraform/iam_policy.go.erb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ parent_resource_name = object.iam_policy.parent_resource_attribute || object.nam
resource_params = extract_identifiers(resource_uri.gsub('{{name}}', "{{#{parent_resource_name}}}"))
-%>

var <%= resource_name -%>IamSchema = map[string]*schema.Schema{
var <%= object.resource_name -%>IamSchema = map[string]*schema.Schema{
<% resource_params.each_with_index do |param, i| -%>
"<%= param.underscore -%>": {
Type: schema.TypeString,
Expand All @@ -54,7 +54,7 @@ var <%= resource_name -%>IamSchema = map[string]*schema.Schema{
<% if object.iam_policy.custom_diff_suppress.nil? -%>
DiffSuppressFunc: tpgresource.CompareSelfLinkOrResourceName,
<% else -%>
DiffSuppressFunc: <%= resource_name -%>DiffSuppress,
DiffSuppressFunc: <%= object.resource_name -%>DiffSuppress,
<% end -%>
<% end # param == object.name -%>
},
Expand All @@ -65,7 +65,7 @@ var <%= resource_name -%>IamSchema = map[string]*schema.Schema{
<%= lines(compile(pwd + '/' + object.iam_policy.custom_diff_suppress)) -%>
<% end -%>

type <%= resource_name -%>IamUpdater struct {
type <%= object.resource_name -%>IamUpdater struct {
<% resource_params.each do |param| -%>
<%= param.camelize(:lower) -%> string
<% end # resource_params.each -%>
Expand All @@ -74,7 +74,7 @@ type <%= resource_name -%>IamUpdater struct {
}

<% provider_default_values = ['project', 'location', 'region', 'zone'] -%>
func <%= resource_name -%>IamUpdaterProducer(d tpgresource.TerraformResourceData, config *transport_tpg.Config) (tpgiamresource.ResourceIamUpdater, error) {
func <%= object.resource_name -%>IamUpdaterProducer(d tpgresource.TerraformResourceData, config *transport_tpg.Config) (tpgiamresource.ResourceIamUpdater, error) {
values := make(map[string]string)

<% resource_params.each do |param| -%>
Expand Down Expand Up @@ -106,7 +106,7 @@ func <%= resource_name -%>IamUpdaterProducer(d tpgresource.TerraformResourceData
values[k] = v
}

u := &<%= resource_name -%>IamUpdater{
u := &<%= object.resource_name -%>IamUpdater{
<% resource_params.each do |param| -%>
<%= param.camelize(:lower) -%>: values["<%= param -%>"],
<% end -%>
Expand Down Expand Up @@ -137,7 +137,7 @@ func <%= resource_name -%>IamUpdaterProducer(d tpgresource.TerraformResourceData
return u, nil
}

func <%= resource_name -%>IdParseFunc(d *schema.ResourceData, config *transport_tpg.Config) error {
func <%= object.resource_name -%>IdParseFunc(d *schema.ResourceData, config *transport_tpg.Config) error {
values := make(map[string]string)

<% resource_params.each do |param| -%>
Expand All @@ -159,7 +159,7 @@ func <%= resource_name -%>IdParseFunc(d *schema.ResourceData, config *transport_
values[k] = v
}

u := &<%= resource_name -%>IamUpdater{
u := &<%= object.resource_name -%>IamUpdater{
<% resource_params.each do |param| -%>
<%= param.camelize(:lower) -%>: values["<%= param -%>"],
<% end -%>
Expand All @@ -181,7 +181,7 @@ func <%= resource_name -%>IdParseFunc(d *schema.ResourceData, config *transport_
return nil
}

func (u *<%= resource_name -%>IamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) {
func (u *<%= object.resource_name -%>IamUpdater) GetResourceIamPolicy() (*cloudresourcemanager.Policy, error) {
url, err := u.qualify<%= object.name -%>Url("<%= object.iam_policy.fetch_iam_policy_method -%>")
if err != nil {
return nil, err
Expand Down Expand Up @@ -246,7 +246,7 @@ func (u *<%= resource_name -%>IamUpdater) GetResourceIamPolicy() (*cloudresource
return out, nil
}

func (u *<%= resource_name -%>IamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error {
func (u *<%= object.resource_name -%>IamUpdater) SetResourceIamPolicy(policy *cloudresourcemanager.Policy) error {
json, err := tpgresource.ConvertToMap(policy)
if err != nil {
return err
Expand Down Expand Up @@ -306,7 +306,7 @@ func (u *<%= resource_name -%>IamUpdater) SetResourceIamPolicy(policy *cloudreso

<% import_url = resource_uri.gsub(/({{)\%?(\w+)(}})/, '%s') -%>
<% string_qualifiers = extract_identifiers(resource_uri.gsub('{{name}}', "{{#{parent_resource_name}}}")).map{|param| "u.#{param.camelize(:lower)}"}.join(', ') -%>
func (u *<%= resource_name -%>IamUpdater) qualify<%= object.name -%>Url(methodIdentifier string) (string, error) {
func (u *<%= object.resource_name -%>IamUpdater) qualify<%= object.name -%>Url(methodIdentifier string) (string, error) {
urlTemplate := fmt.Sprintf("{{<%= object.__product.name -%>BasePath}}%s<%= object.iam_policy.method_name_separator -%>%s", fmt.Sprintf("<%= import_url -%>", <%= string_qualifiers -%>), methodIdentifier)
url, err := tpgresource.ReplaceVars(u.d, u.Config, urlTemplate)
if err != nil {
Expand All @@ -315,14 +315,14 @@ func (u *<%= resource_name -%>IamUpdater) qualify<%= object.name -%>Url(methodId
return url, nil
}

func (u *<%= resource_name -%>IamUpdater) GetResourceId() string {
func (u *<%= object.resource_name -%>IamUpdater) GetResourceId() string {
return fmt.Sprintf("<%= import_url -%>", <%= string_qualifiers -%>)
}

func (u *<%= resource_name -%>IamUpdater) GetMutexKey() string {
return fmt.Sprintf("iam-<%= object.__product.name .downcase -%>-<%= object.name.downcase -%>-%s", u.GetResourceId())
return fmt.Sprintf("iam-<%= object.__product.name.downcase -%>-<%= object.name.downcase -%>-%s", u.GetResourceId())
}

func (u *<%= resource_name -%>IamUpdater) DescribeResource() string {
return fmt.Sprintf("<%= object.__product.name .downcase -%> <%= object.name.downcase -%> %q", u.GetResourceId())
return fmt.Sprintf("<%= object.__product.name.downcase -%> <%= object.name.downcase -%> %q", u.GetResourceId())
}
36 changes: 18 additions & 18 deletions mmv1/templates/terraform/nested_query.go.erb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<% unless object.nested_query.nil? -%>
func flattenNested<%= resource_name -%>(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) {
func flattenNested<%= object.resource_name -%>(d *schema.ResourceData, meta interface{}, res map[string]interface{}) (map[string]interface{}, error) {
var v interface{}
var ok bool

Expand All @@ -26,24 +26,24 @@ func flattenNested<%= resource_name -%>(d *schema.ResourceData, meta interface{}
return nil, fmt.Errorf("expected list or map for value <%= object.nested_query.keys.join(".") -%>. Actual value: %v", v)
}

_, item, err := resource<%=resource_name%>FindNestedObjectInList(d, meta, v.([]interface{}))
_, item, err := resource<%=object.resource_name%>FindNestedObjectInList(d, meta, v.([]interface{}))
if err != nil {
return nil, err
}
return item, nil
}

func resource<%=resource_name%>FindNestedObjectInList(d *schema.ResourceData, meta interface{}, items []interface{}) (index int, item map[string]interface{}, err error) {
func resource<%=object.resource_name%>FindNestedObjectInList(d *schema.ResourceData, meta interface{}, items []interface{}) (index int, item map[string]interface{}, err error) {
<% object.identity.each do |id_prop| -%>
<% if settable_properties.include?(id_prop) -%>
expected<%= titlelize_property(id_prop) -%>, err := expandNested<%= resource_name -%><%= titlelize_property(id_prop) -%>(d.Get("<%= id_prop.name.underscore -%>"), d, meta.(*transport_tpg.Config))
expected<%= titlelize_property(id_prop) -%>, err := expandNested<%= object.resource_name -%><%= titlelize_property(id_prop) -%>(d.Get("<%= id_prop.name.underscore -%>"), d, meta.(*transport_tpg.Config))
if err != nil {
return -1, nil, err
}
<% else -%>
expected<%= titlelize_property(id_prop) -%> := d.Get("<%= id_prop.name.underscore -%>")
<% end # settable_properties.include?(id_prop)-%>
expectedFlattened<%= titlelize_property(id_prop) -%> := flattenNested<%= resource_name -%><%= titlelize_property(id_prop) -%>(expected<%= titlelize_property(id_prop) -%>, d, meta.(*transport_tpg.Config))
expectedFlattened<%= titlelize_property(id_prop) -%> := flattenNested<%= object.resource_name -%><%= titlelize_property(id_prop) -%>(expected<%= titlelize_property(id_prop) -%>, d, meta.(*transport_tpg.Config))
<% end # object.identity.each -%>

// Search list for this resource.
Expand All @@ -62,14 +62,14 @@ func resource<%=resource_name%>FindNestedObjectInList(d *schema.ResourceData, me

<% if object.custom_code.decoder -%>
// Decode list item before comparing.
item, err := resource<%= resource_name -%>Decoder(d, meta, item)
item, err := resource<%= object.resource_name -%>Decoder(d, meta, item)
if err != nil {
return -1, nil, err
}
<% end -%>

<% object.identity.each do |prop| -%>
item<%= titlelize_property(prop) -%> := flattenNested<%= resource_name -%><%= titlelize_property(prop) -%>(item["<%= prop.api_name %>"], d, meta.(*transport_tpg.Config))
item<%= titlelize_property(prop) -%> := flattenNested<%= object.resource_name -%><%= titlelize_property(prop) -%>(item["<%= prop.api_name %>"], d, meta.(*transport_tpg.Config))
// IsEmptyValue check so that if one is nil and the other is "", that's considered a match
if !(tpgresource.IsEmptyValue(reflect.ValueOf(item<%= titlelize_property(prop) -%>)) && tpgresource.IsEmptyValue(reflect.ValueOf(expectedFlattened<%= titlelize_property(prop) -%>))) && !reflect.DeepEqual(item<%= titlelize_property(prop) -%>, expectedFlattened<%= titlelize_property(prop) -%>) {
log.Printf("[DEBUG] Skipping item with <%= prop.api_name %>= %#v, looking for %#v)", item<%= titlelize_property(prop) -%>, expectedFlattened<%= titlelize_property(prop) -%>)
Expand All @@ -88,13 +88,13 @@ func resource<%=resource_name%>FindNestedObjectInList(d *schema.ResourceData, me
%>
// PatchCreateEncoder handles creating request data to PATCH parent resource
// with list including new object.
func resource<%= resource_name -%>PatchCreateEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
currItems, err := resource<%= resource_name -%>ListForPatch(d, meta)
func resource<%= object.resource_name -%>PatchCreateEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
currItems, err := resource<%= object.resource_name -%>ListForPatch(d, meta)
if err != nil {
return nil, err
}

_, found, err := resource<%=resource_name%>FindNestedObjectInList(d, meta, currItems)
_, found, err := resource<%=object.resource_name%>FindNestedObjectInList(d, meta, currItems)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -145,13 +145,13 @@ func resource<%= resource_name -%>PatchCreateEncoder(d *schema.ResourceData, met
<% if updatable?(object, object.root_properties) -%>
// PatchUpdateEncoder handles creating request data to PATCH parent resource
// with list including updated object.
func resource<%= resource_name -%>PatchUpdateEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
items, err := resource<%= resource_name -%>ListForPatch(d, meta)
func resource<%= object.resource_name -%>PatchUpdateEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
items, err := resource<%= object.resource_name -%>ListForPatch(d, meta)
if err != nil {
return nil, err
}

idx, item, err := resource<%=resource_name%>FindNestedObjectInList(d, meta, items)
idx, item, err := resource<%=object.resource_name%>FindNestedObjectInList(d, meta, items)
if err != nil {
return nil, err
}
Expand Down Expand Up @@ -185,19 +185,19 @@ func resource<%= resource_name -%>PatchUpdateEncoder(d *schema.ResourceData, met

// PatchDeleteEncoder handles creating request data to PATCH parent resource
// with list excluding object to delete.
func resource<%= resource_name -%>PatchDeleteEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
currItems, err := resource<%= resource_name -%>ListForPatch(d, meta)
func resource<%= object.resource_name -%>PatchDeleteEncoder(d *schema.ResourceData, meta interface{}, obj map[string]interface{}) (map[string]interface{}, error) {
currItems, err := resource<%= object.resource_name -%>ListForPatch(d, meta)
if err != nil {
return nil, err
}

idx, item, err := resource<%=resource_name%>FindNestedObjectInList(d, meta, currItems)
idx, item, err := resource<%=object.resource_name%>FindNestedObjectInList(d, meta, currItems)
if err != nil {
return nil, err
}
if item == nil {
// Spoof 404 error for proper handling by Delete (i.e. no-op)
return nil, tpgresource.Fake404("nested", "<%= resource_name%>")
return nil, tpgresource.Fake404("nested", "<%= object.resource_name%>")
}

updatedItems := append(currItems[:idx], currItems[idx+1:]...)
Expand All @@ -224,7 +224,7 @@ func resource<%= resource_name -%>PatchDeleteEncoder(d *schema.ResourceData, met
# 2) returns the full list of other resources, rather than just the
# matching resource
-%>
func resource<%= resource_name -%>ListForPatch(d *schema.ResourceData, meta interface{}) ([]interface{}, error) {
func resource<%= object.resource_name -%>ListForPatch(d *schema.ResourceData, meta interface{}) ([]interface{}, error) {
config := meta.(*transport_tpg.Config)
url, err := tpgresource.ReplaceVars(d, config, "<%= "{{#{object.__product.name}BasePath}}#{object.self_link_uri}" -%>")
if err != nil {
Expand Down
10 changes: 5 additions & 5 deletions mmv1/templates/terraform/post_create/labels.erb
Original file line number Diff line number Diff line change
@@ -1,17 +1,17 @@
<% if properties.any?{ |p| p.name == "labels" } -%>
<% if object.properties.any?{ |p| p.name == "labels" } -%>
if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect.ValueOf(v)) && (ok || !reflect.DeepEqual(v, labelsProp)) {
labels := d.Get("labels")
terraformLables := d.Get("terraform_labels")

// Labels cannot be set in a create. We'll have to set them here.
err = resource<%= resource_name -%>Read(d, meta)
err = resource<%= object.resource_name -%>Read(d, meta)
if err != nil {
return err
}

obj := make(map[string]interface{})
// d.Get("effective_labels") will have been overridden by the Read call.
labelsProp, err := expand<%= resource_name -%>EffectiveLabels(v, d, config)
labelsProp, err := expand<%= object.resource_name -%>EffectiveLabels(v, d, config)
if err != nil {
return err
}
Expand All @@ -38,11 +38,11 @@ if v, ok := d.GetOkExists("effective_labels"); !tpgresource.IsEmptyValue(reflect
<% end -%>
})
if err != nil {
return fmt.Errorf("Error adding labels to <%= resource_name -%> %q: %s", d.Id(), err)
return fmt.Errorf("Error adding labels to <%= object.resource_name -%> %q: %s", d.Id(), err)
}

err = ComputeOperationWaitTime(
config, res, project, "Updating <%= resource_name -%> Labels", userAgent,
config, res, project, "Updating <%= object.resource_name -%> Labels", userAgent,
d.Timeout(schema.TimeoutUpdate))

if err != nil {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
log.Printf("[WARN] Attempt to clean up <%= object.name -%> if it still exists")
var cleanErr error
if cleanErr = resource<%= resource_name -%>Read(d, meta); cleanErr == nil {
if cleanErr = resource<%= object.resource_name -%>Read(d, meta); cleanErr == nil {
if d.Id() != "" {
log.Printf("[WARN] <%= object.name -%> %q still exists, attempting to delete...", d.Id())
if cleanErr = resource<%= resource_name -%>Delete(d, meta); cleanErr == nil {
if cleanErr = resource<%= object.resource_name -%>Delete(d, meta); cleanErr == nil {
log.Printf("[WARN] Invalid <%= object.name -%> was successfully deleted")
d.SetId("")
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@ if isDefaultStartFlow || isDefaultWelcomeIntent || isDefaultNegativeIntent {
d.SetId(id)

// and defer to the Update method:
log.Printf("[DEBUG] Updating default <%= resource_name -%>")
return resource<%= resource_name -%>Update(d, meta)
log.Printf("[DEBUG] Updating default <%= object.resource_name -%>")
return resource<%= object.resource_name -%>Update(d, meta)
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,24 @@
location := ""

if parts := regexp.MustCompile(`locations\/([^\/]*)\/`).FindStringSubmatch(d.Get("parent").(string)); parts != nil {
location = parts[1]
location = parts[1]
} else {
return fmt.Errorf(
"Saw %s when the parent is expected to contains location %s",
d.Get("parent"),
"projects/{{project}}/locations/{{location}}/...",
)
return fmt.Errorf(
"Saw %s when the parent is expected to contains location %s",
d.Get("parent"),
"projects/{{project}}/locations/{{location}}/...",
)
}

url = strings.Replace(url,"-dialogflow",fmt.Sprintf("%s-dialogflow",location),1)
url = strings.Replace(url, "-dialogflow", fmt.Sprintf("%s-dialogflow", location), 1)

// if it's a default object Dialogflow creates for you, skip deletion
// Note: below we try to access fields that aren't present in the resource, because this custom code is reused across multiple Dialogflow resources that contain different fields. When the field isn't present, we deliberately ignore the error and the boolean is false.
isDefaultStartFlow, _ := d.Get("is_default_start_flow").(bool)
isDefaultWelcomeIntent, _ := d.Get("is_default_welcome_intent").(bool)
isDefaultNegativeIntent, _ := d.Get("is_default_negative_intent").(bool)
if isDefaultStartFlow || isDefaultWelcomeIntent || isDefaultNegativeIntent {
// we can't delete these resources so do nothing
log.Printf("[DEBUG] Not deleting default <%= resource_name -%>")
return nil
// we can't delete these resources so do nothing
log.Printf("[DEBUG] Not deleting default <%= object.resource_name -%>")
return nil
}
Loading

0 comments on commit 163480b

Please sign in to comment.