Skip to content

Commit

Permalink
prepare recursive script parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
d-led committed Dec 31, 2023
1 parent 4c48242 commit 0c556ae
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 23 deletions.
40 changes: 17 additions & 23 deletions common/nix_candidate_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,21 @@ import (

g "github.com/zyedidia/generic"
"github.com/zyedidia/generic/hashset"
"mvdan.cc/sh/v3/syntax"
)

type NixCandidateSource struct {
fs Filesystem
sources map[string]*PathSetIn
key string
fs Filesystem
sources map[string]*PathSetIn
expandedPathsAlreadyCrawled map[string]bool
key string
}

func NewNixCandidateSource(fs Filesystem, key string) CandidateSource {
res := &NixCandidateSource{
fs: fs,
sources: map[string]*PathSetIn{},
key: key,
fs: fs,
sources: map[string]*PathSetIn{},
expandedPathsAlreadyCrawled: map[string]bool{},
key: key,
}
res.crawlKnownPaths()
res.crawlPathLists()
Expand All @@ -40,30 +41,23 @@ func (s *NixCandidateSource) WhereSet(somePath string) *PathSetIn {

func (s *NixCandidateSource) crawlKnownPaths() {
ForEachKnownPath(func(originalSource, expandedSource string) {
// try getting the contents
input, err := readAllText(expandedSource)
if err != nil {
if s.expandedPathsAlreadyCrawled[expandedSource] {
return
}
// do not crawl this file again
s.expandedPathsAlreadyCrawled[expandedSource] = true

// parse
r := strings.NewReader(input)
f, err := syntax.NewParser().Parse(r, "")
// try getting the contents
input, err := readAllText(expandedSource)
if err != nil {
return
}

syntax.Walk(f, func(node syntax.Node) bool {
switch x := node.(type) {
case *syntax.Assign:
if s.key == x.Name.Value {
harvestedPaths := s.harvestPaths(input[x.Value.Pos().Offset():x.Value.End().Offset()])
for _, harvestedPath := range harvestedPaths {
s.tryUpdatePathMap(harvestedPath, originalSource, expandedSource)
}
}
ForEachVariableAssignment(s.key, input, func(value string) {
harvestedPaths := s.harvestPaths(value)
for _, harvestedPath := range harvestedPaths {
s.tryUpdatePathMap(harvestedPath, originalSource, expandedSource)
}
return true
})
})
}
Expand Down
27 changes: 27 additions & 0 deletions common/script_parser.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
package common

import (
"strings"

"mvdan.cc/sh/v3/syntax"
)

func ForEachVariableAssignment(key, input string, fn func(string)) {
// parse
r := strings.NewReader(input)
f, err := syntax.NewParser().Parse(r, "")
if err != nil {
return
}

syntax.Walk(f, func(node syntax.Node) bool {
switch x := node.(type) {
case *syntax.Assign:
if key == x.Name.Value {
value := input[x.Value.Pos().Offset():x.Value.End().Offset()]
fn(value)
}
}
return true
})
}

0 comments on commit 0c556ae

Please sign in to comment.