From 5ae698589e3d1c9baad522e9ba07cab812c04aab Mon Sep 17 00:00:00 2001 From: Martin Tournoij Date: Thu, 24 Nov 2022 16:25:26 +0100 Subject: [PATCH] Don't double up underscores with -transform=snakecase It would treat an existing underscore as a "word", so one underscore got transformed in to 3. I run in to this semi-regularly when I copy something like a database schema to a struct: type Sequence struct { sequence_id int64 server_id int32 data_type string increment_by int64 cache_size int64 } And this gets transformed to: type Sequence struct { sequence_id int64 `db:"sequence___id"` server_id int32 `db:"server___id"` data_type string `db:"data___type"` increment_by int64 `db:"increment___by"` cache_size int64 `db:"cache___size"` } I could fix up the field names first, which needs to be done anyway, or use `-transform keep`, but this makes it do the right thing with the defaults with a minimal of friction, and I don't expect it to break anything for anyone. --- main.go | 4 ++++ main_test.go | 9 +++++++++ test-fixtures/struct_add_underscore.golden | 5 +++++ test-fixtures/struct_add_underscore.input | 5 +++++ 4 files changed, 23 insertions(+) create mode 100644 test-fixtures/struct_add_underscore.golden create mode 100644 test-fixtures/struct_add_underscore.input diff --git a/main.go b/main.go index e4efff7..b8abf48 100644 --- a/main.go +++ b/main.go @@ -391,6 +391,10 @@ func (c *config) addTags(fieldName string, tags *structtag.Tags) (*structtag.Tag case "snakecase": var lowerSplitted []string for _, s := range splitted { + s = strings.Trim(s, "_") + if s == "" { + continue + } lowerSplitted = append(lowerSplitted, strings.ToLower(s)) } diff --git a/main_test.go b/main_test.go index 1facda4..c83a786 100644 --- a/main_test.go +++ b/main_test.go @@ -32,6 +32,15 @@ func TestRewrite(t *testing.T) { transform: "snakecase", }, }, + { + file: "struct_add_underscore", + cfg: &config{ + add: []string{"json"}, + output: "source", + structName: "foo", + transform: "snakecase", + }, + }, { file: "struct_add_existing", cfg: &config{ diff --git a/test-fixtures/struct_add_underscore.golden b/test-fixtures/struct_add_underscore.golden new file mode 100644 index 0000000..786a7f3 --- /dev/null +++ b/test-fixtures/struct_add_underscore.golden @@ -0,0 +1,5 @@ +package foo + +type foo struct { + foo_bar string `json:"foo_bar"` +} diff --git a/test-fixtures/struct_add_underscore.input b/test-fixtures/struct_add_underscore.input new file mode 100644 index 0000000..74dcca1 --- /dev/null +++ b/test-fixtures/struct_add_underscore.input @@ -0,0 +1,5 @@ +package foo + +type foo struct { + foo_bar string +}