github.com/tilt-dev/wat@v0.0.2-0.20180626175338-9349b638e250/os/ospath/matcher.go (about) 1 // Helpers for matching file paths. 2 package ospath 3 4 import ( 5 "encoding/json" 6 "strings" 7 8 "github.com/windmilleng/wat/data/pathutil" 9 ) 10 11 type Matcher struct { 12 pathutil.Matcher 13 } 14 15 func (m *Matcher) SubdirOS(path string) *Matcher { 16 return &Matcher{Matcher: m.Matcher.Subdir(path)} 17 } 18 19 func (m *Matcher) ChildOS(path string) *Matcher { 20 return &Matcher{Matcher: m.Matcher.Child(path)} 21 } 22 23 func (m *Matcher) Subdir(path string) pathutil.Matcher { 24 return m.SubdirOS(path) 25 } 26 27 func (m *Matcher) Child(path string) pathutil.Matcher { 28 return m.ChildOS(path) 29 } 30 31 func (m *Matcher) MarshalJSON() ([]byte, error) { 32 patterns := m.Matcher.ToPatterns() 33 return json.Marshal(patterns) 34 } 35 36 func (m *Matcher) UnmarshalJSON(b []byte) error { 37 var patterns []string 38 err := json.Unmarshal(b, &patterns) 39 if err != nil { 40 return err 41 } 42 43 newM, err := NewMatcherFromPatterns(patterns) 44 if err != nil { 45 return err 46 } 47 m.Matcher = newM.Matcher 48 return nil 49 } 50 51 // Matches nothing. 52 func NewEmptyMatcher() *Matcher { 53 return &Matcher{Matcher: pathutil.NewEmptyMatcher()} 54 } 55 56 // Matches everything 57 func NewAllMatcher() *Matcher { 58 return &Matcher{Matcher: pathutil.NewAllMatcher()} 59 } 60 61 func InvertMatcher(m *Matcher) (*Matcher, error) { 62 inner, err := pathutil.InvertMatcher(m.Matcher) 63 if err != nil { 64 return &Matcher{}, err 65 } 66 return &Matcher{Matcher: inner}, nil 67 } 68 69 // Matches a single file only 70 func NewFileMatcher(file string) (*Matcher, error) { 71 m, err := pathutil.NewFileMatcher(theOsPathUtil, file) 72 return &Matcher{Matcher: m}, err 73 } 74 75 func NewMatcherFromPattern(pattern string) (*Matcher, error) { 76 m, err := pathutil.NewMatcherFromPattern(theOsPathUtil, pattern) 77 return &Matcher{Matcher: m}, err 78 } 79 80 func NewMatcherFromPatterns(patterns []string) (*Matcher, error) { 81 m, err := pathutil.NewMatcherFromPatterns(theOsPathUtil, patterns) 82 return &Matcher{Matcher: m}, err 83 } 84 85 func (m *Matcher) String() string { 86 return strings.Join(m.ToPatterns(), ",") 87 } 88 89 func MatchersEqual(a, b *Matcher) bool { 90 return pathutil.MatchersEqual(a.Matcher, b.Matcher) 91 }