Skip to content

Commit 584600d

Browse files
authored
feat(sidekick/rust): extract variables in rust template (#4346)
Extract segment substitutions into variable bindings before string formatting, making the variables reusable for both `path` and `_resource_name`. For #4183
1 parent fd5d5a4 commit 584600d

3 files changed

Lines changed: 11 additions & 3 deletions

File tree

internal/sidekick/rust/annotate.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -397,6 +397,11 @@ func (s *bindingSubstitution) TemplateAsString() string {
397397
return strings.Join(s.Template, "/")
398398
}
399399

400+
// VariableName returns the variable name to be used in the templates.
401+
func (s *bindingSubstitution) VariableName() string {
402+
return fmt.Sprintf("var_%s", strings.ReplaceAll(s.FieldName, ".", "_"))
403+
}
404+
400405
type pathBindingAnnotation struct {
401406
// The path format string for this binding
402407
//
@@ -1252,7 +1257,7 @@ func makeBindingSubstitution(v *api.PathVariable, m *api.Method) (*bindingSubsti
12521257
}
12531258
var rustNames []string
12541259
for _, n := range v.FieldPath {
1255-
rustNames = append(rustNames, toSnake(n))
1260+
rustNames = append(rustNames, toSnakeNoMangling(n))
12561261
}
12571262
binding := &bindingSubstitution{
12581263
FieldAccessor: fieldAccessor,

internal/sidekick/rust/annotate_test.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1483,7 +1483,7 @@ func TestPathBindingAnnotationsStyle(t *testing.T) {
14831483
{"machine", "machine", "Some(&req).map(|m| &m.machine).map(|s| s.as_str())"},
14841484
{"machineType", "machine_type", "Some(&req).map(|m| &m.machine_type).map(|s| s.as_str())"},
14851485
{"machine_type", "machine_type", "Some(&req).map(|m| &m.machine_type).map(|s| s.as_str())"},
1486-
{"type", "r#type", "Some(&req).map(|m| &m.r#type).map(|s| s.as_str())"},
1486+
{"type", "type", "Some(&req).map(|m| &m.r#type).map(|s| s.as_str())"},
14871487
} {
14881488
field := &api.Field{
14891489
Name: test.FieldName,

internal/sidekick/rust/templates/crate/src/transport.rs.mustache

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,13 @@ impl super::stub::{{Codec.Name}} for {{Codec.Name}} {
104104
{{#PathInfo.Bindings}}
105105
.or_else(|| {
106106
{{#Codec.HasVariablePath}}
107+
{{#Codec.Substitutions}}
108+
let {{VariableName}} = try_match({{{FieldAccessor}}}, {{{TemplateAsArray}}})?;
109+
{{/Codec.Substitutions}}
107110
let path = format!(
108111
"{{Codec.PathFmt}}",
109112
{{#Codec.Substitutions}}
110-
try_match({{{FieldAccessor}}}, {{{TemplateAsArray}}})?,
113+
{{VariableName}},
111114
{{/Codec.Substitutions}}
112115
);
113116
{{/Codec.HasVariablePath}}

0 commit comments

Comments
 (0)