Debian Codegraph @

cached_parser.go

raw
1 package editorconfig
2
3 import (
4 "errors"
5 "fmt"
6 "os"
7 "regexp"
8
9 "gopkg.in/ini.v1"
10 )
11
12 // CachedParser implements the Parser interface but caches the definition and
13 // the regular expressions.
14 type CachedParser struct {
15 editorconfigs map[string]*Editorconfig
16 regexps map[string]*regexp.Regexp
17 }
18
19 // NewCachedParser initializes the CachedParser.
20 func NewCachedParser() *CachedParser {
21 return &CachedParser{
22 editorconfigs: make(map[string]*Editorconfig),
23 regexps: make(map[string]*regexp.Regexp),
24 }
25 }
26
27 // ParseIni parses the given filename to a Definition and caches the result.
28 func (parser *CachedParser) ParseIni(filename string) (*Editorconfig, error) {
29 ec, warning, err := parser.ParseIniGraceful(filename)
30 if err != nil {
31 return nil, err
32 }
33
34 return ec, warning
35 }
36
37 // ParseIniGraceful parses the given filename to a Definition and caches the result.
38 func (parser *CachedParser) ParseIniGraceful(filename string) (*Editorconfig, error, error) {
39 var warning error
40
41 empty := (*Editorconfig)(nil)
42
43 ec, ok := parser.editorconfigs[filename]
44 if !ok {
45 fp, err := os.Open(filename)
46 if err != nil {
47 return empty, nil, fmt.Errorf("error opening %q: %w", filename, err)
48 }
49
50 defer fp.Close()
51
52 iniFile, err := ini.Load(fp)
53 if err != nil {
54 return empty, nil, fmt.Errorf("error loading ini file %q: %w", filename, err)
55 }
56
57 var warn error
58
59 ec, warn, err = newEditorconfig(iniFile)
60 if err != nil {
61 return empty, nil, fmt.Errorf("error creating config: %w", err)
62 }
63
64 if warn != nil {
65 warning = errors.Join(warning, warn)
66 }
67
68 parser.editorconfigs[filename] = ec
69 }
70
71 return ec, warning, nil
72 }
73
74 // FnmatchCase calls the module's FnmatchCase and caches the parsed selector.
75 func (parser *CachedParser) FnmatchCase(selector string, filename string) (bool, error) {
76 r, ok := parser.regexps[selector]
77 if !ok {
78 p := translate(selector)
79
80 var err error
81
82 r, err = regexp.Compile(fmt.Sprintf("^%s$", p))
83 if err != nil {
84 return false, fmt.Errorf("error compiling selector %q: %w", selector, err)
85 }
86
87 parser.regexps[selector] = r
88 }
89
90 return r.MatchString(filename), nil
91 }