Skip to content

Commit

Permalink
refactor color parsing and environ loader using strings.Cut
Browse files Browse the repository at this point in the history
  • Loading branch information
itchyny committed Oct 28, 2024
1 parent b144489 commit 9de339f
Show file tree
Hide file tree
Showing 3 changed files with 9 additions and 22 deletions.
19 changes: 4 additions & 15 deletions cli/color.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,32 +41,21 @@ func validColor(x string) bool {
return false
}
}
return num || x == ""
return num
}

func setColors(colors string) error {
var i int
var color string
for _, target := range []*[]byte{
&nullColor, &falseColor, &trueColor, &numberColor,
&stringColor, &objectKeyColor, &arrayColor, &objectColor,
} {
if i < len(colors) {
if j := strings.IndexByte(colors[i:], ':'); j >= 0 {
color = colors[i : i+j]
i += j + 1
} else {
color = colors[i:]
i = len(colors)
}
color, colors, _ = strings.Cut(colors, ":")
if color != "" {
if !validColor(color) {
return fmt.Errorf("invalid color: %q", color)
}
if color == "" {
*target = nil
} else {
*target = newColor(color)
}
*target = newColor(color)
} else {
*target = nil
}
Expand Down
8 changes: 3 additions & 5 deletions cli/error.go
Original file line number Diff line number Diff line change
Expand Up @@ -125,13 +125,11 @@ func (err *yamlParseError) Error() string {
msg := strings.TrimPrefix(
strings.TrimPrefix(err.err.Error(), "yaml: "),
"unmarshal errors:\n ")
if fmt.Sscanf(msg, "line %d: ", &line); line == 0 {
if _, e := fmt.Sscanf(msg, "line %d: ", &line); e != nil {
return "invalid yaml: " + err.fname
}
msg = msg[strings.Index(msg, ": ")+2:]
if i := strings.IndexByte(msg, '\n'); i >= 0 {
msg = msg[:i]
}
_, msg, _ = strings.Cut(msg, ": ")
msg, _, _ = strings.Cut(msg, "\n")
linestr := getLineByLine(err.contents, line)
return fmt.Sprintf("invalid yaml: %s:%d\n%s %s",
err.fname, line, formatLineInfo(linestr, line, 0), msg)
Expand Down
4 changes: 2 additions & 2 deletions compiler.go
Original file line number Diff line number Diff line change
Expand Up @@ -913,8 +913,8 @@ func (c *compiler) compileFunc(e *Func) error {
env := make(map[string]any)
if c.environLoader != nil {
for _, kv := range c.environLoader() {
if i := strings.IndexByte(kv, '='); i > 0 {
env[kv[:i]] = kv[i+1:]
if k, v, ok := strings.Cut(kv, "="); ok && k != "" {
env[k] = v
}
}
}
Expand Down

0 comments on commit 9de339f

Please sign in to comment.