github.com/klaytn/klaytn@v1.12.1/cmd/utils/strings.go (about) 1 // Copyright 2018 The klaytn Authors 2 // This file is part of the klaytn library. 3 // 4 // The klaytn library is free software: you can redistribute it and/or modify 5 // it under the terms of the GNU Lesser General Public License as published by 6 // the Free Software Foundation, either version 3 of the License, or 7 // (at your option) any later version. 8 // 9 // The klaytn library is distributed in the hope that it will be useful, 10 // but WITHOUT ANY WARRANTY; without even the implied warranty of 11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12 // GNU Lesser General Public License for more details. 13 // 14 // You should have received a copy of the GNU Lesser General Public License 15 // along with the klaytn library. If not, see <http://www.gnu.org/licenses/>. 16 17 package utils 18 19 import ( 20 "fmt" 21 "regexp" 22 "strings" 23 ) 24 25 // ToCamelCase converts an under-score string to a camel-case string 26 func ToCamelCase(inputUnderScoreStr string) (camelCase string) { 27 isToUpper := false 28 29 for k, v := range inputUnderScoreStr { 30 if k == 0 { 31 camelCase = strings.ToUpper(string(inputUnderScoreStr[0])) 32 } else { 33 if isToUpper { 34 camelCase += strings.ToUpper(string(v)) 35 isToUpper = false 36 } else { 37 if v == '_' { 38 isToUpper = true 39 } else { 40 camelCase += string(v) 41 } 42 } 43 } 44 } 45 return 46 } 47 48 // ToUnderScore converts a camel-case string to a under-score string 49 func ToUnderScore(s string) string { 50 return SplitAndJoin(s, "_") 51 } 52 53 // ToHyphen converts a camel-case string to a hyphen-style string 54 func ToHyphen(s string) string { 55 return SplitAndJoin(s, "-") 56 } 57 58 // SplitAndJoin converts a camel-case string to a string joined by the provided symbol 59 func SplitAndJoin(s string, symbol string) string { 60 camel := regexp.MustCompile("(^[^A-Z0-9]*)?([A-Z0-9]{2,}|[A-Z0-9][^A-Z]+|$)") 61 var a []string 62 for _, sub := range camel.FindAllStringSubmatch(s, -1) { 63 if sub[1] != "" { 64 a = append(a, sub[1]) 65 } 66 if sub[2] != "" { 67 a = append(a, sub[2]) 68 } 69 } 70 71 result := strings.ToLower(strings.Join(a, symbol)) 72 result = strings.TrimPrefix(result, "_") 73 result = strings.TrimSuffix(result, "_") 74 return result 75 } 76 77 func FormatPackage(name string) string { 78 if name == "" { 79 return "" 80 } 81 return fmt.Sprintf("%v.", name) 82 }