Created
October 29, 2018 15:12
-
-
Save myitcv/834084e4a606a95a09afd4ab7304a21c to your computer and use it in GitHub Desktop.
First cut of solution for https://github.com/myitcv/x/issues/83
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"fmt" | |
"os" | |
"strings" | |
"mvdan.cc/sh/syntax" | |
) | |
type slModifier func(*syntax.StmtList) error | |
func main() { | |
sete := func(sl *syntax.StmtList) error { | |
if sl.Stmts == nil { | |
return nil | |
} | |
sete := &syntax.Stmt{ | |
Cmd: &syntax.CallExpr{ | |
Args: []*syntax.Word{ | |
&syntax.Word{Parts: []syntax.WordPart{&syntax.Lit{Value: "set"}}}, | |
&syntax.Word{Parts: []syntax.WordPart{&syntax.Lit{Value: "-euo"}}}, | |
&syntax.Word{Parts: []syntax.WordPart{&syntax.Lit{Value: "pipefail"}}}, | |
}, | |
}, | |
} | |
sl.Stmts = append([]*syntax.Stmt{sete}, sl.Stmts...) | |
return nil | |
} | |
{ | |
r := strings.NewReader("x=$(ls); (ls)") | |
f, err := syntax.NewParser().Parse(r, "") | |
if err != nil { | |
panic(err) | |
} | |
fmt.Println("Before:") | |
syntax.NewPrinter().Print(os.Stdout, f) | |
syntax.Walk(f, func(n syntax.Node) bool { | |
var f slModifier | |
var sl *syntax.StmtList | |
switch n := n.(type) { | |
case *syntax.CmdSubst: | |
f = sete | |
sl = &n.StmtList | |
case *syntax.Subshell: | |
f = sete | |
sl = &n.StmtList | |
default: | |
return true | |
} | |
if err := f(sl); err != nil { | |
panic(err) | |
} | |
return true | |
}) | |
fmt.Println() | |
fmt.Println("After:") | |
syntax.NewPrinter().Print(os.Stdout, f) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment