Skip to content

Commit

Permalink
Don't double up underscores with -transform=snakecase
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
arp242 committed Nov 24, 2022
1 parent 450757f commit 5ae6985
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 0 deletions.
4 changes: 4 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -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))
}

Expand Down
9 changes: 9 additions & 0 deletions main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{
Expand Down
5 changes: 5 additions & 0 deletions test-fixtures/struct_add_underscore.golden
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package foo

type foo struct {
foo_bar string `json:"foo_bar"`
}
5 changes: 5 additions & 0 deletions test-fixtures/struct_add_underscore.input
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package foo

type foo struct {
foo_bar string
}

0 comments on commit 5ae6985

Please sign in to comment.