Skip to content

Commit

Permalink
syntax: allow redirects before all arguments
Browse files Browse the repository at this point in the history
Fixes #942.
  • Loading branch information
MaienM authored Aug 23, 2023
1 parent 1cb2396 commit 6fe8d00
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 21 deletions.
48 changes: 28 additions & 20 deletions syntax/printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -1058,36 +1058,44 @@ func (p *Printer) stmt(s *Stmt) {
p.decLevel()
}

func (p *Printer) printRedirsUntil(redirs []*Redirect, startRedirs int, pos Pos) int {
for _, r := range redirs[startRedirs:] {
if r.Pos().After(pos) || r.Op == Hdoc || r.Op == DashHdoc {
break
}
if p.wantSpace == spaceRequired {
p.spacePad(r.Pos())
}
if r.N != nil {
p.writeLit(r.N.Value)
}
p.WriteString(r.Op.String())
if p.spaceRedirects && (r.Op != DplIn && r.Op != DplOut) {
p.space()
} else {
p.wantSpace = spaceRequired
}
p.word(r.Word)
startRedirs++
}
return startRedirs
}

func (p *Printer) command(cmd Command, redirs []*Redirect) (startRedirs int) {
p.advanceLine(cmd.Pos().Line())
p.spacePad(cmd.Pos())
switch x := cmd.(type) {
case *CallExpr:
p.assigns(x.Assigns)
if len(x.Args) > 0 {
startRedirs = p.printRedirsUntil(redirs, startRedirs, x.Args[0].Pos())
}
if len(x.Args) <= 1 {
p.wordJoin(x.Args)
return 0
return startRedirs
}
p.wordJoin(x.Args[:1])
for _, r := range redirs {
if r.Pos().After(x.Args[1].Pos()) || r.Op == Hdoc || r.Op == DashHdoc {
break
}
if p.wantSpace == spaceRequired {
p.spacePad(r.Pos())
}
if r.N != nil {
p.writeLit(r.N.Value)
}
p.WriteString(r.Op.String())
if p.spaceRedirects && (r.Op != DplIn && r.Op != DplOut) {
p.space()
} else {
p.wantSpace = spaceRequired
}
p.word(r.Word)
startRedirs++
}
startRedirs = p.printRedirsUntil(redirs, startRedirs, x.Args[1].Pos())
p.wordJoin(x.Args[1:])
case *Block:
p.WriteByte('{')
Expand Down
5 changes: 4 additions & 1 deletion syntax/printer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,9 @@ var printTests = []printCase{
{"if a; then b\nelse c\nfi", "if a; then\n\tb\nelse\n\tc\nfi"},
samePrint("foo >&2 <f bar"),
samePrint("foo >&2 bar <f"),
samePrint(">&2 foo bar <f"),
samePrint(">&2 foo"),
samePrint(">&2 foo 2>&1 bar <f"),
{"foo >&2>/dev/null", "foo >&2 >/dev/null"},
{"foo <<EOF bar\nl1\nEOF", "foo bar <<EOF\nl1\nEOF"},
samePrint("foo <<\\\\\\\\EOF\nbar\n\\\\EOF"),
Expand Down Expand Up @@ -620,7 +623,7 @@ var printTests = []printCase{
samePrint("#comment\n>redir"),
{
">redir \\\n\tfoo",
"foo >redir",
">redir foo",
},
samePrint("$(declare)"),
{
Expand Down

0 comments on commit 6fe8d00

Please sign in to comment.