Skip to content

Commit

Permalink
Fix bug with ${x/#/replace} caught by wild tests.
Browse files Browse the repository at this point in the history
Also, fix a bug in the prior OSH implementation.  The negative index
was wrong in the case of an empty pattern.
  • Loading branch information
Andy Chu committed Aug 25, 2018
1 parent 695c859 commit 2c205f0
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 9 deletions.
9 changes: 5 additions & 4 deletions core/libstr.py
Expand Up @@ -274,21 +274,22 @@ def Replace(self, s, op):
class _ConstStringReplacer(_Replacer):
def __init__(self, pat, replace_str):
self.pat = pat
self.pat_len = len(pat)
self.replace_str = replace_str

def Replace(self, s, op):
if op.do_all:
return s.replace(self.pat, self.replace_str)
elif op.do_prefix:
if s.startswith(self.pat):
n = len(self.pat)
return self.replace_str + s[n:]
return self.replace_str + s[self.pat_len:]
else:
return s
elif op.do_suffix:
if s.endswith(self.pat):
n = len(self.pat)
return s[:-n] + self.replace_str
# NOTE: This handles ${s/#/foo}. See spec test in var-op-strip.
i = len(s) - self.pat_len
return s[:i] + self.replace_str
else:
return s
else:
Expand Down
6 changes: 2 additions & 4 deletions osh/word_parse.py
Expand Up @@ -232,10 +232,8 @@ def _ReadPatSubVarOp(self, lex_mode):
do_suffix = True
pat.parts.pop(0)

if len(pat.parts) == 0:
# TODO: Print the modifier better.
p_die('Pattern in ${x/pat/replace} must not be empty (got modifier %s)',
first_part, token=self.cur_token)
# NOTE: If there is a modifier, the pattern can be empty, e.g.
# ${s/#/foo} and ${a/%/foo}.

if self.token_type == Id.Right_VarSub:
# e.g. ${v/a} is the same as ${v/a/} -- empty replacement string
Expand Down
22 changes: 21 additions & 1 deletion spec/var-op-strip.test.sh
Expand Up @@ -85,5 +85,25 @@ argv.py "${s%%abcde}" "${s%abcde}" "${s#abcde}" "${s##abcde}"
['abcd', 'abcd', 'abcd', 'abcd']
## END

#### Prepend using replacement of #
# This case was found in Kubernetes and others
array=(aa bb '')
argv.py ${array[@]/#/prefix-}
## STDOUT:
['prefix-aa', 'prefix-bb', 'prefix-']
## END
## N-I dash status: 2
## N-I dash stdout-json: ""
## N-I mksh status: 1
## N-I mksh stdout-json: ""


#### Append using replacement of %
array=(aa bb '')
argv.py ${array[@]/%/-suffix}
## STDOUT:
['aa-suffix', 'bb-suffix', '-suffix']
## END
## N-I dash status: 2
## N-I dash stdout-json: ""
## N-I mksh status: 1
## N-I mksh stdout-json: ""
4 changes: 4 additions & 0 deletions test/parse-errors.sh
Expand Up @@ -130,6 +130,10 @@ arith-expr() {
_error-case '$(( ` ))'

_error-case '$(( $ ))'

# "Can't assign to None" is misleading.
# From wild/src/distro/portage/bin/helper-functions.sh
_error-case '$(( ${var} = fd ))'
}

bool-expr() {
Expand Down

0 comments on commit 2c205f0

Please sign in to comment.