From 23633a432f903599a4ce46c30c4337e413a26ef1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Daniel=20Mart=C3=AD?= Date: Sun, 28 Apr 2024 23:53:21 +0100 Subject: [PATCH] expand: avoid a panic when ParamExp.Repl.Orig is nil Pattern expected the word to never be nil, unlike other APIs such as Literal or Document. Fix that to avoid other similar panics. And when encountering a nil or empty ParamExp.Repl.Orig, do not perform a search and replace, as it would result in every match. Fixes #1076. --- expand/expand.go | 3 +++ expand/param.go | 3 +++ interp/interp_test.go | 1 + 3 files changed, 7 insertions(+) diff --git a/expand/expand.go b/expand/expand.go index 3c4343da..5e52ae05 100644 --- a/expand/expand.go +++ b/expand/expand.go @@ -214,6 +214,9 @@ const patMode = pattern.Filenames | pattern.Braces // The config specifies shell expansion options; nil behaves the same as an // empty config. func Pattern(cfg *Config, word *syntax.Word) (string, error) { + if word == nil { + return "", nil + } cfg = prepareConfig(cfg) field, err := cfg.wordField(word.Parts, quoteNone) if err != nil { diff --git a/expand/param.go b/expand/param.go index f876ef0b..07d3e13b 100644 --- a/expand/param.go +++ b/expand/param.go @@ -206,6 +206,9 @@ func (cfg *Config) paramExp(pe *syntax.ParamExp) (string, error) { if err != nil { return "", err } + if orig == "" { + break // nothing to replace + } with, err := Literal(cfg, pe.Repl.With) if err != nil { return "", err diff --git a/interp/interp_test.go b/interp/interp_test.go index d2312412..11ab2873 100644 --- a/interp/interp_test.go +++ b/interp/interp_test.go @@ -509,6 +509,7 @@ var runTests = []runTest{ {"a='abcx1y'; echo ${a//x[[:digit:]]y}", "abc\n"}, {`a=xyz; echo "${a/y/a b}"`, "xa bz\n"}, {"a='foo_interp_missing/bar_interp_missing'; echo ${a//o*a/}", "fr_interp_missing\n"}, + {"a=foobar; echo ${a//a/} ${a///b} ${a///}", "foobr foobar foobar\n"}, { "echo ${a:-b}; echo $a; a=; echo ${a:-b}; a=c; echo ${a:-b}", "b\n\nb\nc\n",