Skip to content

Commit

Permalink
interp: support read -p flag for prompts
Browse files Browse the repository at this point in the history
I have implemented the "read -p" flag, as requested in issue #551.
Included are new test cases to cover the added feature,
as well as the integration of -p with the existing code that handles read.
All test cases old and new are passing.
  • Loading branch information
parkerduckworth authored Aug 26, 2021
1 parent 1a7878d commit ec61336
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
11 changes: 11 additions & 0 deletions interp/builtin.go
Original file line number Diff line number Diff line change
Expand Up @@ -518,12 +518,19 @@ func (r *Runner) builtinCode(ctx context.Context, pos syntax.Pos, name string, a
}
r.setErr(returnStatus(code))
case "read":
var prompt string
raw := false
fp := flagParser{remaining: args}
for fp.more() {
switch flag := fp.flag(); flag {
case "-r":
raw = true
case "-p":
prompt = fp.value()
if prompt == "" {
r.errf("read: -p: option requires an argument\n")
return 2
}
default:
r.errf("read: invalid option %q\n", flag)
return 2
Expand All @@ -538,6 +545,10 @@ func (r *Runner) builtinCode(ctx context.Context, pos syntax.Pos, name string, a
}
}

if prompt != "" {
r.out(prompt)
}

line, err := r.readLine(raw)
if err != nil {
return 1
Expand Down
16 changes: 16 additions & 0 deletions interp/interp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2587,6 +2587,22 @@ set +o pipefail
"IFS=: read a b c <<< '1\\:2:3'; echo \"$a\"; echo $b; echo $c",
"1:2\n3\n\n",
},
{
"read -p",
"read: -p: option requires an argument\nexit status 2 #JUSTERR",
},
{
"read -X -p",
"read: invalid option \"-X\"\nexit status 2 #JUSTERR",
},
{
"read -p 'Display me as a prompt. Continue? (y/n) ' choice <<< 'y'; echo $choice",
"Display me as a prompt. Continue? (y/n) y\n",
},
{
"read -r -p 'Prompt and raw flag together: ' a <<< '\\a\\b\\c'; echo $a",
"Prompt and raw flag together: \\a\\b\\c\n",
},

// getopts
{
Expand Down

0 comments on commit ec61336

Please sign in to comment.