Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add attribute mv and replace commands #111

Merged
merged 3 commits into from
Feb 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,8 @@
- Schemaless: No dependency on specific HCL application binary or schema
- Support HCL2 (not HCL1)
- Available operations:
- attribute append/get/rm/set
- block append/get/list/mv/new/rm
- attribute append / get / mv / replace / rm / set
- block append / get / list / mv / new / rm
- body get
- fmt

Expand Down Expand Up @@ -83,6 +83,8 @@ Usage:
Available Commands:
append Append attribute
get Get attribute
mv Move attribute (Rename attribute key)
replace Replace both the name and value of attribute
rm Remove attribute
set Set attribute

Expand Down Expand Up @@ -122,6 +124,26 @@ resource "foo" "bar" {
}
```

```
$ cat tmp/attr.hcl | hcledit attribute mv resource.foo.bar.nested.attr2 resource.foo.bar.nested.attr3
resource "foo" "bar" {
attr1 = "val1"
nested {
attr3 = "val2"
}
}
```

```
$ cat tmp/attr.hcl | hcledit attribute replace resource.foo.bar.nested.attr2 attr3 '"val3"'
resource "foo" "bar" {
attr1 = "val1"
nested {
attr3 = "val3"
}
}
```

```
$ cat tmp/attr.hcl | hcledit attribute rm resource.foo.bar.attr1
resource "foo" "bar" {
Expand Down
74 changes: 72 additions & 2 deletions cmd/attribute.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ func newAttributeCmd() *cobra.Command {
cmd.AddCommand(
newAttributeGetCmd(),
newAttributeSetCmd(),
newAttributeMvCmd(),
newAttributeReplaceCmd(),
newAttributeRmCmd(),
newAttributeAppendCmd(),
)
Expand Down Expand Up @@ -79,9 +81,9 @@ Arguments:
ADDRESS An address of attribute to set.
VALUE A new value of attribute.
The value is set literally, even if references or expressions.
Thus, if you want to set a string literal "hoge", be sure to
Thus, if you want to set a string literal "foo", be sure to
escape double quotes so that they are not discarded by your shell.
e.g.) hcledit attribute set aaa.bbb.ccc '"hoge"'
e.g.) hcledit attribute set aaa.bbb.ccc '"foo"'
`,
RunE: runAttributeSetCmd,
}
Expand Down Expand Up @@ -119,6 +121,74 @@ Arguments:
return cmd
}

func newAttributeMvCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "mv <FROM_ADDRESS> <TO_ADDRESS>",
Short: "Move attribute (Rename attribute key)",
Long: `Move attribute (Rename attribute key)

Arguments:
FROM_ADDRESS An old address of attribute.
TO_ADDRESS A new address of attribute.
`,
RunE: runAttributeMvCmd,
}

return cmd
}

func runAttributeMvCmd(cmd *cobra.Command, args []string) error {
if len(args) != 2 {
return fmt.Errorf("expected 2 argument, but got %d arguments", len(args))
}

from := args[0]
to := args[1]
file := viper.GetString("file")
update := viper.GetBool("update")

filter := editor.NewAttributeRenameFilter(from, to)
c := newDefaultClient(cmd)
return c.Edit(file, update, filter)
}

func newAttributeReplaceCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "replace <ADDRESS> <NAME> <VALUE>",
Short: "Replace both the name and value of attribute",
Long: `Replace both the name and value of matched attribute at a given address

Arguments:
ADDRESS An address of attribute to be replaced.
NAME A new name (key) of attribute.
VALUE A new value of attribute.
The value is set literally, even if references or expressions.
Thus, if you want to set a string literal "bar", be sure to
escape double quotes so that they are not discarded by your shell.
e.g.) hcledit attribute replace aaa.bbb.ccc foo '"bar"'
`,
RunE: runAttributeReplaceCmd,
}

return cmd
}

func runAttributeReplaceCmd(cmd *cobra.Command, args []string) error {
if len(args) != 3 {
return fmt.Errorf("expected 3 argument, but got %d arguments", len(args))
}

address := args[0]
name := args[1]
value := args[2]
file := viper.GetString("file")
update := viper.GetBool("update")

filter := editor.NewAttributeReplaceFilter(address, name, value)
c := newDefaultClient(cmd)
return c.Edit(file, update, filter)
}

func runAttributeRmCmd(cmd *cobra.Command, args []string) error {
if len(args) != 1 {
return fmt.Errorf("expected 1 argument, but got %d arguments", len(args))
Expand Down
156 changes: 156 additions & 0 deletions cmd/attribute_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,162 @@ module "hoge" {
}
}

func TestAttributeMv(t *testing.T) {
src := `locals {
foo1 = "bar1"
foo2 = "bar2"
}

resource "foo" "bar" {
foo3 = "bar3"
}
`

cases := []struct {
name string
args []string
ok bool
want string
}{
{
name: "simple",
args: []string{"locals.foo1", "locals.foo3"},
ok: true,
want: `locals {
foo3 = "bar1"
foo2 = "bar2"
}

resource "foo" "bar" {
foo3 = "bar3"
}
`,
},
{
name: "no match",
args: []string{"locals.foo3", "locals.foo4"},
ok: true,
want: src,
},
{
name: "duplicated",
args: []string{"locals.foo1", "locals.foo2"},
ok: false,
want: "",
},
{
name: "move an attribute accross blocks",
args: []string{"locals.foo1", "resource.foo.bar.foo1"},
ok: false,
want: "",
},
{
name: "no args",
args: []string{},
ok: false,
want: "",
},
{
name: "1 arg",
args: []string{"hoge"},
ok: false,
want: "",
},
{
name: "too many args",
args: []string{"hoge", "fuga", "piyo"},
ok: false,
want: "",
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := newMockCmd(newAttributeMvCmd(), src)
assertMockCmd(t, cmd, tc.args, tc.ok, tc.want)
})
}
}

func TestAttributeReplace(t *testing.T) {
src := `terraform {
backend "s3" {
region = "ap-northeast-1"
bucket = "my-s3lock-test"
key = "dir1/terraform.tfstate"
dynamodb_table = "tflock"
profile = "foo"
}
}
`

cases := []struct {
name string
args []string
ok bool
want string
}{
{
name: "simple",
args: []string{"terraform.backend.s3.dynamodb_table", "use_lockfile", "true"},
ok: true,
want: `terraform {
backend "s3" {
region = "ap-northeast-1"
bucket = "my-s3lock-test"
key = "dir1/terraform.tfstate"
use_lockfile = true
profile = "foo"
}
}
`,
},
{
name: "no match",
args: []string{"terraform.backend.s3.foo_table", "use_lockfile", "true"},
ok: true,
want: src,
},
{
name: "duplicated",
args: []string{"terraform.backend.s3.dynamodb_table", "profile", "true"},
ok: false,
want: "",
},
{
name: "no args",
args: []string{},
ok: false,
want: "",
},
{
name: "1 arg",
args: []string{"foo"},
ok: false,
want: "",
},
{
name: "2 args",
args: []string{"foo", "bar"},
ok: false,
want: "",
},
{
name: "too many args",
args: []string{"foo", "bar", "baz", "qux"},
ok: false,
want: "",
},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cmd := newMockCmd(newAttributeReplaceCmd(), src)
assertMockCmd(t, cmd, tc.args, tc.ok, tc.want)
})
}
}

func TestAttributeRm(t *testing.T) {
src := `locals {
service = "hoge"
Expand Down
60 changes: 60 additions & 0 deletions editor/filter_attribute_rename.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package editor

import (
"fmt"

"github.com/hashicorp/hcl/v2/hclwrite"
)

// AttributeRenameFilter is a filter implementation for renaming attribute.
type AttributeRenameFilter struct {
from string
to string
}

var _ Filter = (*AttributeRenameFilter)(nil)

// NewAttributeRenameFilter creates a new instance of AttributeRenameFilter.
func NewAttributeRenameFilter(from string, to string) Filter {
return &AttributeRenameFilter{
from: from,
to: to,
}
}

// Filter reads HCL and renames matched an attribute at a given address.
// The current implementation does not allow moving an attribute across blocks,
// but it accepts addresses as arguments, which allows for future extensions.
func (f *AttributeRenameFilter) Filter(inFile *hclwrite.File) (*hclwrite.File, error) {
fromAttr, fromBody, err := findAttribute(inFile.Body(), f.from)
if err != nil {
return nil, err
}

if fromAttr != nil {
fromBlockAddress, fromAttributeName, err := parseAttributeAddress(f.from)
if err != nil {
return nil, err
}
toBlockAddress, toAttributeName, err := parseAttributeAddress(f.to)
if err != nil {
return nil, err
}

if fromBlockAddress == toBlockAddress {
// The Body.RenameAttribute() returns false if fromName does not exist or
// toName already exists. However, here, we want to return an error only
// if toName already exists, so we check it ourselves.
toAttr := fromBody.GetAttribute(toAttributeName)
if toAttr != nil {
return nil, fmt.Errorf("attribute already exists: %s", f.to)
}

_ = fromBody.RenameAttribute(fromAttributeName, toAttributeName)
} else {
return nil, fmt.Errorf("moving an attribute across blocks has not been implemented yet: %s -> %s", f.from, f.to)
}
}

return inFile, nil
}
Loading