github.com/richardwilkes/toolbox@v1.121.0/txt/all_caps.go (about) 1 // Copyright (c) 2016-2024 by Richard A. Wilkes. All rights reserved. 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, version 2.0. If a copy of the MPL was not distributed with 5 // this file, You can obtain one at http://mozilla.org/MPL/2.0/. 6 // 7 // This Source Code Form is "Incompatible With Secondary Licenses", as 8 // defined by the Mozilla Public License, version 2.0. 9 10 // Package txt provides various text utilities. 11 package txt 12 13 import ( 14 _ "embed" 15 "fmt" 16 "regexp" 17 "strings" 18 19 "github.com/richardwilkes/toolbox/errs" 20 "github.com/richardwilkes/toolbox/fatal" 21 ) 22 23 //go:embed all_caps.txt 24 var stdAllCaps string 25 26 // StdAllCaps provides the standard list of words that golint expects to be capitalized, found in the variable 27 // 'commonInitialisms' in https://github.com/golang/lint/blob/master/lint.go#L771-L808 28 var StdAllCaps = MustNewAllCaps(strings.Split(NormalizeLineEndings(stdAllCaps), "\n")...) 29 30 // AllCaps holds information for transforming text with ToCamelCaseWithExceptions. 31 type AllCaps struct { 32 regex *regexp.Regexp 33 } 34 35 // NewAllCaps takes a list of words that should be all uppercase when part of a camel-cased string. 36 func NewAllCaps(in ...string) (*AllCaps, error) { 37 var buffer strings.Builder 38 for _, str := range in { 39 if buffer.Len() > 0 { 40 buffer.WriteByte('|') 41 } 42 buffer.WriteString(FirstToUpper(strings.ToLower(str))) 43 } 44 r, err := regexp.Compile(fmt.Sprintf("(%s)(?:$|[A-Z])", buffer.String())) 45 if err != nil { 46 return nil, errs.Wrap(err) 47 } 48 return &AllCaps{regex: r}, nil 49 } 50 51 // MustNewAllCaps takes a list of words that should be all uppercase when part of a camel-cased string. Failure to 52 // create the AllCaps object causes the program to exit. 53 func MustNewAllCaps(in ...string) *AllCaps { 54 result, err := NewAllCaps(in...) 55 fatal.IfErr(err) 56 return result 57 }