Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
10 changes: 5 additions & 5 deletions Src/CSharpier.Cli/CommandLineFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ CommandLineFormatterResult result
)
{
if (
(!commandLineOptions.CompilationErrorsAsWarnings && result.FailedCompilation > 0)
(!commandLineOptions.SyntaxErrorsAsWarnings && result.FailedCompilation > 0)
|| (
commandLineOptions.Check
&& result.UnformattedFiles > 0
Expand Down Expand Up @@ -477,16 +477,16 @@ CancellationToken cancellationToken
return;
}

if (codeFormattingResult.CompilationErrors.Any())
if (codeFormattingResult.ErrorDiagnostics.Any())
{
var errorMessage = new StringBuilder();
errorMessage.AppendLine("Failed to compile so was not formatted.");
foreach (var message in codeFormattingResult.CompilationErrors)
errorMessage.AppendLine("Was not formatted due to syntax errors.");
foreach (var message in codeFormattingResult.ErrorDiagnostics)
{
errorMessage.AppendLine(message.ToString());
}

if (!commandLineOptions.CompilationErrorsAsWarnings)
if (!commandLineOptions.SyntaxErrorsAsWarnings)
{
fileIssueLogger.WriteError(errorMessage.ToString());
}
Expand Down
3 changes: 2 additions & 1 deletion Src/CSharpier.Cli/CommandLineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ internal class CommandLineOptions
public bool WriteStdout { get; init; }
public bool NoCache { get; init; }
public bool NoMSBuildCheck { get; init; }
public bool CompilationErrorsAsWarnings { get; init; }

public bool SyntaxErrorsAsWarnings { get; init; }
public bool UnformattedAsWarnings { get; init; }
public bool IncludeGenerated { get; init; }
public string? StandardInFileContents { get; init; }
Expand Down
26 changes: 13 additions & 13 deletions Src/CSharpier.Cli/FormattingCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ public static Command CreateFormatCommand()
"Write the results of formatting any files to stdout."
);
formatCommand.AddOption(writeStdoutOption);
formatCommand.AddOption(CompilationErrorsAsWarningsOption);
formatCommand.AddOption(SyntaxErrorsAsWarningsOption);
formatCommand.AddOption(ConfigPathOption);
formatCommand.AddOption(IgnorePathOption);
formatCommand.AddOption(StdinPathOption);
Expand All @@ -49,8 +49,8 @@ public static Command CreateFormatCommand()
var noCache = context.ParseResult.GetValueForOption(noCacheOption);
var noMSBuildCheck = context.ParseResult.GetValueForOption(NoMsBuildCheckOption);
var includeGenerated = context.ParseResult.GetValueForOption(IncludeGeneratedOption);
var compilationErrorsAsWarnings = context.ParseResult.GetValueForOption(
CompilationErrorsAsWarningsOption
var syntaxErrorsAsWarnings = context.ParseResult.GetValueForOption(
SyntaxErrorsAsWarningsOption
);
var configPath = context.ParseResult.GetValueForOption(ConfigPathOption);
var ignorePath = context.ParseResult.GetValueForOption(IgnorePathOption);
Expand All @@ -68,7 +68,7 @@ public static Command CreateFormatCommand()
noCache,
noMSBuildCheck,
includeGenerated,
compilationErrorsAsWarnings,
syntaxErrorsAsWarnings,
false,
configPath,
ignorePath,
Expand Down Expand Up @@ -101,7 +101,7 @@ public static Command CreateCheckCommand()
checkCommand.AddOption(LogLevelOption);
checkCommand.AddOption(IncludeGeneratedOption);
checkCommand.AddOption(NoMsBuildCheckOption);
checkCommand.AddOption(CompilationErrorsAsWarningsOption);
checkCommand.AddOption(SyntaxErrorsAsWarningsOption);
checkCommand.AddOption(UnformattedAsWarningsOption);

checkCommand.SetHandler(async context =>
Expand All @@ -110,8 +110,8 @@ public static Command CreateCheckCommand()
var useCache = context.ParseResult.GetValueForOption(useCacheOption);
var noMSBuildCheck = context.ParseResult.GetValueForOption(NoMsBuildCheckOption);
var includeGenerated = context.ParseResult.GetValueForOption(IncludeGeneratedOption);
var compilationErrorsAsWarnings = context.ParseResult.GetValueForOption(
CompilationErrorsAsWarningsOption
var syntaxErrorsAsWarnings = context.ParseResult.GetValueForOption(
SyntaxErrorsAsWarningsOption
);
var unformattedAsWarningsOption = context.ParseResult.GetValueForOption(
UnformattedAsWarningsOption
Expand All @@ -131,7 +131,7 @@ public static Command CreateCheckCommand()
noCache: !useCache,
noMSBuildCheck,
includeGenerated,
compilationErrorsAsWarnings,
syntaxErrorsAsWarnings,
unformattedAsWarningsOption,
configPath,
ignorePath,
Expand All @@ -154,7 +154,7 @@ private static async Task<int> FormatOrCheck(
bool noCache,
bool noMSBuildCheck,
bool includeGenerated,
bool compilationErrorsAsWarnings,
bool syntaxErrorsAsWarnings,
bool unformattedAsWarnings,
string? configPath,
string? ignorePath,
Expand Down Expand Up @@ -205,7 +205,7 @@ CancellationToken cancellationToken
IncludeGenerated = includeGenerated,
ConfigPath = configPath,
IgnorePath = ignorePath,
CompilationErrorsAsWarnings = compilationErrorsAsWarnings,
SyntaxErrorsAsWarnings = syntaxErrorsAsWarnings,
UnformattedAsWarnings = unformattedAsWarnings,
LogFormat = logFormat,
};
Expand Down Expand Up @@ -281,9 +281,9 @@ Log output format
"Bypass the check to determine if a csproj files references a different version of CSharpier.MsBuild."
);

private static readonly Option<bool> CompilationErrorsAsWarningsOption = new(
["--compilation-errors-as-warnings"],
"Treat compilation errors from files as warnings instead of errors."
private static readonly Option<bool> SyntaxErrorsAsWarningsOption = new(
["--syntax-errors-as-warnings"],
"Treat syntax errors from files as warnings instead of errors."
);

private static readonly Option<bool> UnformattedAsWarningsOption = new(
Expand Down
2 changes: 2 additions & 0 deletions Src/CSharpier.Cli/IgnoreFile.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ namespace CSharpier.Cli;

internal class IgnoreFile
{
public static IgnoreFile NullIgnore = new([]);

private List<IgnoreList> Ignores { get; }

private IgnoreFile(List<IgnoreList> ignores)
Expand Down
18 changes: 2 additions & 16 deletions Src/CSharpier.Cli/Options/OptionsProvider.cs
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,7 @@ CancellationToken cancellationToken
cancellationToken
);

#pragma warning disable IDE0270
if (ignoreFile is null)
{
// should never happen
throw new Exception("Unable to locate an IgnoreFile for " + directoryName);
}
#pragma warning restore IDE0270
ignoreFile ??= IgnoreFile.NullIgnore;

var specifiedEditorConfig = editorConfigPath is not null
? await EditorConfigLocator.FindForDirectoryNameAsync(
Expand Down Expand Up @@ -218,15 +212,7 @@ CancellationToken cancellationToken
)
);

#pragma warning disable IDE0270
if (ignoreFile is null)
{
// should never happen
throw new Exception("Unable to locate an IgnoreFile for " + directoryName);
}
#pragma warning restore IDE0270

return ignoreFile;
return ignoreFile ?? IgnoreFile.NullIgnore;
}

/// <summary>
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Cli/Server/CSharpierServiceImplementation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ CancellationToken cancellationToken
cancellationToken
);

if (result.CompilationErrors.Any())
if (result.ErrorDiagnostics.Any())
{
return new FormatFileResult(Status.Failed)
{
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Core/CSharp/CSharpFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ bool TryGetCompilationFailure(out CodeFormatterResult compilationResult)
compilationResult = new CodeFormatterResult
{
Code = syntaxTree.ToString(),
CompilationErrors = diagnostics,
ErrorDiagnostics = diagnostics,
AST = printerOptions.IncludeAST ? PrintAST(rootNode) : string.Empty,
};

Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Core/CodeFormatterResult.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ internal CodeFormatterResult() { }
internal string DocTree { get; init; } = string.Empty;
internal string AST { get; init; } = string.Empty;
internal string WarningMessage { get; init; } = string.Empty;
public IEnumerable<Diagnostic> CompilationErrors { get; internal init; } = [];
public IEnumerable<Diagnostic> ErrorDiagnostics { get; internal init; } = [];

internal string FailureMessage { get; init; } = string.Empty;

Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Core/PublicAPI.Shipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ CSharpier.Core.CodeFormatterOptions.IndentStyle.init -> void

CSharpier.Core.CodeFormatterResult
CSharpier.Core.CodeFormatterResult.Code.get -> string!
CSharpier.Core.CodeFormatterResult.CompilationErrors.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic!>!
CSharpier.Core.CodeFormatterResult.ErrorDiagnostics.get -> System.Collections.Generic.IEnumerable<Microsoft.CodeAnalysis.Diagnostic!>!
CSharpier.Core.CodeFormatterOptions.IncludeGenerated.get -> bool
CSharpier.Core.CodeFormatterOptions.IncludeGenerated.init -> void

Expand Down
41 changes: 40 additions & 1 deletion Src/CSharpier.Core/Xml/XmlFormatter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
using System.Xml;
using CSharpier.Core.CSharp.SyntaxPrinter;
using CSharpier.Core.DocTypes;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
using Node = CSharpier.Core.Xml.XNodePrinters.Node;

namespace CSharpier.Core.Xml;
Expand Down Expand Up @@ -56,16 +58,53 @@ PrinterOptions printerOptions
AST = RawNodeSyntaxWriter.Write(rootNode),
};
}
catch (XmlException)
catch (XmlException ex)
{
return new CodeFormatterResult
{
Code = xml,
ErrorDiagnostics = [CreateDiagnosticFromXmlException(xml, ex)],
WarningMessage = "Appeared to be invalid xml so was not formatted.",
};
}
}

private static Diagnostic CreateDiagnosticFromXmlException(string xml, XmlException ex)
{
var sourceText = SourceText.From(xml);

// XmlException is 1-based; Roslyn is 0-based
var lineIndex = Math.Max(0, ex.LineNumber - 1);
if (lineIndex >= sourceText.Lines.Count)
{
lineIndex = sourceText.Lines.Count - 1;
}

var line = sourceText.Lines[lineIndex];

var charIndexInLine = Math.Max(0, ex.LinePosition - 1);
var position = Math.Min(line.Start + charIndexInLine, line.End);

var span = new TextSpan(position, 0);

var location = Location.Create(
filePath: string.Empty,
textSpan: span,
lineSpan: sourceText.Lines.GetLinePositionSpan(span)
);

var descriptor = new DiagnosticDescriptor(
id: "XML001",
title: "XML parsing error",
messageFormat: "{0}",
category: "XML",
DiagnosticSeverity.Error,
isEnabledByDefault: true
);

return Diagnostic.Create(descriptor, location, ex.Message);
}

// the RawNodeReader is very basic and doesn't care if xml is valid or not and could mangle invalid xml if we allow it to format the invalid xml
private static async Task ValidateXmlAsync(string xml)
{
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.MsBuild/build/CSharpier.MsBuild.targets
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
StdOutEncoding="utf-8"
StdErrEncoding="utf-8"
IgnoreExitCode="true"
Command="&quot;$(CSharpier_dotnet_Path)&quot; exec &quot;$(CSharpierDllPath)&quot; $(CSharpierCommand) $(CSharpierArgs) --log-format msBuild --no-msbuild-check --compilation-errors-as-warnings &quot;$(MSBuildProjectDirectory)&quot; &gt; $(NullOutput) "
Command="&quot;$(CSharpier_dotnet_Path)&quot; exec &quot;$(CSharpierDllPath)&quot; $(CSharpierCommand) $(CSharpierArgs) --log-format msBuild --no-msbuild-check --syntax-errors-as-warnings &quot;$(MSBuildProjectDirectory)&quot; &gt; $(NullOutput) "
/>
</Target>

Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Playground/Controllers/FormatController.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ CancellationToken cancellationToken
Code = result.Code,
Json = result.AST,
Doc = result.DocTree,
Errors = result.CompilationErrors.Select(this.ConvertError).ToList(),
Errors = result.ErrorDiagnostics.Select(this.ConvertError).ToList(),
SyntaxValidation = await comparer.CompareSourceAsync(CancellationToken.None),
};
}
Expand Down
4 changes: 2 additions & 2 deletions Src/CSharpier.Tests/CSharp/CSharpFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ public void Format_Should_Use_Default_Width()
var result = CSharpFormatter.Format(code);

result.Code.Should().Be("var someVariable = someValue;\n");
result.CompilationErrors.Should().BeEmpty();
result.ErrorDiagnostics.Should().BeEmpty();
}

[Test]
Expand All @@ -24,7 +24,7 @@ public void Format_Should_Return_Compilation_Errors()
var result = CSharpFormatter.Format(code);

result.Code.Should().Be(code);
result.CompilationErrors.Should().ContainSingle();
result.ErrorDiagnostics.Should().ContainSingle();
}

[Test]
Expand Down
18 changes: 9 additions & 9 deletions Src/CSharpier.Tests/CommandLineFormatterTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public async Task Format_Writes_Failed_To_Compile()
.ErrorOutputLines.First()
.Replace('\\', '/')
.Should()
.Be("Error ./Invalid.cs - Failed to compile so was not formatted.");
.Be("Error ./Invalid.cs - Was not formatted due to syntax errors.");

result.ExitCode.Should().Be(1);
}
Expand All @@ -36,13 +36,13 @@ public async Task Format_Writes_Failed_To_Compile_As_Warning()
var context = new TestContext();
context.WhenAFileExists("Invalid.cs", "asdfasfasdf");

var result = await Format(context, compilationErrorsAsWarnings: true);
var result = await Format(context, syntaxErrorsAsWarnings: true);

result
.OutputLines.First()
.Replace('\\', '/')
.Should()
.Be("Warning ./Invalid.cs - Failed to compile so was not formatted.");
.Be("Warning ./Invalid.cs - Was not formatted due to syntax errors.");

result.ExitCode.Should().Be(0);
}
Expand All @@ -59,7 +59,7 @@ public async Task Format_Writes_Failed_To_Compile_For_Subdirectory()
.ErrorOutputLines.First()
.Replace('\\', '/')
.Should()
.Be("Error ./Subdirectory/Invalid.cs - Failed to compile so was not formatted.");
.Be("Error ./Subdirectory/Invalid.cs - Was not formatted due to syntax errors.");
}

[Test]
Expand All @@ -78,7 +78,7 @@ public async Task Format_Writes_Failed_To_Compile_For_FullPath()
.Replace('\\', '/')
.Should()
.Be(
$"Error {GetRootPath().Replace('\\', '/')}/Subdirectory/Invalid.cs - Failed to compile so was not formatted."
$"Error {GetRootPath().Replace('\\', '/')}/Subdirectory/Invalid.cs - Was not formatted due to syntax errors."
);
}

Expand All @@ -94,7 +94,7 @@ public async Task Format_Writes_Failed_To_Compile_With_Directory()
.ErrorOutputLines.First()
.Replace('\\', '/')
.Should()
.Be("Error ./Directory/Invalid.cs - Failed to compile so was not formatted.");
.Be("Error ./Directory/Invalid.cs - Was not formatted due to syntax errors.");
}

[Test]
Expand Down Expand Up @@ -829,7 +829,7 @@ public async Task File_With_Compilation_Error_Should_Not_Lose_Code()
.ErrorOutputLines.First()
.Replace('\\', '/')
.Should()
.Be("Error ./Invalid.cs - Failed to compile so was not formatted.");
.Be("Error ./Invalid.cs - Was not formatted due to syntax errors.");
}

[Test]
Expand Down Expand Up @@ -1057,7 +1057,7 @@ private static async Task<FormatResult> Format(
LogFormat logFormat = LogFormat.Console,
bool writeStdout = false,
bool includeGenerated = false,
bool compilationErrorsAsWarnings = false,
bool syntaxErrorsAsWarnings = false,
string? standardInFileContents = null,
string? configPath = null,
params string[] directoryOrFilePaths
Expand Down Expand Up @@ -1090,7 +1090,7 @@ params string[] directoryOrFilePaths
WriteStdout = writeStdout || standardInFileContents != null,
StandardInFileContents = standardInFileContents,
IncludeGenerated = includeGenerated,
CompilationErrorsAsWarnings = compilationErrorsAsWarnings,
SyntaxErrorsAsWarnings = syntaxErrorsAsWarnings,
},
context.FileSystem,
fakeConsole,
Expand Down
2 changes: 1 addition & 1 deletion Src/CSharpier.Tests/FormattingTests/BaseTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ PrinterOptions printerOptions
CancellationToken.None
);

result.CompilationErrors.Should().BeEmpty();
result.ErrorDiagnostics.Should().BeEmpty();
result.FailureMessage.Should().BeEmpty();
result.WarningMessage.Should().BeEmpty();

Expand Down
Loading
Loading