Skip to content

Commit

Permalink
fix: support EditorConfig comments
Browse files Browse the repository at this point in the history
The spec very clearly states that comments are supported. Without this fix a basic config file like the example given on the EditorConfig website will cause a crash.

```
# EditorConfig is awesome: https://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# ...
```

Spec: https://spec.editorconfig.org/#file-format
  • Loading branch information
meenzen committed Sep 22, 2023
1 parent 2ad4e5d commit aac5f3a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 1 deletion.
14 changes: 13 additions & 1 deletion Src/CSharpier.Cli/EditorConfig/ConfigFileParser.cs
Original file line number Diff line number Diff line change
@@ -1,13 +1,25 @@
using System.IO.Abstractions;
using System.Text.RegularExpressions;
using IniParser;
using IniParser.Model.Configuration;
using IniParser.Parser;

namespace CSharpier.Cli.EditorConfig;

internal static class ConfigFileParser
{
// According to https://spec.editorconfig.org/#file-format
// "Comment: starts with a ; or a #."
private static readonly Regex CommentRegex = new("^[;#].*$");

private static readonly IniParserConfiguration Configuration = new()
{
CommentRegex = CommentRegex,
};

public static ConfigFile Parse(string filePath, IFileSystem fileSystem)
{
var parser = new FileIniDataParser();
var parser = new FileIniDataParser(new IniDataParser(Configuration));

using var stream = fileSystem.File.OpenRead(filePath);
using var streamReader = new StreamReader(stream);
Expand Down
29 changes: 29 additions & 0 deletions Src/CSharpier.Tests/OptionsProviderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -215,6 +215,35 @@ public async Task Should_Support_EditorConfig_Basic()
result.EndOfLine.Should().Be(EndOfLine.CRLF);
}

[Test]
public async Task Should_Support_EditorConfig_With_Comments()
{
var context = new TestContext();
context.WhenAFileExists(
"c:/test/.editorconfig",
@"
# EditorConfig is awesome: https://EditorConfig.org
# top-most EditorConfig file
root = true
[*]
indent_style = space
indent_size = 2
max_line_length = 10
; Windows-style line endings
end_of_line = crlf
"
);

var result = await context.CreateProviderAndGetOptionsFor("c:/test", "c:/test/test.cs");

result.UseTabs.Should().BeFalse();
result.TabWidth.Should().Be(2);
result.Width.Should().Be(10);
result.EndOfLine.Should().Be(EndOfLine.CRLF);
}

[TestCase("tab_width")]
[TestCase("indent_size")]
public async Task Should_Support_EditorConfig_Tabs(string propertyName)
Expand Down

0 comments on commit aac5f3a

Please sign in to comment.