Skip to content

Commit

Permalink
[strutil] Code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
andyone committed Feb 12, 2024
1 parent 420f841 commit 597b938
Show file tree
Hide file tree
Showing 14 changed files with 58 additions and 57 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

* `[log]` Added `NilLogger`
* `[path]` Handle both directions in `DirN`
* `[strutil]` Code refactoring

### 12.99.0

Expand Down
20 changes: 10 additions & 10 deletions cron/cron.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,10 @@ const (
// ////////////////////////////////////////////////////////////////////////////////// //

const (
_SYMBOL_PERIOD = "-"
_SYMBOL_INTERVAL = "/"
_SYMBOL_ENUM = ","
_SYMBOL_ANY = "*"
_SYMBOL_PERIOD = '-'
_SYMBOL_INTERVAL = '/'
_SYMBOL_ENUM = ','
_SYMBOL_ANY = '*'
)

const (
Expand Down Expand Up @@ -106,7 +106,7 @@ func Parse(expr string) (*Expr, error) {
var data []uint8
var err error

token := strutil.ReadField(expr, tn, true, " ")
token := strutil.ReadField(expr, tn, true, ' ')

switch {
case isAnyToken(token):
Expand Down Expand Up @@ -322,25 +322,25 @@ func (e *Expr) String() string {
// ////////////////////////////////////////////////////////////////////////////////// //

func isAnyToken(t string) bool {
return t == _SYMBOL_ANY
return t == string(_SYMBOL_ANY)
}

func isEnumToken(t string) bool {
return strings.Contains(t, _SYMBOL_ENUM)
return strings.ContainsRune(t, _SYMBOL_ENUM)
}

func isPeriodToken(t string) bool {
return strings.Contains(t, _SYMBOL_PERIOD)
return strings.ContainsRune(t, _SYMBOL_PERIOD)
}

func isIntervalToken(t string) bool {
return strings.Contains(t, _SYMBOL_INTERVAL)
return strings.ContainsRune(t, _SYMBOL_INTERVAL)
}

func parseEnumToken(t string, ei exprInfo) ([]uint8, error) {
var result []uint8

for i := 0; i <= strings.Count(t, _SYMBOL_ENUM); i++ {
for i := 0; i <= strings.Count(t, string(_SYMBOL_ENUM)); i++ {
tt := strutil.ReadField(t, i, false, _SYMBOL_ENUM)

switch {
Expand Down
6 changes: 3 additions & 3 deletions fmtutil/fmtutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -301,13 +301,13 @@ func CountDigits(i int) int {
// ////////////////////////////////////////////////////////////////////////////////// //

func formatPrettyFloat(str, sep string) string {
flt := strings.TrimRight(strutil.ReadField(str, 1, false, "."), "0")
flt := strings.TrimRight(strutil.ReadField(str, 1, false, '.'), "0")

if flt == "" {
return appendPrettySymbol(strutil.ReadField(str, 0, false, "."), sep)
return appendPrettySymbol(strutil.ReadField(str, 0, false, '.'), sep)
}

return appendPrettySymbol(strutil.ReadField(str, 0, false, "."), sep) + "." + flt
return appendPrettySymbol(strutil.ReadField(str, 0, false, '.'), sep) + "." + flt
}

func appendPrettySymbol(str, sep string) string {
Expand Down
10 changes: 5 additions & 5 deletions initsystem/initsystem.go
Original file line number Diff line number Diff line change
Expand Up @@ -322,15 +322,15 @@ func parseSysvEnabledOutput(data string) (bool, error) {
}

func parseSystemdStatusOutput(name, data string) (bool, error) {
loadState := strutil.ReadField(data, 0, false, "\n")
loadStateValue := strutil.ReadField(loadState, 1, false, "=")
loadState := strutil.ReadField(data, 0, false, '\n')
loadStateValue := strutil.ReadField(loadState, 1, false, '=')

if strings.Trim(loadStateValue, "\r\n") == "not-found" {
return false, fmt.Errorf("Unit %s could not be found", name)
}

activeState := strutil.ReadField(data, 1, false, "\n")
activeStateValue := strutil.ReadField(activeState, 1, false, "=")
activeState := strutil.ReadField(data, 1, false, '\n')
activeStateValue := strutil.ReadField(activeState, 1, false, '=')

switch strings.Trim(activeStateValue, "\r\n") {
case "active":
Expand All @@ -345,7 +345,7 @@ func parseSystemdStatusOutput(name, data string) (bool, error) {

func parseUpstartStatusOutput(data string) (bool, error) {
data = strings.TrimRight(data, "\r\n")
status := strutil.ReadField(data, 1, false, " ")
status := strutil.ReadField(data, 1, false, ' ')

switch status {
case "start/running":
Expand Down
4 changes: 2 additions & 2 deletions strutil/example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,8 @@ func ExampleFields() {
}

func ExampleReadField() {
fmt.Println(ReadField("Bob Alice\tJohn Mary", 2, true, " ", "\t"))
fmt.Println(ReadField("Bob:::Mary:John:", 3, false, ":"))
fmt.Println(ReadField("Bob Alice\tJohn Mary", 2, true, ' ', '\t'))
fmt.Println(ReadField("Bob:::Mary:John:", 3, false, ':'))

// Output:
// John
Expand Down
6 changes: 3 additions & 3 deletions strutil/strutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ var EllipsisSuffix = "..."

// ////////////////////////////////////////////////////////////////////////////////// //

var defaultFieldsSeparators = []string{" ", "\t"}
var defaultFieldsSeparators = []rune{' ', '\t'}

// ////////////////////////////////////////////////////////////////////////////////// //

Expand Down Expand Up @@ -318,7 +318,7 @@ func Exclude(data, substr string) string {
}

// ReadField reads field with given index from data
func ReadField(data string, index int, multiSep bool, separators ...string) string {
func ReadField(data string, index int, multiSep bool, separators ...rune) string {
if data == "" || index < 0 {
return ""
}
Expand All @@ -332,7 +332,7 @@ func ReadField(data string, index int, multiSep bool, separators ...string) stri
MAINLOOP:
for i, r := range data {
for _, s := range separators {
if r == rune(s[0]) {
if r == s {
if curIndex == index {
return data[startPointer:i]
}
Expand Down
6 changes: 3 additions & 3 deletions strutil/strutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -156,9 +156,9 @@ func (s *StrUtilSuite) TestReadField(c *C) {
c.Assert(ReadField("abc 1234 DEF", 2, true), Equals, "DEF")
c.Assert(ReadField("abc 1234 DEF", 3, true), Equals, "")

c.Assert(ReadField("abc|||||1234||DEF", 1, true, "|"), Equals, "1234")
c.Assert(ReadField("abc+1234|DEF", 1, true, "|", "+"), Equals, "1234")
c.Assert(ReadField("abc::1234:::DEF:", 5, false, ":"), Equals, "DEF")
c.Assert(ReadField("abc|||||1234||DEF", 1, true, '|'), Equals, "1234")
c.Assert(ReadField("abc+1234|DEF", 1, true, '|', '+'), Equals, "1234")
c.Assert(ReadField("abc::1234:::DEF:", 5, false, ':'), Equals, "DEF")
}

func (s *StrUtilSuite) TestCopy(c *C) {
Expand Down
18 changes: 9 additions & 9 deletions system/info_cpu_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,25 +246,25 @@ func parseCPUInfo(s *bufio.Scanner) ([]*CPUInfo, error) {

switch {
case strings.HasPrefix(text, "vendor_id"):
vendor = strings.Trim(strutil.ReadField(text, 1, false, ":"), " ")
vendor = strings.Trim(strutil.ReadField(text, 1, false, ':'), " ")

case strings.HasPrefix(text, "model name"):
model = strings.Trim(strutil.ReadField(text, 1, false, ":"), " ")
model = strings.Trim(strutil.ReadField(text, 1, false, ':'), " ")

case strings.HasPrefix(text, "cache size"):
cache, err = parseSize(strings.Trim(strutil.ReadField(text, 1, false, ":"), " KB"))
cache, err = parseSize(strings.Trim(strutil.ReadField(text, 1, false, ':'), " KB"))

case strings.HasPrefix(text, "cpu MHz"):
speed, err = strconv.ParseFloat(strings.Trim(strutil.ReadField(text, 1, false, ":"), " "), 64)
speed, err = strconv.ParseFloat(strings.Trim(strutil.ReadField(text, 1, false, ':'), " "), 64)

case strings.HasPrefix(text, "physical id"):
id, err = strconv.Atoi(strings.Trim(strutil.ReadField(text, 1, false, ":"), " "))
id, err = strconv.Atoi(strings.Trim(strutil.ReadField(text, 1, false, ':'), " "))

case strings.HasPrefix(text, "siblings"):
siblings, err = strconv.Atoi(strings.Trim(strutil.ReadField(text, 1, false, ":"), " "))
siblings, err = strconv.Atoi(strings.Trim(strutil.ReadField(text, 1, false, ':'), " "))

case strings.HasPrefix(text, "cpu cores"):
cores, err = strconv.Atoi(strings.Trim(strutil.ReadField(text, 1, false, ":"), " "))
cores, err = strconv.Atoi(strings.Trim(strutil.ReadField(text, 1, false, ':'), " "))

case strings.HasPrefix(text, "flags"):
if len(info) < id+1 {
Expand Down Expand Up @@ -292,8 +292,8 @@ func parseCPUInfo(s *bufio.Scanner) ([]*CPUInfo, error) {

// parseCPUCountInfo parses CPU count data
func parseCPUCountInfo(data string) uint32 {
startNum := strings.Trim(strutil.ReadField(data, 0, false, "-"), "\n\r")
endNum := strings.Trim(strutil.ReadField(data, 1, false, "-"), "\n\r")
startNum := strings.Trim(strutil.ReadField(data, 0, false, '-'), "\n\r")
endNum := strings.Trim(strutil.ReadField(data, 1, false, '-'), "\n\r")

start, _ := strconv.ParseUint(startNum, 10, 32)
end, _ := strconv.ParseUint(endNum, 10, 32)
Expand Down
4 changes: 2 additions & 2 deletions system/info_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ func ParseOSInfo(file string) (*OSInfo, error) {
continue
}

name := strutil.ReadField(line, 0, false, "=")
value := strings.Trim(strutil.ReadField(line, 1, false, "="), "\"")
name := strutil.ReadField(line, 0, false, '=')
value := strings.Trim(strutil.ReadField(line, 1, false, '='), "\"")

applyOSInfo(info, name, value)
}
Expand Down
6 changes: 3 additions & 3 deletions system/process/process_mount.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ func parseMountInfoLine(data string) (*MountInfo, error) {

for i := 0; i < 128; i++ {
pseudoIndex := i - optFieldsNum
value := strutil.ReadField(data, i, false, " ")
value := strutil.ReadField(data, i, false, ' ')

if i >= 6 && !optFieldParsed {
if value != "-" {
Expand Down Expand Up @@ -131,13 +131,13 @@ func parseMountInfoLine(data string) (*MountInfo, error) {

// parseStDevValue parses st_dev major and minor values
func parseStDevValue(data string) (uint16, uint16, error) {
major, err := parseFieldUint16(strutil.ReadField(data, 0, false, ":"), "StDevMajor")
major, err := parseFieldUint16(strutil.ReadField(data, 0, false, ':'), "StDevMajor")

if err != nil {
return 0, 0, err
}

minor, err := parseFieldUint16(strutil.ReadField(data, 1, false, ":"), "StDevMinor")
minor, err := parseFieldUint16(strutil.ReadField(data, 1, false, ':'), "StDevMinor")

if err != nil {
return 0, 0, err
Expand Down
8 changes: 4 additions & 4 deletions system/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -427,14 +427,14 @@ func extractGroupsInfo(data string) []*Group {
var result []*Group

data = strings.TrimRight(data, "\n")
groupsInfo := strutil.ReadField(data, 3, false, "=")
groupsInfo := strutil.ReadField(data, 3, false, '=')

if groupsInfo == "" {
return nil
}

for {
groupInfo := strutil.ReadField(groupsInfo, field, false, ",")
groupInfo := strutil.ReadField(groupsInfo, field, false, ',')

if groupInfo == "" {
break
Expand All @@ -454,8 +454,8 @@ func extractGroupsInfo(data string) []*Group {

// parseGroupInfo parse group info from 'id' command
func parseGroupInfo(data string) (*Group, error) {
id := strutil.ReadField(data, 0, false, "(")
name := strutil.ReadField(data, 1, false, "(")
id := strutil.ReadField(data, 0, false, '(')
name := strutil.ReadField(data, 1, false, '(')
gid, _ := strconv.Atoi(id)

if len(name) == 0 {
Expand Down
18 changes: 9 additions & 9 deletions system/user_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,35 +67,35 @@ func getGroupInfo(nameOrID string) (*Group, error) {
func parseGetentPasswdOutput(data string) (*User, error) {
data = strings.TrimRight(data, "\r\n")

uid, err := strconv.Atoi(strutil.ReadField(data, 2, false, ":"))
uid, err := strconv.Atoi(strutil.ReadField(data, 2, false, ':'))

if err != nil {
return nil, ErrCantParseGetentOutput
}

gid, err := strconv.Atoi(strutil.ReadField(data, 3, false, ":"))
gid, err := strconv.Atoi(strutil.ReadField(data, 3, false, ':'))

if err != nil {
return nil, ErrCantParseGetentOutput
}

return &User{
Name: strutil.ReadField(data, 0, false, ":"),
Name: strutil.ReadField(data, 0, false, ':'),
UID: uid,
GID: gid,
Comment: strutil.ReadField(data, 4, false, ":"),
HomeDir: strutil.ReadField(data, 5, false, ":"),
Shell: strutil.ReadField(data, 6, false, ":"),
RealName: strutil.ReadField(data, 0, false, ":"),
Comment: strutil.ReadField(data, 4, false, ':'),
HomeDir: strutil.ReadField(data, 5, false, ':'),
Shell: strutil.ReadField(data, 6, false, ':'),
RealName: strutil.ReadField(data, 0, false, ':'),
RealUID: uid,
RealGID: gid,
}, nil
}

// parseGetentGroupOutput parse 'getent group' command output
func parseGetentGroupOutput(data string) (*Group, error) {
name := strutil.ReadField(data, 0, false, ":")
id := strutil.ReadField(data, 2, false, ":")
name := strutil.ReadField(data, 0, false, ':')
id := strutil.ReadField(data, 2, false, ':')

if name == "" || id == "" {
return nil, ErrCantParseGetentOutput
Expand Down
4 changes: 2 additions & 2 deletions terminal/tty/tmux_linux.go
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,13 @@ func isTmuxAncestor() (bool, error) {
}

statString := string(statData)
processName := strutil.ReadField(statString, 1, false, " ")
processName := strutil.ReadField(statString, 1, false, ' ')

if strings.HasPrefix(processName, "(tmux:") {
return true, nil
}

parentPID := strutil.ReadField(statString, 3, false, " ")
parentPID := strutil.ReadField(statString, 3, false, ' ')

if parentPID == "1" || parentPID == "0" {
break
Expand Down
4 changes: 2 additions & 2 deletions usage/usage.go
Original file line number Diff line number Diff line change
Expand Up @@ -672,8 +672,8 @@ func formatOptionName(opt *Option, colorTag string) string {
// parseOptionName parses option name
func parseOptionName(name string) (string, string) {
if strings.Contains(name, ":") {
return strutil.ReadField(name, 1, false, ":"),
strutil.ReadField(name, 0, false, ":")
return strutil.ReadField(name, 1, false, ':'),
strutil.ReadField(name, 0, false, ':')
}

return name, ""
Expand Down

0 comments on commit 597b938

Please sign in to comment.