Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding XML formatting #858

Merged
merged 60 commits into from
Jan 12, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
60 commits
Select commit Hold shift + click to select a range
fec0970
Working on moving around tests
belav Mar 20, 2023
ee13114
Making some changes so that adding more file types is easier to test
belav Mar 20, 2023
85e1731
Refactoring towards multiple formatters
belav Mar 20, 2023
c617fe4
Updating ignore
belav Mar 20, 2023
b1fdc0f
Some cleanup
belav Mar 20, 2023
756b51f
Working on getting the generators happy with multiple directories
belav Mar 20, 2023
57395fd
Getting basics working
belav Mar 20, 2023
e72b76d
Adding csproj to playground. Switching to a sane state management pat…
belav Mar 27, 2023
5887f44
Trying to format with the CLI
belav Mar 27, 2023
30f05a4
fixing warnings
belav Mar 27, 2023
f5e8be4
Some notes and fixes
belav Mar 28, 2023
4a4c2a2
Adding some tests. Fixing <?xml being removed
belav Apr 17, 2023
e51834d
Getting the basics of printing Xml with Doc going
belav Apr 17, 2023
e61f38d
Merge branch 'main' into csproj-formatting
belav Apr 17, 2023
a8d1c64
Fixing thing
belav Apr 17, 2023
ebd2316
Getting attributes working better
belav Apr 17, 2023
f95ad65
some little cleanup
belav Apr 17, 2023
a913e77
Merge branch 'main' into csproj-formatting
belav Sep 15, 2024
14fa782
get playground partly working
belav Sep 15, 2024
21b7185
cleanup usings
belav Sep 15, 2024
a8ffa77
Getting things working with the changes that were in main
belav Sep 16, 2024
9367648
starting to pull in all the logic from how prettier prints html
belav Sep 17, 2024
25ce144
add note for looking into the xml plugin to see if it is easier
belav Sep 17, 2024
eaf396d
getting child elements partly working
belav Sep 22, 2024
d6ab600
kinda getting somewhere.... maybe
belav Sep 23, 2024
2f37675
now this is actually getting somewhat close
belav Sep 23, 2024
9eb07e0
actually getting close now
belav Sep 23, 2024
a99fd33
getting initial xml formatting done. settling on 2 spaces for default…
belav Sep 27, 2024
3fd3bb8
Fixing up some edge cases
belav Oct 5, 2024
3bb0661
adding some more notes about edge cases
belav Oct 5, 2024
4f4f476
Merge branch 'main' into csproj-formatting
belav Oct 20, 2024
463f89d
Merge branch 'main' into csproj-formatting
belav Oct 20, 2024
3b7f27e
fixing more edge cases
belav Oct 20, 2024
fb448ab
Merge branch 'main' into csproj-formatting
belav Nov 11, 2024
662b362
resolving merge issues
belav Nov 11, 2024
5bf1b55
some cleanup
belav Nov 11, 2024
6264407
Merge branch 'main' into csproj-formatting
belav Nov 11, 2024
968cef9
Fixing more issues
belav Nov 11, 2024
36673f1
Merge branch 'main' into csproj-formatting
belav Nov 17, 2024
681b2fe
finding a road block
belav Nov 17, 2024
902729a
Merge branch 'main' into csproj-formatting
belav Nov 18, 2024
fbcefb8
getting things mostly converted to using XDocument instead
belav Nov 18, 2024
ac66f01
getting things kinda sorta working
belav Nov 19, 2024
32753e5
Another road block
belav Dec 23, 2024
210696a
Possibly getting everything working
belav Dec 23, 2024
0f4a4cb
a bit of cleanup
belav Dec 24, 2024
582f2cc
Merge branch 'main' into csproj-formatting
belav Dec 24, 2024
84dd9fc
Fixing a few edge cases
belav Dec 24, 2024
3560bcb
Dealing with more stuff
belav Dec 25, 2024
69745da
Maybe getting the last erroring file from csharpier-repos
belav Dec 25, 2024
c2e741d
trying to get msbuild passing
belav Dec 25, 2024
c478215
ignore xml files in these msbuild tests
belav Dec 25, 2024
20b2cc7
notes
belav Dec 25, 2024
ee07a7d
Merge branch 'main' into csproj-formatting
belav Dec 26, 2024
32a343f
cleanup after merge
belav Dec 26, 2024
eefa553
cleanup comments
belav Dec 28, 2024
3b3dfc2
Merge branch '1.0.0' into csproj-formatting
belav Jan 4, 2025
d4fcfa8
fixing some issues so vscode can format xml
belav Jan 4, 2025
1d9bc5d
Merge branch '1.0.0' into csproj-formatting
belav Jan 12, 2025
2bd3d62
fixing some tests
belav Jan 12, 2025
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ build
publish

*.doctree.txt
*.actual.cst
*.actual.test
*.vsix
/.husky/pre-commit
Expand Down
7 changes: 7 additions & 0 deletions .idea/.idea.CSharpier/.idea/prettier.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -1194,7 +1194,7 @@ host.AddSection(
tags: Tags.SamplesUsed,
tasks:
[
// TODO: Add any used third party instruments below as you discover them.
// TO-DO: Add any used third party instruments below as you discover them.
]
);

Expand All @@ -1204,7 +1204,7 @@ host.AddSection(
tags: Tags.SamplesUsed,
tasks:
[
// TODO: Add any used third party instruments below as you discover them.
// TO-DO: Add any used third party instruments below as you discover them.
]
);
```
Expand Down
1 change: 1 addition & 0 deletions CSharpier.sln.DotSettings
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:Boolean x:Key="/Default/CodeStyle/CSharpUsing/AddImportsToDeepestScope/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Concated/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=csharpier/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=csharpierignore/@EntryIndexedValue">True</s:Boolean>
Expand Down
2 changes: 1 addition & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<!-- this is the warning generators get when they fail to generate a source file this makes sure the error for it failing is obvious -->
<WarningsAsErrors>CS8032</WarningsAsErrors>
<WarningsAsErrors>CS8032;CS8033;</WarningsAsErrors>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
Expand Down
31 changes: 9 additions & 22 deletions Shell/UpdateCSharpierRepos.psm1
Original file line number Diff line number Diff line change
Expand Up @@ -46,24 +46,20 @@ function CSH-UpdateCSharpierRepos()
Set-Location $destination
& git checkout main

Get-ChildItem $tempLocation | Copy-Item -Destination $destination -Filter *.cs -Recurse -Force
$extensions = (".csproj", ".props", ".targets", ".xml", ".config", ".cs")

foreach ($extension in $extensions)
{
Get-ChildItem $tempLocation | Copy-Item -Destination $destination -Filter "*$extension" -Recurse -Force
}

return

$items = Get-ChildItem -Recurse C:\projects\csharpier-repos -File
$count = 0
foreach ($item in $items)
{
if ($item.Name -eq ".git")
{
Remove-Item -Force -Recurse $item.FullName
}
elseif ($item.Extension -ne ".cs")
{
if ($item.Name -ne ".csharpierignore")
{
Remove-Item $item.FullName
}
}
else
if ($item.Extension -eq ".cs")
{
# we don't really need all of these files, let's just cut out every other one
if ($count % 2 -eq 0)
Expand All @@ -74,15 +70,6 @@ function CSH-UpdateCSharpierRepos()
}
}

$items = Get-ChildItem C:\projects\csharpier-repos -Directory -Recurse
foreach ($item in $items)
{
if ($item.Name -eq ".git")
{
Remove-Item -Force -Recurse $item.FullName
}
}

Set-Location $destination

& git add .
Expand Down
5 changes: 4 additions & 1 deletion Src/CSharpier.Benchmarks/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,10 @@ public class Benchmarks
[Benchmark]
public void Default_CodeFormatter()
{
CSharpFormatter.FormatAsync(this.largeCode, new PrinterOptions()).GetAwaiter().GetResult();
CSharpFormatter
.FormatAsync(this.largeCode, new PrinterOptions(Formatter.CSharp))
.GetAwaiter()
.GetResult();
}

[Benchmark]
Expand Down
7 changes: 2 additions & 5 deletions Src/CSharpier.Cli.Tests/CliTests.cs
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CliWrap;
using CliWrap.Buffered;
Expand Down Expand Up @@ -95,8 +93,7 @@ public async Task Should_Respect_Ignore_File_With_Subdirectory_When_DirectorOrFi
await this.WriteFileAsync(filePath, unformattedContent);
await this.WriteFileAsync(".csharpierignore", filePath);

var result = await new CsharpierProcess().WithArguments("format .").ExecuteAsync();
result.Output.Should().StartWith("Formatted 0 files in ");
await new CsharpierProcess().WithArguments("format .").ExecuteAsync();
var fileContents = await this.ReadAllTextAsync(filePath);

fileContents
Expand Down Expand Up @@ -395,7 +392,7 @@ await this.WriteFileAsync(

result.ErrorOutput.Should().BeEmpty();
result.ExitCode.Should().Be(0);
result.Output.Should().StartWith("Formatted 0 files in ");
result.Output.Should().StartWith("Formatted 1 files in ");
}

[Test]
Expand Down
1 change: 0 additions & 1 deletion Src/CSharpier.Cli.Tests/ServerTests.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
using System.Diagnostics;
using System.Net.Http.Json;
using System.Text;
using CliWrap;
using CliWrap.EventStream;
using CSharpier.Cli.Server;
Expand Down
73 changes: 42 additions & 31 deletions Src/CSharpier.Cli/CommandLineFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -379,18 +379,13 @@ CancellationToken cancellationToken

cancellationToken.ThrowIfCancellationRequested();

CodeFormatterResult codeFormattingResult;

var sourceCodeKind = Path.GetExtension(fileToFormatInfo.Path).EqualsIgnoreCase(".csx")
? SourceCodeKind.Script
: SourceCodeKind.Regular;
CodeFormatterResult? codeFormattingResult;

try
{
codeFormattingResult = await CSharpFormatter.FormatAsync(
codeFormattingResult = await CodeFormatter.FormatAsync(
fileToFormatInfo.FileContents,
printerOptions,
sourceCodeKind,
cancellationToken
);
}
Expand Down Expand Up @@ -427,6 +422,12 @@ CancellationToken cancellationToken
return;
}

if (!codeFormattingResult.WarningMessage.IsBlank())
{
fileIssueLogger.WriteWarning(codeFormattingResult.WarningMessage);
return;
}

if (!codeFormattingResult.FailureMessage.IsBlank())
{
fileIssueLogger.WriteError(codeFormattingResult.FailureMessage);
Expand All @@ -435,35 +436,45 @@ CancellationToken cancellationToken

if (!commandLineOptions.Fast)
{
var syntaxNodeComparer = new SyntaxNodeComparer(
fileToFormatInfo.FileContents,
codeFormattingResult.Code,
codeFormattingResult.ReorderedModifiers,
codeFormattingResult.ReorderedUsingsWithDisabledText,
codeFormattingResult.MovedTrailingTrivia,
sourceCodeKind,
cancellationToken
);

try
if (printerOptions.Formatter is Formatter.CSharp or Formatter.CSharpScript)
{
var failure = await syntaxNodeComparer.CompareSourceAsync(cancellationToken);
if (!string.IsNullOrEmpty(failure))
var sourceCodeKind =
printerOptions.Formatter is Formatter.CSharpScript
? SourceCodeKind.Script
: SourceCodeKind.Regular;

var syntaxNodeComparer = new SyntaxNodeComparer(
fileToFormatInfo.FileContents,
codeFormattingResult.Code,
codeFormattingResult.ReorderedModifiers,
codeFormattingResult.ReorderedUsingsWithDisabledText,
codeFormattingResult.MovedTrailingTrivia,
sourceCodeKind,
cancellationToken
);

try
{
var failure = await syntaxNodeComparer.CompareSourceAsync(cancellationToken);
if (!string.IsNullOrEmpty(failure))
{
Interlocked.Increment(
ref commandLineFormatterResult.FailedSyntaxTreeValidation
);
fileIssueLogger.WriteError($"Failed syntax tree validation.\n{failure}");
}
}
catch (Exception ex)
{
Interlocked.Increment(
ref commandLineFormatterResult.FailedSyntaxTreeValidation
ref commandLineFormatterResult.ExceptionsValidatingSource
);
fileIssueLogger.WriteError($"Failed syntax tree validation.\n{failure}");
}
}
catch (Exception ex)
{
Interlocked.Increment(ref commandLineFormatterResult.ExceptionsValidatingSource);

fileIssueLogger.WriteError(
"Failed with exception during syntax tree validation.",
ex
);
fileIssueLogger.WriteError(
"Failed with exception during syntax tree validation.",
ex
);
}
}
}

Expand Down
7 changes: 3 additions & 4 deletions Src/CSharpier.Cli/EditorConfig/EditorConfigSections.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,14 @@ internal class EditorConfigSections
var resolvedConfiguration = new ResolvedConfiguration(sections);

var formatter =
resolvedConfiguration.Formatter
?? (filePath.EndsWith(".cs") || filePath.EndsWith(".csx") ? "csharp" : null);
resolvedConfiguration.Formatter ?? PrinterOptions.GetFormatter(filePath).ToString();

if (formatter == null)
if (!Enum.TryParse<Formatter>(formatter, ignoreCase: true, out var parsedFormatter))
{
return null;
}

var printerOptions = new PrinterOptions { Formatter = formatter };
var printerOptions = new PrinterOptions(parsedFormatter);

if (resolvedConfiguration.MaxLineLength is { } maxLineLength)
{
Expand Down
24 changes: 17 additions & 7 deletions Src/CSharpier.Cli/Options/ConfigurationFileOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ namespace CSharpier.Cli.Options;
internal class ConfigurationFileOptions
{
public int PrintWidth { get; init; } = 100;
public int IndentSize { get; init; } = 4;
public int? IndentSize { get; init; }
public bool UseTabs { get; init; }

[JsonConverter(typeof(CaseInsensitiveEnumConverter<EndOfLine>))]
Expand All @@ -20,25 +20,35 @@ internal class ConfigurationFileOptions
var matchingOverride = this.Overrides.LastOrDefault(o => o.IsMatch(filePath));
if (matchingOverride is not null)
{
return new PrinterOptions
if (
!Enum.TryParse<Formatter>(
matchingOverride.Formatter,
ignoreCase: true,
out var parsedFormatter
)
)
{
return null;
}

return new PrinterOptions(parsedFormatter)
{
IndentSize = matchingOverride.IndentSize,
UseTabs = matchingOverride.UseTabs,
Width = matchingOverride.PrintWidth,
EndOfLine = matchingOverride.EndOfLine,
Formatter = matchingOverride.Formatter,
};
}

if (filePath.EndsWith(".cs") || filePath.EndsWith(".csx"))
var formatter = PrinterOptions.GetFormatter(filePath);
if (formatter != Formatter.Unknown)
{
return new PrinterOptions
return new PrinterOptions(formatter)
{
IndentSize = this.IndentSize,
IndentSize = this.IndentSize ?? (formatter == Formatter.XML ? 2 : 4),
UseTabs = this.UseTabs,
Width = this.PrintWidth,
EndOfLine = this.EndOfLine,
Formatter = "csharp",
};
}

Expand Down
8 changes: 2 additions & 6 deletions Src/CSharpier.Cli/Options/OptionsProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -110,12 +110,8 @@ public static async Task<OptionsProvider> Create(
return resolvedEditorConfig.ConvertToPrinterOptions(filePath);
}

if (filePath.EndsWith(".cs") || filePath.EndsWith(".csx"))
{
return new PrinterOptions { Formatter = "csharp" };
}

return null;
var formatter = PrinterOptions.GetFormatter(filePath);
return formatter != Formatter.Unknown ? new PrinterOptions(formatter) : null;
}

public bool IsIgnored(string actualFilePath)
Expand Down
30 changes: 25 additions & 5 deletions Src/CSharpier.Cli/PhysicalFileInfoAndWriter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,31 @@ public void WriteResult(CodeFormatterResult result, FileToFormatInfo fileToForma
{
if (result.Code != fileToFormatInfo.FileContents)
{
this.FileSystem.File.WriteAllText(
fileToFormatInfo.Path,
result.Code,
fileToFormatInfo.Encoding
);
const int maxTries = 5;
var tries = 1;
// TODO #819 this started happening on the EFcore folder, is it related to the msbuild check somehow?
while (tries <= maxTries)
{
try
{
this.FileSystem.File.WriteAllText(
fileToFormatInfo.Path,
result.Code,
fileToFormatInfo.Encoding
);
return;
}
catch (IOException)
{
if (tries == maxTries)
{
throw;
}

Thread.Sleep(TimeSpan.FromMilliseconds(50));
tries++;
}
}
}
}
}
3 changes: 2 additions & 1 deletion Src/CSharpier.Cli/Server/CSharpierServiceImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ CancellationToken cancellationToken
return new FormatFileResult(Status.UnsupportedFile);
}

var result = await CSharpFormatter.FormatAsync(
// TODO if compilation errors we still return whatever was here
var result = await CodeFormatter.FormatAsync(
formatFileParameter.fileContents,
printerOptions,
cancellationToken
Expand Down
Loading
Loading