Skip to content

Commit

Permalink
expand,interp: trim whitespace in atoi
Browse files Browse the repository at this point in the history
Fixes #928.
  • Loading branch information
mvdan committed Oct 23, 2022
1 parent 6ba49e2 commit 6e31936
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 4 deletions.
5 changes: 3 additions & 2 deletions expand/arith.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ package expand
import (
"fmt"
"strconv"
"strings"

"mvdan.cc/sh/v3/syntax"
)
Expand Down Expand Up @@ -105,9 +106,9 @@ func oneIf(b bool) int {
return 0
}

// atoi is just a shorthand for strconv.Atoi that ignores the error,
// just like shells do.
// atoi is like strconv.Atoi, but it ignores errors and trims whitespace.
func atoi(s string) int {
s = strings.TrimSpace(s)
n, _ := strconv.Atoi(s)
return n
}
Expand Down
6 changes: 4 additions & 2 deletions interp/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,18 @@ func isBuiltin(name string) bool {
return false
}

// TODO: oneIf and atoi are duplicated in the expand package.

func oneIf(b bool) int {
if b {
return 1
}
return 0
}

// atoi is just a shorthand for strconv.Atoi that ignores the error,
// just like shells do.
// atoi is like strconv.Atoi, but it ignores errors and trims whitespace.
func atoi(s string) int {
s = strings.TrimSpace(s)
n, _ := strconv.Atoi(s)
return n
}
Expand Down
13 changes: 13 additions & 0 deletions interp/interp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1412,6 +1412,10 @@ var runTests = []runTest{
"[[ 3 -lt 4 ]]",
"",
},
{
"[[ ' 3' -lt '4 ' ]]",
"",
},
{
"[[ 3 -gt 4 ]]",
"exit status 1",
Expand Down Expand Up @@ -1637,6 +1641,7 @@ var runTests = []runTest{
{"[ 0 -gt 1 -o 1 -gt 0 ]", ""},
{"[ 3 -gt 4 ]", "exit status 1"},
{"[ 3 -lt 4 ]", ""},
{"[ ' 3' -lt '4 ' ]", ""},
{
"[ -e a ] && echo x; >a; [ -e a ] && echo y",
"y\n",
Expand Down Expand Up @@ -1826,6 +1831,14 @@ var runTests = []runTest{
"let x=3; let 3%0; ((3%0)); echo $((x%y)); let x%=0",
"division by zero\ndivision by zero\ndivision by zero\ndivision by zero\nexit status 1 #JUSTERR",
},
{
"let x=' 3'; echo $x",
"3\n",
},
{
"x=' 3'; let x++; echo \"$x\"",
"4\n",
},

// set/shift
{
Expand Down

0 comments on commit 6e31936

Please sign in to comment.