editorconfig

package module
v2.6.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 2, 2024 License: MIT Imports: 11 Imported by: 20

README

Build Status Go Reference Go Report Card

Editorconfig Core Go

A Editorconfig file parser and manipulator for Go.

Missing features

Installing

We recommend the use of Go 1.17+ modules for this package. Lower versions, such as 1.13, should be fine.

Import by the same path. The package name you will use to access it is editorconfig.

import "github.com/editorconfig/editorconfig-core-go/v2"

Usage

Parse from a file
fp, err := os.Open("path/to/.editorconfig")
if err != nil {
	log.Fatal(err)
}
defer fp.Close()

editorConfig, err := editorconfig.Parse(fp)
if err != nil {
	log.Fatal(err)
}
Graceful parsing from a file
fp, err := os.Open("path/to/.editorconfig")
if err != nil {
	log.Fatal(err)
}
defer fp.Close()

editorConfig, warning, err := editorconfig.ParseGraceful(fp)
if err != nil {
	log.Fatal(err)
}

// Log the warning(s) encountered while reading the editorconfig file
if warning != nil {
	log.Print(warning)
}
Parse from slice of bytes
data := []byte("...")
editorConfig, err := editorconfig.ParseBytes(data)
if err != nil {
	log.Fatal(err)
}
Get definition to a given filename

This method builds a definition to a given filename. This definition is a merge of the properties with selectors that matched the given filename. The lasts sections of the file have preference over the priors.

def := editorConfig.GetDefinitionForFilename("my/file.go")

This definition have the following properties:

type Definition struct {
	Selector string

	Charset                string
	IndentStyle            string
	IndentSize             string
	TabWidth               int
	EndOfLine              string
	TrimTrailingWhitespace *bool
	InsertFinalNewline     *bool
	Raw                    map[string]string
}
Automatic search for .editorconfig files

If you want a definition of a file without having to manually parse the .editorconfig files, you can then use the static version of GetDefinitionForFilename:

def, err := editorconfig.GetDefinitionForFilename("foo/bar/baz/my-file.go")

In the example above, the package will automatically search for .editorconfig files on:

  • foo/bar/baz/.editorconfig
  • foo/baz/.editorconfig
  • foo/.editorconfig

Until it reaches a file with root = true or the root of the filesystem.

Generating a .editorconfig file

You can easily convert a Editorconfig struct to a compatible INI file:

// serialize to slice of bytes
data, err := editorConfig.Serialize()
if err != nil {
	log.Fatal(err)
}

// save directly to file
err := editorConfig.Save("path/to/.editorconfig")
if err != nil {
	log.Fatal(err)
}

Contributing

To run the tests:

go test -v ./...

To run the integration tests:

make test-core

Documentation

Index

Constants

View Source
const (
	// ConfigNameDefault represents the name of the configuration file.
	ConfigNameDefault = ".editorconfig"
	// UnsetValue is the value that unsets a preexisting variable.
	UnsetValue = "unset"
)
View Source
const (
	IndentStyleTab    = "tab"
	IndentStyleSpaces = "space"
)

IndentStyle possible values.

View Source
const (
	EndOfLineLf   = "lf"
	EndOfLineCr   = "cr"
	EndOfLineCrLf = "crlf"
)

EndOfLine possible values.

View Source
const (
	CharsetLatin1  = "latin1"
	CharsetUTF8    = "utf-8"
	CharsetUTF8BOM = "utf-8-bom"
	CharsetUTF16BE = "utf-16be"
	CharsetUTF16LE = "utf-16le"
)

Charset possible values.

View Source
const (
	MaxSectionLength = 4096
)

Limit for section name.

Variables

View Source
var ErrInvalidVersion = errors.New("invalid semantic version")

ErrInvalidVersion represents a standard error with the semantic version.

Functions

func FnmatchCase added in v2.1.0

func FnmatchCase(pattern, name string) (bool, error)

FnmatchCase tests whether the name matches the given pattern case included.

Types

type CachedParser added in v2.3.0

type CachedParser struct {
	// contains filtered or unexported fields
}

CachedParser implements the Parser interface but caches the definition and the regular expressions.

func NewCachedParser added in v2.3.0

func NewCachedParser() *CachedParser

NewCachedParser initializes the CachedParser.

func (*CachedParser) FnmatchCase added in v2.3.0

func (parser *CachedParser) FnmatchCase(selector string, filename string) (bool, error)

FnmatchCase calls the module's FnmatchCase and caches the parsed selector.

func (*CachedParser) ParseIni added in v2.3.0

func (parser *CachedParser) ParseIni(filename string) (*Editorconfig, error)

ParseIni parses the given filename to a Definition and caches the result.

func (*CachedParser) ParseIniGraceful added in v2.5.0

func (parser *CachedParser) ParseIniGraceful(filename string) (*Editorconfig, error, error)

ParseIniGraceful parses the given filename to a Definition and caches the result.

type Config added in v2.2.1

type Config struct {
	Path     string
	Name     string
	Version  string
	Parser   Parser
	Graceful bool
}

Config holds the configuration.

func (*Config) Load added in v2.3.0

func (config *Config) Load(filename string) (*Definition, error)

Load loads definition of a given file.

func (*Config) LoadGraceful added in v2.5.0

func (config *Config) LoadGraceful(filename string) (*Definition, error, error)

Load loads definition of a given file with warnings and error.

type Definition

type Definition struct {
	Selector string `ini:"-" json:"-"`

	Charset                string            `ini:"charset"      json:"charset,omitempty"`
	IndentStyle            string            `ini:"indent_style" json:"indent_style,omitempty"`
	IndentSize             string            `ini:"indent_size"  json:"indent_size,omitempty"`
	TabWidth               int               `ini:"-"            json:"-"`
	EndOfLine              string            `ini:"end_of_line"  json:"end_of_line,omitempty"`
	TrimTrailingWhitespace *bool             `ini:"-"            json:"-"`
	InsertFinalNewline     *bool             `ini:"-"            json:"-"`
	Raw                    map[string]string `ini:"-"            json:"-"`
	// contains filtered or unexported fields
}

Definition represents a definition inside the .editorconfig file. E.g. a section of the file. The definition is composed of the selector ("*", "*.go", "*.{js.css}", etc), plus the properties of the selected files.

func GetDefinitionForFilename

func GetDefinitionForFilename(filename string) (*Definition, error)

GetDefinitionForFilename given a filename, searches for .editorconfig files, starting from the file folder, walking through the previous folders, until it reaches a folder with `root = true`, and returns the right editorconfig definition for the given file.

func GetDefinitionForFilenameGraceful added in v2.5.1

func GetDefinitionForFilenameGraceful(filename string) (*Definition, error, error)

GetDefinitionForFilenameGraceful given a filename, searches for .editorconfig files, starting from the file folder, walking through the previous folders, until it reaches a folder with `root = true`, and returns the right editorconfig definition for the given file.

In case of non-fatal errors, a joined errors warning is return as well.

func GetDefinitionForFilenameWithConfigname

func GetDefinitionForFilenameWithConfigname(filename string, configname string) (*Definition, error)

GetDefinitionForFilenameWithConfigname given a filename and a configname, searches for configname files, starting from the file folder, walking through the previous folders, until it reaches a folder with `root = true`, and returns the right editorconfig definition for the given file.

func GetDefinitionForFilenameWithConfignameGraceful added in v2.5.0

func GetDefinitionForFilenameWithConfignameGraceful(filename string, configname string) (*Definition, error, error)

GetDefinitionForFilenameWithConfignameGraceful given a filename and a configname, searches for configname files, starting from the file folder, walking through the previous folders, until it reaches a folder with `root = true`, and returns the right editorconfig definition for the given file.

In case of non-fatal errors, a joined errors warning is return as well.

func NewDefinition added in v2.2.1

func NewDefinition(config Config) (*Definition, error)

NewDefinition builds a definition from a given config.

func (*Definition) InsertToIniFile

func (d *Definition) InsertToIniFile(iniFile *ini.File)

InsertToIniFile writes the definition into a ini file.

type Editorconfig

type Editorconfig struct {
	Root        bool
	Definitions []*Definition
	// contains filtered or unexported fields
}

Editorconfig represents a .editorconfig file.

It is composed by a "root" property, plus the definitions defined in the file.

func Parse added in v2.2.0

func Parse(r io.Reader) (*Editorconfig, error)

Parse parses from a reader.

func ParseBytes deprecated

func ParseBytes(data []byte) (*Editorconfig, error)

ParseBytes parses from a slice of bytes.

Deprecated: use Parse instead.

func ParseFile deprecated

func ParseFile(path string) (*Editorconfig, error)

ParseFile parses from a file.

Deprecated: use Parse instead.

func ParseGraceful added in v2.5.0

func ParseGraceful(r io.Reader) (*Editorconfig, error, error)

ParseGraceful parses from a reader with warnings not treated as a fatal error.

func (*Editorconfig) FnmatchCase added in v2.3.0

func (e *Editorconfig) FnmatchCase(selector string, filename string) (bool, error)

FnmatchCase calls the matcher from the config's parser or the vanilla's.

func (*Editorconfig) GetDefinitionForFilename

func (e *Editorconfig) GetDefinitionForFilename(name string) (*Definition, error)

GetDefinitionForFilename returns a definition for the given filename.

The result is a merge of the selectors that matched the file. The last section has preference over the priors.

func (*Editorconfig) Save

func (e *Editorconfig) Save(filename string) error

Save saves the Editorconfig to a compatible INI file.

func (*Editorconfig) Serialize

func (e *Editorconfig) Serialize() ([]byte, error)

Serialize converts the Editorconfig to a slice of bytes, containing the content of the file in the INI format.

func (*Editorconfig) Write added in v2.2.1

func (e *Editorconfig) Write(w io.Writer) error

Write writes the Editorconfig to the Writer in a compatible INI file.

type Parser added in v2.3.0

type Parser interface {
	// ParseIni takes one .editorconfig (ini format) filename and returns its
	// Editorconfig definition.
	ParseIni(filename string) (*Editorconfig, error)

	// ParseIni takes one .editorconfig (ini format) filename and returns its
	// Editorconfig definition. In case of non fatal warnings, they are in
	// a joined errors and might be ignored in some cases.
	ParseIniGraceful(filename string) (*Editorconfig, error, error)

	// FnmatchCase takes a pattern, a filename, and tells wether the given filename
	// matches the globbing pattern.
	FnmatchCase(pattern string, filename string) (bool, error)
}

Parser interface is responsible for the parsing of the ini file and the globbing patterns.

type SimpleParser added in v2.3.0

type SimpleParser struct{}

SimpleParser implements the Parser interface but without doing any caching.

func (*SimpleParser) FnmatchCase added in v2.3.0

func (parser *SimpleParser) FnmatchCase(selector string, filename string) (bool, error)

FnmatchCase calls the module's FnmatchCase.

func (*SimpleParser) ParseIni added in v2.3.0

func (parser *SimpleParser) ParseIni(filename string) (*Editorconfig, error)

ParseInit calls go-ini's Load on the file.

func (*SimpleParser) ParseIniGraceful added in v2.5.0

func (parser *SimpleParser) ParseIniGraceful(filename string) (*Editorconfig, error, error)

ParseIni calls go-ini's Load on the file and keep warnings in a separate error.

Directories

Path Synopsis
cmd
internal
assert
this code is from the examples https://pkg.go.dev/github.com/google/go-cmp/cmp?tab=doc#Reporter
this code is from the examples https://pkg.go.dev/github.com/google/go-cmp/cmp?tab=doc#Reporter

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL