EditorConfig Core written in Go

Build Status GoDoc Go Report Card

Editorconfig Core Go

A Editorconfig file parser and manipulator for Go.

Missing features

Installing

We recommend the use of Go 1.13+ modules for this package.

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 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)
}

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
Comments
  • What is the status of this project?

    What is the status of this project?

    Hey, I'm using your project right now in one of mine: https://github.com/editorconfig-checker/editorconfig-checker.go

    But as I get more and more to a state where I could release an MVP-release I'm asking myself what the status of editorconfig-core-go is right now. I would love to cooperate and use the official implementation to retrieve rules for specific files, but as it seems more like a work in progress state I'm not sure if I could take the responsibility to use it in my project especially when you are making changes to this repository later on.

    So my concrete question is: is it a readily usable state which needs some minor adjustments or do you plan to do more refactorings, API changes or so on? Would you suggest to use it in a 'real-world-program'?

    Thanks in advance!

  • make the API more idiomatic

    make the API more idiomatic

    1. I see many GetFoo functions. The Get should be removed entirely; editorconfig.DefinitionForFilename is already clear enough.

    2. The Serialize and Save APIs could both be replaced by a single WriterTo method; see https://golang.org/pkg/io/#WriterTo. Not only is this simpler, but it's also more powerful - it supports streaming data, writing to more than just files on disk, etc.

    3. ParseBytes(data []byte) should be replaced with Parse(r io.Reader). ParseFile could be removed too.

    In a way, it seems like this API is ported from another language with no readers and writers, hence all the []byte and reading/writing directly to disk.

    I realise this package is a v2, so these probably can't change for now. But I think that if a v3 ever happens, the API could be made much nicer, and these are some ideas for it :)

  • backport and release new version

    backport and release new version

    The current release that Go modules respect, in the v1 series, is v1.3.0, this contains a bug that was fixed in #14. Unfortunately, you also migrated to /v2/, thus no module customers on the v1 series can consume this fix. The backport and new release would be appreciated.

  • using GetDefinitionForFilename incrementally

    using GetDefinitionForFilename incrementally

    Thanks for this library! I'm looking at using it to implement https://github.com/mvdan/sh/issues/393.

    Here's one problem, though. When one runs a command like shfmt -l -w ., it searches all shell files under the current directory, similar to what gofmt would do.

    Imagine a fairly simple use case, where we have a few hundred shell files and an .editorconfig in the current directory. As I read the source for GetDefinitionForFilename, I'm a bit horrified, as using it for each of the shell script paths would result in the library re-reading and re-parsing the editorconfig hundreds of times.

    I think the library should expose a stateful, incremental API. Keeping data in a struct, and using methods, it could cache:

    • which directories are known to contain (or not contain) an editorconfig
    • editorconfig files that have already been parsed

    For my sample use case above, this would mean only parsing the editorconfig once, and also only one stat call per directory containing a shell script.

    For the sake of simplicity, merging of editorconfig files doesn't need to be cached.

  • Unset support

    Unset support

    Passing more tests don't mean that the features are correct, but it's a starting point.

    before

    100% tests passed, 0 tests failed out of 172
    

    now

    100% tests passed, 0 tests failed out of 179
    
  • cached loader and some refactoring

    cached loader and some refactoring

    This addresses the closed issue #30.

    Now on https://github.com/dotnet/roslyn

    $ time editorconfig $(git ls-files)
    
    real    0m8.061s
    user    0m8.973s
    sys     0m0.470s
    

    This branch

    $ time editorconfig $(git ls-files)
    
    real    0m3.426s
    user    0m3.777s
    sys     0m0.224s
    

    It didn't change any of the API and should be backward compatible.

    Usage in the wild, https://gitlab.com/greut/eclint/merge_requests/38

  • fnmatch: rewrite

    fnmatch: rewrite

    • the fnmatch is somewhat stolen from editorconfig-core-py
    • core-test is bumped to v0.13
    • 15 tests are still breaking (any help is welcome)
    92% tests passed, 15 tests failed out of 193
    
    Total Test time (real) =   0.55 sec
    
    The following tests FAILED:
            120 - tab_width_default_ML (Failed)
            122 - indent_size_default_ML (Failed)
            125 - indent_size_default_with_tab_width_ML (Failed)
            126 - lowercase_values1_ML (Failed)
            127 - lowercase_values2_ML (Failed)
            129 - lowercase_names (Failed)
            148 - comments_after_section (Failed)
            155 - octothorpe_comments_after_section (Failed)
            158 - octothorpe_in_property (Failed)
            159 - escaped_octothorpe_in_property (Failed)
            163 - max_property_name (Failed)
            164 - max_property_value (Failed)
            166 - max_section_name_ignore (Failed)
            173 - root_file_mixed_case (Failed)
            186 - unset_indent_size_ML (Failed)
    
  • use go modules

    use go modules

    Jumping over to go modules, let's depreciate the gopkg.in way of fetching dependencies.

    • [x] https://github.com/stretchr/testify/issues/745
    • [x] adapt the readme
  • Cant read `trim_trailing_whitespace` correctly

    Cant read `trim_trailing_whitespace` correctly

    Hey,

    I have something like this code:

    editorconfig, _ := editorconfig.GetDefinitionForFilename(file)
    if strings.HasSuffix(file, "README.md") {
    	fmt.Println(editorconfig)
    	fmt.Println(editorconfig.TrimTrailingWhitespace)
    }
    

    The output is:

    &{ utf-8 space 4 4 lf true true map[charset:utf-8 trim_trailing_whitespace:false insert_final_newline:true indent_style:space indent_size:4 end_of_line:lf]}
    true
    

    I don't get it - the first line let me believe that trim_trailing_whitespace is set to false (and it is indeed written like that in my .editorconfig) but the second line says that trim_trailing_whitespace is set to true.

    What do I do wrong?

    In case you need the live-code, it can be found here: https://github.com/editorconfig-checker/editorconfig-checker.go/blob/whatsHappening/src/main.go#L206

    My .editorconfig looks like this:

    [*]
    charset = utf-8
    insert_final_newline = true
    trim_trailing_whitespace = true
    indent_style = space
    indent_size = 4
    end_of_line = lf
    
    [*.md]
    trim_trailing_whitespace = false
    
    [*.go]
    indent_style = tab
    
    [Makefile]
    indent_style = tab
    

    and I'm checking my README.md file.

  • Installing doesn't seem to work

    Installing doesn't seem to work

    Hey, I wanted to make a small PR but I don't get it to work.

    What I did:

    go get -u github.com/editorconfig/editorconfig-core-go && \
    go get go get -u gopkg.in/editorconfig/editorconfig-core-go.v1 && \
    cd ~/go/github.com/editorconfig/editorconfig-core-go && \
    make submodule && \
    make installdeps
    

    While executing make installdeps I get the following error:

    $ make installdeps
    go get -t ./...
    # github.com/editorconfig/editorconfig-core-go/cmd/editorconfig
    cmd/editorconfig/main.go:26:35: undefined: editorconfig.ConfigNameDefault
    cmd/editorconfig/main.go:49:15: undefined: editorconfig.GetDefinitionForFilenameWithConfigname
    make: *** [Makefile:12: installdeps] Error 2 
    

    Is this already known? How can I fix this? Or is it something with my specific setup/usage?

    Thanks in advance for your help!

  • build(deps): bump golang.org/x/mod from 0.5.0 to 0.5.1

    build(deps): bump golang.org/x/mod from 0.5.0 to 0.5.1

    Bumps golang.org/x/mod from 0.5.0 to 0.5.1.

    Commits
    • 49f84bc [release-branch.go1.17] modfile: in SetRequireSeparateIndirect, convert lines...
    • 57376c6 [release-branch.go1.17] modfile: in SetRequireSeparateIndirect, arrange requi...
    • See full diff in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
  • Parsing of spaces isn't working correctly

    Parsing of spaces isn't working correctly

    As mentioned here https://github.com/editorconfig-checker/editorconfig-checker/issues/198 the parsing of spaces in editor config files isn't parsed correctly

  • LRU cache

    LRU cache

    This change adds a new LRU cached parser. Usually useless because most projects have few globbing patterns and even fewer .editorconfig files, so it's not enabled by default.

    To make this more "reusable", they have been moved to a sub package, hence the internal calls had to be made public. Now, you can have you own cache without having to rewrite the translate function (which is the hard part)

  • max_line_length support

    max_line_length support

    Would it make sense to have a MaxLineLength int property where any off value would be translated to a 0.

    https://github.com/editorconfig/editorconfig/wiki/EditorConfig-Properties#max_line_length

pdfcpu is a PDF processor written in Go.
pdfcpu is a PDF processor written in Go.

pdfcpu is a PDF processing library written in Go supporting encryption. It provides both an API and a CLI. Supported are all versions up to PDF 1.7 (ISO-32000).

Jan 4, 2023
A CLI markdown converter written in Go.

MDConv is a markdown converter written in Go. It is able to create PDF and HTML files from Markdown without using LaTeX. Instead MDConv u

Dec 20, 2022
A markdown parser written in Go. Easy to extend, standard(CommonMark) compliant, well structured.

goldmark A Markdown parser written in Go. Easy to extend, standards-compliant, well-structured. goldmark is compliant with CommonMark 0.29. Motivation

Dec 29, 2022
a simple and lightweight terminal text editor written in Go

Simple Text editor written in Golang build go build main.go

Oct 4, 2021
Example Book Report API written in Golang with Fiber and GORM

book-report Example Book Report API written in Golang with Fiber and GORM API func setupRoutes(app *fiber.App) { app.Get("/api/v1/book", book.GetBook

Nov 5, 2021
Simple Markdown-Driven Scaffolding tool written by Go
Simple Markdown-Driven Scaffolding tool written by Go

Manaita Simple Markdown-Driven Scaffolding tool written by Go Write your scaffolding code on SCAFFOLD.md and generate files using the scaffold. Scaffo

Jun 25, 2022
Slack bot core/framework written in Go with support for reactions to message updates/deletes
Slack bot core/framework written in Go with support for reactions to message updates/deletes

Overview Requirements Features Demo The Name Concepts Create Your Own Slackscot Assembling the Parts and Bringing Your slackscot to Life Configuration

Oct 28, 2022
Parallel implementation of Gzip for modern multi-core machines written in Go

gzip Parallel implementation of gzip for modern multi-core machines written in Go Usage: gzip [OPTION]... [FILE] Compress or uncompress FILE (by defau

Nov 16, 2021
zlib compression tool for modern multi-core machines written in Go

zlib compression tool for modern multi-core machines written in Go

Jan 21, 2022
⟁ Tendermint Core (BFT Consensus) in Go
⟁ Tendermint Core (BFT Consensus) in Go

Tendermint Byzantine-Fault Tolerant State Machines. Or Blockchain, for short. Branch Tests Coverage Linting master Tendermint Core is Byzantine Fault

Dec 26, 2022
A Go client for Google IoT Core

IoT A simple framework for implementing a Google IoT device. This package makes use of the context package to handle request cancelation, timeouts, an

Sep 26, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Jan 5, 2023
Eudore is the core of a golang lightweight web framework.

Eudore eudore是一个golang轻量级web框架核心,可以轻松扩展成一个技术栈专用框架,具有完整框架设计体系。 反馈和交流请加群组:QQ群373278915。 Features 易扩展:主要设计目标、核心全部解耦,接口即为逻辑。 简单:对象语义明确,框架代码量少复杂度低,无依赖库。 易用

Nov 7, 2022
Package git provides an incomplete pure Go implementation of Git core methods.

git Package git provides an incomplete pure Go implementation of Git core methods. Example Code: store := git.TempStore() defer os.RemoveAll(string(st

Oct 6, 2022
⟁ Tendermint Core (BFT Consensus) in Go
⟁ Tendermint Core (BFT Consensus) in Go

Tendermint Byzantine-Fault Tolerant State Machines. Or Blockchain, for short. Branch Tests Coverage Linting master Tendermint Core is Byzantine Fault

Dec 31, 2022
Eudore is the core of a golang lightweight web framework.

Eudore eudore是一个golang轻量级web框架核心,可以轻松扩展成一个技术栈专用框架,具有完整框架设计体系。 反馈和交流请加群组:QQ群373278915。 Features 易扩展:主要设计目标、核心全部解耦,接口即为逻辑。 简单:对象语义明确,框架代码量少复杂度低,无依赖库。 易用

Nov 7, 2022
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.
Flamingo Framework and Core Library. Flamingo is a go based framework for pluggable web projects. It is used to build scalable and maintainable (web)applications.

Flamingo Framework Flamingo is a web framework based on Go. It is designed to build pluggable and maintainable web projects. It is production ready, f

Jan 5, 2023
Yet another SIP003 plugin for shadowsocks, based on Xray-core

Yet another SIP003 plugin for shadowsocks, based on Xray-core Build go build Usage See command line args for advanced usages.

Jan 8, 2023
Package core is a service container that elegantly bootstrap and coordinate twelve-factor apps in Go.

Package core is a service container that elegantly bootstrap and coordinate twelve-factor apps in Go. Background The twelve-factor methodology has pro

Nov 3, 2022
Open source 5G core network base on 3GPP R15
Open source 5G core network base on 3GPP R15

What is free5GC The free5GC is an open-source project for 5th generation (5G) mobile core networks. The ultimate goal of this project is to implement

Jan 4, 2023