| 1 | package editorconfig |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "errors" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "os" |
| 9 | "strings" |
| 10 | |
| 11 | "gopkg.in/ini.v1" |
| 12 | ) |
| 13 | |
| 14 | const ( |
| 15 | // ConfigNameDefault represents the name of the configuration file. |
| 16 | ConfigNameDefault = ".editorconfig" |
| 17 | // UnsetValue is the value that unsets a preexisting variable. |
| 18 | UnsetValue = "unset" |
| 19 | ) |
| 20 | |
| 21 | // IndentStyle possible values. |
| 22 | const ( |
| 23 | IndentStyleTab = "tab" |
| 24 | IndentStyleSpaces = "space" |
| 25 | ) |
| 26 | |
| 27 | // EndOfLine possible values. |
| 28 | const ( |
| 29 | EndOfLineLf = "lf" |
| 30 | EndOfLineCr = "cr" |
| 31 | EndOfLineCrLf = "crlf" |
| 32 | ) |
| 33 | |
| 34 | // Charset possible values. |
| 35 | const ( |
| 36 | CharsetLatin1 = "latin1" |
| 37 | CharsetUTF8 = "utf-8" |
| 38 | CharsetUTF8BOM = "utf-8-bom" |
| 39 | CharsetUTF16BE = "utf-16be" |
| 40 | CharsetUTF16LE = "utf-16le" |
| 41 | ) |
| 42 | |
| 43 | // Limit for section name. |
| 44 | const ( |
| 45 | MaxSectionLength = 4096 |
| 46 | ) |
| 47 | |
| 48 | // Editorconfig represents a .editorconfig file. |
| 49 | // |
| 50 | // It is composed by a "root" property, plus the definitions defined in the |
| 51 | // file. |
| 52 | type Editorconfig struct { |
| 53 | Root bool |
| 54 | Definitions []*Definition |
| 55 | config *Config |
| 56 | } |
| 57 | |
| 58 | // newEditorconfig builds the configuration from an INI file. |
| 59 | func newEditorconfig(iniFile *ini.File) (*Editorconfig, error, error) { |
| 60 | editorConfig := &Editorconfig{} |
| 61 | |
| 62 | var warning error |
| 63 | |
| 64 | // Consider mixed-case values for true and false. |
| 65 | rootKey := iniFile.Section(ini.DefaultSection).Key("root") |
| 66 | rootKey.SetValue(strings.ToLower(rootKey.Value())) |
| 67 | editorConfig.Root = rootKey.MustBool(false) |
| 68 | |
| 69 | for _, sectionStr := range iniFile.SectionStrings() { |
| 70 | if sectionStr == ini.DefaultSection || len(sectionStr) > MaxSectionLength { |
| 71 | continue |
| 72 | } |
| 73 | |
| 74 | iniSection := iniFile.Section(sectionStr) |
| 75 | definition := &Definition{} |
| 76 | raw := make(map[string]string) |
| 77 | |
| 78 | err := iniSection.MapTo(&definition) |
| 79 | if err != nil { |
| 80 | return editorConfig, nil, fmt.Errorf("error mapping current section: %w", err) |
| 81 | } |
| 82 | |
| 83 | // Shallow copy all the properties |
| 84 | for k, v := range iniSection.KeysHash() { |
| 85 | raw[strings.ToLower(k)] = v |
| 86 | } |
| 87 | |
| 88 | definition.Raw = raw |
| 89 | definition.Selector = sectionStr |
| 90 | |
| 91 | err = definition.normalize() |
| 92 | if err != nil { |
| 93 | // Append those error(s) into the warning |
| 94 | warning = errors.Join(warning, err) |
| 95 | } |
| 96 | |
| 97 | editorConfig.Definitions = append(editorConfig.Definitions, definition) |
| 98 | } |
| 99 | |
| 100 | return editorConfig, warning, nil |
| 101 | } |
| 102 | |
| 103 | // GetDefinitionForFilename returns a definition for the given filename. |
| 104 | // |
| 105 | // The result is a merge of the selectors that matched the file. |
| 106 | // The last section has preference over the priors. |
| 107 | func (e *Editorconfig) GetDefinitionForFilename(name string) (*Definition, error) { |
| 108 | def := &Definition{ |
| 109 | Raw: make(map[string]string), |
| 110 | } |
| 111 | |
| 112 | // The last section has preference over the priors. |
| 113 | for i := len(e.Definitions) - 1; i >= 0; i-- { |
| 114 | actualDef := e.Definitions[i] |
| 115 | selector := actualDef.Selector |
| 116 | |
| 117 | if !strings.HasPrefix(selector, "/") { |
| 118 | if strings.ContainsRune(selector, '/') { |
| 119 | selector = "/" + selector |
| 120 | } else { |
| 121 | selector = "/**/" + selector |
| 122 | } |
| 123 | } |
| 124 | |
| 125 | if !strings.HasPrefix(name, "/") { |
| 126 | name = "/" + name |
| 127 | } |
| 128 | |
| 129 | ok, err := e.FnmatchCase(selector, name) |
| 130 | if err != nil { |
| 131 | return nil, err |
| 132 | } |
| 133 | |
| 134 | if ok { |
| 135 | def.merge(actualDef) |
| 136 | } |
| 137 | } |
| 138 | |
| 139 | return def, nil |
| 140 | } |
| 141 | |
| 142 | // FnmatchCase calls the matcher from the config's parser or the vanilla's. |
| 143 | func (e *Editorconfig) FnmatchCase(selector string, filename string) (bool, error) { |
| 144 | if e.config != nil && e.config.Parser != nil { |
| 145 | ok, err := e.config.Parser.FnmatchCase(selector, filename) |
| 146 | if err != nil { |
| 147 | return ok, fmt.Errorf("filename match failed: %w", err) |
| 148 | } |
| 149 | |
| 150 | return ok, nil |
| 151 | } |
| 152 | |
| 153 | return FnmatchCase(selector, filename) |
| 154 | } |
| 155 | |
| 156 | // Serialize converts the Editorconfig to a slice of bytes, containing the |
| 157 | // content of the file in the INI format. |
| 158 | func (e *Editorconfig) Serialize() ([]byte, error) { |
| 159 | buffer := bytes.NewBuffer(nil) |
| 160 | |
| 161 | err := e.Write(buffer) |
| 162 | if err != nil { |
| 163 | return nil, fmt.Errorf("cannot write into buffer: %w", err) |
| 164 | } |
| 165 | |
| 166 | return buffer.Bytes(), nil |
| 167 | } |
| 168 | |
| 169 | // Write writes the Editorconfig to the Writer in a compatible INI file. |
| 170 | func (e *Editorconfig) Write(w io.Writer) error { |
| 171 | iniFile := ini.Empty() |
| 172 | |
| 173 | iniFile.Section(ini.DefaultSection).Comment = "https://editorconfig.org" |
| 174 | |
| 175 | if e.Root { |
| 176 | iniFile.Section(ini.DefaultSection).Key("root").SetValue(boolToString(e.Root)) |
| 177 | } |
| 178 | |
| 179 | for _, d := range e.Definitions { |
| 180 | d.InsertToIniFile(iniFile) |
| 181 | } |
| 182 | |
| 183 | _, err := iniFile.WriteTo(w) |
| 184 | if err != nil { |
| 185 | return fmt.Errorf("error writing ini file: %w", err) |
| 186 | } |
| 187 | |
| 188 | return nil |
| 189 | } |
| 190 | |
| 191 | // Save saves the Editorconfig to a compatible INI file. |
| 192 | func (e *Editorconfig) Save(filename string) error { |
| 193 | f, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0o644) |
| 194 | if err != nil { |
| 195 | return fmt.Errorf("cannot open file %q: %w", filename, err) |
| 196 | } |
| 197 | |
| 198 | return e.Write(f) |
| 199 | } |
| 200 | |
| 201 | func boolToString(b bool) string { |
| 202 | if b { |
| 203 | return "true" |
| 204 | } |
| 205 | |
| 206 | return "false" |
| 207 | } |
| 208 | |
| 209 | // Parse parses from a reader. |
| 210 | func Parse(r io.Reader) (*Editorconfig, error) { |
| 211 | iniFile, err := ini.Load(r) |
| 212 | if err != nil { |
| 213 | return nil, fmt.Errorf("cannot load ini file: %w", err) |
| 214 | } |
| 215 | |
| 216 | ec, warning, err := newEditorconfig(iniFile) |
| 217 | if warning != nil { |
| 218 | err = errors.Join(warning, err) |
| 219 | } |
| 220 | |
| 221 | return ec, err |
| 222 | } |
| 223 | |
| 224 | // ParseGraceful parses from a reader with warnings not treated as a fatal error. |
| 225 | func ParseGraceful(r io.Reader) (*Editorconfig, error, error) { |
| 226 | iniFile, err := ini.Load(r) |
| 227 | if err != nil { |
| 228 | return &Editorconfig{}, nil, fmt.Errorf("cannot load ini file: %w", err) |
| 229 | } |
| 230 | |
| 231 | return newEditorconfig(iniFile) |
| 232 | } |
| 233 | |
| 234 | // ParseBytes parses from a slice of bytes. |
| 235 | // |
| 236 | // Deprecated: use Parse instead. |
| 237 | func ParseBytes(data []byte) (*Editorconfig, error) { |
| 238 | iniFile, err := ini.Load(data) |
| 239 | if err != nil { |
| 240 | return nil, fmt.Errorf("cannot load ini file: %w", err) |
| 241 | } |
| 242 | |
| 243 | ec, warning, err := newEditorconfig(iniFile) |
| 244 | if warning != nil { |
| 245 | err = errors.Join(warning, err) |
| 246 | } |
| 247 | |
| 248 | return ec, err |
| 249 | } |
| 250 | |
| 251 | // ParseFile parses from a file. |
| 252 | // |
| 253 | // Deprecated: use Parse instead. |
| 254 | func ParseFile(path string) (*Editorconfig, error) { |
| 255 | iniFile, err := ini.Load(path) |
| 256 | if err != nil { |
| 257 | return nil, fmt.Errorf("cannot load ini file: %w", err) |
| 258 | } |
| 259 | |
| 260 | ec, warning, err := newEditorconfig(iniFile) |
| 261 | if warning != nil { |
| 262 | err = errors.Join(warning, err) |
| 263 | } |
| 264 | |
| 265 | return ec, err |
| 266 | } |
| 267 | |
| 268 | // GetDefinitionForFilename given a filename, searches for .editorconfig files, |
| 269 | // starting from the file folder, walking through the previous folders, until |
| 270 | // it reaches a folder with `root = true`, and returns the right editorconfig |
| 271 | // definition for the given file. |
| 272 | func GetDefinitionForFilename(filename string) (*Definition, error) { |
| 273 | config := new(Config) |
| 274 | |
| 275 | return config.Load(filename) |
| 276 | } |
| 277 | |
| 278 | // GetDefinitionForFilenameGraceful given a filename, searches for |
| 279 | // .editorconfig files, starting from the file folder, walking through the |
| 280 | // previous folders, until it reaches a folder with `root = true`, and returns |
| 281 | // the right editorconfig definition for the given file. |
| 282 | // |
| 283 | // In case of non-fatal errors, a joined errors warning is return as well. |
| 284 | func GetDefinitionForFilenameGraceful(filename string) (*Definition, error, error) { |
| 285 | config := new(Config) |
| 286 | |
| 287 | return config.LoadGraceful(filename) |
| 288 | } |
| 289 | |
| 290 | // GetDefinitionForFilenameWithConfigname given a filename and a configname, |
| 291 | // searches for configname files, starting from the file folder, walking |
| 292 | // through the previous folders, until it reaches a folder with `root = true`, |
| 293 | // and returns the right editorconfig definition for the given file. |
| 294 | func GetDefinitionForFilenameWithConfigname(filename string, configname string) (*Definition, error) { |
| 295 | config := &Config{ |
| 296 | Name: configname, |
| 297 | } |
| 298 | |
| 299 | return config.Load(filename) |
| 300 | } |
| 301 | |
| 302 | // GetDefinitionForFilenameWithConfignameGraceful given a filename and a |
| 303 | // configname, searches for configname files, starting from the file folder, |
| 304 | // walking through the previous folders, until it reaches a folder with `root = |
| 305 | // true`, and returns the right editorconfig definition for the given file. |
| 306 | // |
| 307 | // In case of non-fatal errors, a joined errors warning is return as well. |
| 308 | func GetDefinitionForFilenameWithConfignameGraceful(filename string, configname string) (*Definition, error, error) { |
| 309 | config := &Config{ |
| 310 | Name: configname, |
| 311 | } |
| 312 | |
| 313 | return config.LoadGraceful(filename) |
| 314 | } |