From 89980839164ece2bbcb2a8924f7ab6e66311850e Mon Sep 17 00:00:00 2001 From: Alexis Montagne Date: Tue, 28 Oct 2025 11:42:47 -0700 Subject: [PATCH] stringutil: Handle properly acronyms in the CamelToSnakeCase --- stringutil/camel_to_snake_case.go | 12 ++++++++---- stringutil/camel_to_snake_case_test.go | 2 ++ 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/stringutil/camel_to_snake_case.go b/stringutil/camel_to_snake_case.go index 4787797..d7d5d6a 100644 --- a/stringutil/camel_to_snake_case.go +++ b/stringutil/camel_to_snake_case.go @@ -5,11 +5,15 @@ import ( "strings" ) -var upperCase = regexp.MustCompile(`([A-Z]+)`) +var upperCaseRegexps = []*regexp.Regexp{ + regexp.MustCompile(`([A-Z][a-z]+)`), + regexp.MustCompile(`([A-Z]+)`), +} func CamelToSnakeCase(s string) string { - s = upperCase.ReplaceAllString(s, `_$1`) - s = strings.TrimPrefix(s, "_") + for _, re := range upperCaseRegexps { + s = re.ReplaceAllStringFunc(s, func(s string) string { return "_" + strings.ToLower(s) }) + } - return strings.ToLower(s) + return strings.ToLower(strings.TrimPrefix(s, "_")) } diff --git a/stringutil/camel_to_snake_case_test.go b/stringutil/camel_to_snake_case_test.go index 354531a..88d3ca3 100644 --- a/stringutil/camel_to_snake_case_test.go +++ b/stringutil/camel_to_snake_case_test.go @@ -12,6 +12,8 @@ func TestCamelToSnakeCase(t *testing.T) { {"Camel", "camel"}, {"VeryVeryLongCamelCase", "very_very_long_camel_case"}, {"WithAcronymLikeURL", "with_acronym_like_url"}, + {"CRMFetcher", "crm_fetcher"}, + {"A0", "a0"}, } { if out := CamelToSnakeCase(tt.in); tt.out != out { t.Errorf("CamelToSnakeCase(%q) = %q wanted: %q", tt.in, out, tt.out)