package main import ( "bytes" "encoding/json" "strings" "sync" "mvdan.cc/sh/v3/syntax" "mvdan.cc/sh/v3/syntax/typedjson" ) // parsedScript is what the comparison needs of a shell script: its parse // tree without positions and literal text, and the text of each heredoc with // every expansion in it written as X. ok is false when it does not parse. type parsedScript struct { ok bool skeleton string heredocs []string } var parsedScripts sync.Map // script text -> *parsedScript // parseScript parses a script as `shfmt -ln bash --to-json` does: bash, // comments kept, the tree in shfmt's typed JSON. func parseScript(script string) *parsedScript { if v, ok := parsedScripts.Load(script); ok { return v.(*parsedScript) } res := &parsedScript{} parser := syntax.NewParser(syntax.KeepComments(true), syntax.Variant(syntax.LangBash)) if f, err := parser.Parse(strings.NewReader(script), ""); err == nil { var buf bytes.Buffer var tree any if typedjson.Encode(&buf, f) == nil && json.Unmarshal(buf.Bytes(), &tree) == nil { if sk, err := json.Marshal(skeleton(tree)); err == nil { res.ok = true res.skeleton = string(sk) res.heredocs = heredocs(f) } } } v, _ := parsedScripts.LoadOrStore(script, res) return v.(*parsedScript) } // skeleton drops every Value and every position from the typed JSON tree, so // two scripts compare equal when only their literal text differs. func skeleton(n any) any { switch x := n.(type) { case map[string]any: out := make(map[string]any, len(x)) for k, v := range x { if k == "Value" || isPos(v) { continue } out[k] = skeleton(v) } return out case []any: out := make([]any, len(x)) for i, v := range x { out[i] = skeleton(v) } return out } return n } func isPos(v any) bool { m, ok := v.(map[string]any) if !ok { return false } _, offset := m["Offset"] _, line := m["Line"] return offset && line } // heredocs is the body of every heredoc, in the order a walk of the tree // meets them, with each part that is not literal text written as X. A heredoc // with an empty body has no word at all. func heredocs(f *syntax.File) []string { var out []string syntax.Walk(f, func(n syntax.Node) bool { r, ok := n.(*syntax.Redirect) if !ok || r.Hdoc == nil { return true } var b strings.Builder for _, p := range r.Hdoc.Parts { if lit, ok := p.(*syntax.Lit); ok { b.WriteString(lit.Value) } else { b.WriteString("X") } } out = append(out, b.String()) return true }) return out }