Skip to content

Commit

Permalink
Rough version of this working
Browse files Browse the repository at this point in the history
  • Loading branch information
belav committed May 8, 2024
1 parent 67f9934 commit 245efe4
Show file tree
Hide file tree
Showing 12 changed files with 101 additions and 75 deletions.
57 changes: 31 additions & 26 deletions Src/CSharpier.Cli/CommandLineFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,18 +65,21 @@ CancellationToken cancellationToken
);

var printerOptions = optionsProvider.GetPrinterOptionsFor(filePath);
printerOptions.IncludeGenerated = commandLineOptions.IncludeGenerated;

await PerformFormattingSteps(
fileToFormatInfo,
new StdOutFormattedFileWriter(console),
commandLineFormatterResult,
fileIssueLogger,
printerOptions,
commandLineOptions,
FormattingCacheFactory.NullCache,
cancellationToken
);
if (printerOptions is not null)
{
printerOptions.IncludeGenerated = commandLineOptions.IncludeGenerated;

await PerformFormattingSteps(
fileToFormatInfo,
new StdOutFormattedFileWriter(console),
commandLineFormatterResult,
fileIssueLogger,
printerOptions,
commandLineOptions,
FormattingCacheFactory.NullCache,
cancellationToken
);
}
}
}
else
Expand Down Expand Up @@ -206,20 +209,23 @@ async Task FormatFile(string actualFilePath, string originalFilePath)
}

var printerOptions = optionsProvider.GetPrinterOptionsFor(actualFilePath);
printerOptions.IncludeGenerated = commandLineOptions.IncludeGenerated;

await FormatPhysicalFile(
actualFilePath,
originalFilePath,
fileSystem,
logger,
commandLineFormatterResult,
writer,
commandLineOptions,
printerOptions,
formattingCache,
cancellationToken
);
if (printerOptions is not null)
{
printerOptions.IncludeGenerated = commandLineOptions.IncludeGenerated;
await FormatPhysicalFile(
actualFilePath,
originalFilePath,
fileSystem,
logger,
commandLineFormatterResult,
writer,
commandLineOptions,
printerOptions,
formattingCache,
cancellationToken
);
}
}

if (isFile)
Expand All @@ -246,7 +252,6 @@ await FormatPhysicalFile(
"*.*",
SearchOption.AllDirectories
)
.Where(o => o.EndsWithIgnoreCase(".cs") || o.EndsWithIgnoreCase(".csx"))
.Select(o =>
{
var normalizedPath = o.Replace("\\", "/");
Expand Down
3 changes: 2 additions & 1 deletion Src/CSharpier.Cli/EditorConfig/EditorConfigSections.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ public PrinterOptions ConvertToPrinterOptions(string filePath)
{
var sections = this.SectionsIncludingParentFiles.Where(o => o.IsMatch(filePath)).ToList();
var resolvedConfiguration = new ResolvedConfiguration(sections);
var printerOptions = new PrinterOptions();
// TODO overrides always this?
var printerOptions = new PrinterOptions { Formatter = "csharp" };

if (resolvedConfiguration.MaxLineLength is { } maxLineLength)
{
Expand Down
29 changes: 1 addition & 28 deletions Src/CSharpier.Cli/EditorConfig/Section.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,6 @@ namespace CSharpier.Cli.EditorConfig;

internal class Section
{
private static readonly GlobMatcherOptions globOptions =
new()
{
MatchBase = true,
Dot = true,
AllowWindowsPaths = true,
AllowSingleBraceSets = true,
};

private readonly GlobMatcher matcher;

public string? IndentStyle { get; }
Expand All @@ -23,8 +14,7 @@ internal class Section

public Section(SectionData section, string directory)
{
var pattern = FixGlob(section.SectionName, directory);
this.matcher = GlobMatcher.Create(pattern, globOptions);
this.matcher = Globber.Create(section.SectionName, directory);
this.IndentStyle = section.Keys["indent_style"];
this.IndentSize = section.Keys["indent_size"];
this.TabWidth = section.Keys["tab_width"];
Expand All @@ -36,21 +26,4 @@ public bool IsMatch(string fileName)
{
return this.matcher.IsMatch(fileName);
}

private static string FixGlob(string glob, string directory)
{
glob = glob.IndexOf('/') switch
{
-1 => "**/" + glob,
0 => glob[1..],
_ => glob
};
directory = directory.Replace(@"\", "/");
if (!directory.EndsWith("/"))
{
directory += "/";
}

return directory + glob;
}
}
23 changes: 15 additions & 8 deletions Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ internal class ConfigurationFileOptions

public Override[] Overrides { get; init; } = [];

public PrinterOptions ConvertToPrinterOptions(string filePath)
public PrinterOptions? ConvertToPrinterOptions(string filePath)
{
var matchingOverride = this.Overrides.LastOrDefault(o => o.IsMatch(filePath));
if (matchingOverride is not null)
Expand All @@ -24,17 +24,24 @@ public PrinterOptions ConvertToPrinterOptions(string filePath)
TabWidth = matchingOverride.TabWidth,
UseTabs = matchingOverride.UseTabs,
Width = matchingOverride.PrintWidth,
EndOfLine = matchingOverride.EndOfLine
EndOfLine = matchingOverride.EndOfLine,
Formatter = matchingOverride.Formatter
};
}

return new PrinterOptions
if (filePath.EndsWith(".cs") || filePath.EndsWith(".csx"))
{
TabWidth = this.TabWidth,
UseTabs = this.UseTabs,
Width = this.PrintWidth,
EndOfLine = this.EndOfLine
};
return new PrinterOptions
{
TabWidth = this.TabWidth,
UseTabs = this.UseTabs,
Width = this.PrintWidth,
EndOfLine = this.EndOfLine,
Formatter = "csharp"
};
}

return null;
}

public void Init(string directory)
Expand Down
11 changes: 8 additions & 3 deletions Src/CSharpier.Cli/Options/OptionsProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ namespace CSharpier.Cli.Options;
using System.Text.Json;
using CSharpier.Cli.EditorConfig;
using Microsoft.Extensions.Logging;
using PrinterOptions = CSharpier.PrinterOptions;

internal class OptionsProvider
{
Expand Down Expand Up @@ -82,7 +81,7 @@ public static async Task<OptionsProvider> Create(
);
}

public PrinterOptions GetPrinterOptionsFor(string filePath)
public PrinterOptions? GetPrinterOptionsFor(string filePath)
{
if (this.specifiedConfigFile is not null)
{
Expand Down Expand Up @@ -110,7 +109,13 @@ public PrinterOptions GetPrinterOptionsFor(string filePath)
return resolvedEditorConfig.ConvertToPrinterOptions(filePath);
}

return new PrinterOptions();
// TODO overrides I should see how prettier deals with some of this
if (filePath.EndsWith(".cs") || filePath.EndsWith(".csx"))
{
return new PrinterOptions { Formatter = "csharp" };
}

return null;
}

public bool IsIgnored(string actualFilePath)
Expand Down
3 changes: 2 additions & 1 deletion Src/CSharpier.Cli/Server/CSharpierServiceImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ CancellationToken cancellationToken

var result = await CSharpFormatter.FormatAsync(
formatFileParameter.fileContents,
optionsProvider.GetPrinterOptionsFor(formatFileParameter.fileName),
// TODO overrides really?
optionsProvider.GetPrinterOptionsFor(formatFileParameter.fileName)!,
cancellationToken
);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace CSharpier.Tests.Cli.Options;
using NUnit.Framework;

[TestFixture]
public class ConfigurationFileParserTests
public class ConfigFileParserTests
{
[Test]
public void Should_Parse_Yaml_With_Overrides()
Expand Down
28 changes: 26 additions & 2 deletions Src/CSharpier.Tests/CommandLineFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,13 +88,14 @@ public void Format_Writes_Unsupported()
result
.OutputLines.First()
.Should()
.Be(@"Warning ./Unsupported.js - Is an unsupported file type.");
.Be("Warning ./Unsupported.js - Is an unsupported file type.");
}

[Test]
public void Format_Writes_File_With_Directory_Path()
{
var context = new TestContext();
var unformattedFilePath = $"Unformatted.cs";
var unformattedFilePath = "Unformatted.cs";
context.WhenAFileExists(unformattedFilePath, UnformattedClassContent);

this.Format(context);
Expand Down Expand Up @@ -134,6 +135,29 @@ public static void Run() { }
);
}

[Test]
public void Formats_Overrides_File()
{
var context = new TestContext();
var unformattedFilePath = "Unformatted.cst";
context.WhenAFileExists(unformattedFilePath, UnformattedClassContent);
context.WhenAFileExists(
".csharpierrc",
"""
overrides:
- files: "*.cst"
formatter: "csharp"
"""
);

var result = this.Format(context);
result.OutputLines.First().Should().StartWith("Formatted 1 files");

context.GetFileContent(unformattedFilePath).Should().Be(FormattedClassContent);
}

// TODO overrides more tests?

[TestCase("0.9.0", false)]
[TestCase("9999.0.0", false)]
[TestCase("current", true)]
Expand Down
3 changes: 2 additions & 1 deletion Src/CSharpier.Tests/OptionsProviderTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -752,7 +752,8 @@ public async Task<PrinterOptions> CreateProviderAndGetOptionsFor(
limitEditorConfigSearch
);

return provider.GetPrinterOptionsFor(filePath);
// TODO overrides, ugh
return provider.GetPrinterOptionsFor(filePath)!;
}
}
}
6 changes: 4 additions & 2 deletions Src/CSharpier/CodeFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,8 @@ public static Task<CodeFormatterResult> FormatAsync(
UseTabs = options.IndentStyle == IndentStyle.Tabs,
TabWidth = options.IndentSize,
EndOfLine = options.EndOfLine,
IncludeGenerated = options.IncludeGenerated
IncludeGenerated = options.IncludeGenerated,
Formatter = "csharp"
},
cancellationToken
);
Expand Down Expand Up @@ -56,7 +57,8 @@ public static Task<CodeFormatterResult> FormatAsync(
Width = options.Width,
UseTabs = options.IndentStyle == IndentStyle.Tabs,
TabWidth = options.IndentSize,
EndOfLine = options.EndOfLine
EndOfLine = options.EndOfLine,
Formatter = "csharp"
},
SourceCodeKind.Regular,
cancellationToken
Expand Down
6 changes: 5 additions & 1 deletion Src/CSharpier/DocTypes/Doc.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ internal abstract class Doc
{
public string Print()
{
return DocPrinter.DocPrinter.Print(this, new PrinterOptions(), Environment.NewLine);
return DocPrinter.DocPrinter.Print(
this,
new PrinterOptions { Formatter = "csharp" },
Environment.NewLine
);
}

public override string ToString()
Expand Down
5 changes: 4 additions & 1 deletion Src/CSharpier/PrinterOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,10 @@ internal class PrinterOptions
public int Width { get; set; } = 100;
public EndOfLine EndOfLine { get; set; } = EndOfLine.Auto;
public bool TrimInitialLines { get; init; } = true;
public bool IncludeGenerated { get; set; } = false;
public bool IncludeGenerated { get; set; }

// TODO overrides require this?
public string Formatter { get; init; } = string.Empty;

public const int WidthUsedByTests = 100;

Expand Down

0 comments on commit 245efe4

Please sign in to comment.