diff --git a/core/stringx/strings.go b/core/stringx/strings.go index 477fdd07..4a89d465 100644 --- a/core/stringx/strings.go +++ b/core/stringx/strings.go @@ -40,6 +40,20 @@ func Filter(s string, filter func(r rune) bool) string { return string(chars[:n]) } +// FirstN returns first n runes from s. +func FirstN(s string, n int) string { + var i int + + for j := range s { + if i == n { + return s[:j] + } + i++ + } + + return s +} + // HasEmpty checks if there are empty strings in args. func HasEmpty(args ...string) bool { for _, arg := range args { diff --git a/core/stringx/strings_test.go b/core/stringx/strings_test.go index 184fceb0..fe118e5f 100644 --- a/core/stringx/strings_test.go +++ b/core/stringx/strings_test.go @@ -92,6 +92,46 @@ func TestFilter(t *testing.T) { } } +func TestFirstN(t *testing.T) { + tests := []struct { + name string + input string + n int + expect string + }{ + { + name: "english string", + input: "anything that we use", + n: 8, + expect: "anything", + }, + { + name: "english string more", + input: "anything that we use", + n: 80, + expect: "anything that we use", + }, + { + name: "chinese string", + input: "我是中国人", + n: 2, + expect: "我是", + }, + { + name: "chinese string", + input: "我是中国人", + n: 10, + expect: "我是中国人", + }, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + assert.Equal(t, test.expect, FirstN(test.input, test.n)) + }) + } +} + func TestRemove(t *testing.T) { cases := []struct { input []string diff --git a/tools/goctl/util/env/env.go b/tools/goctl/util/env/env.go index 6c8209d8..9e9e0a77 100644 --- a/tools/goctl/util/env/env.go +++ b/tools/goctl/util/env/env.go @@ -10,10 +10,12 @@ import ( "github.com/tal-tech/go-zero/tools/goctl/vars" ) -const bin = "bin" -const binGo = "go" -const binProtoc = "protoc" -const binProtocGenGo = "protoc-gen-go" +const ( + bin = "bin" + binGo = "go" + binProtoc = "protoc" + binProtocGenGo = "protoc-gen-go" +) // LookUpGo searches an executable go in the directories // named by the GOROOT/bin or PATH environment variable.