Skip to content

Commit

Permalink
toss in some more analyzers
Browse files Browse the repository at this point in the history
  • Loading branch information
belav committed Dec 26, 2024
1 parent 3fec3fc commit 0f20247
Show file tree
Hide file tree
Showing 40 changed files with 168 additions and 324 deletions.
26 changes: 25 additions & 1 deletion .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,31 @@
indent_size = 2
indent_style = space

csharp_using_directive_placement = outside_namespace
csharp_style_inlined_variable_declaration = true
csharp_style_pattern_matching_over_is_with_cast_check = true
csharp_style_var_elsewhere = true
csharp_style_var_for_built_in_types = true
csharp_style_var_when_type_is_apparent = true

[*.{cs,vb}]
dotnet_diagnostic.RS0041.severity = warning
dotnet_diagnostic.IDE0007.severity = warning
dotnet_diagnostic.IDE0018.severity = warning
dotnet_diagnostic.IDE0019.severity = warning
dotnet_diagnostic.IDE0020.severity = warning
dotnet_diagnostic.IDE0029.severity = warning
dotnet_diagnostic.IDE0030.severity = warning
dotnet_diagnostic.IDE0031.severity = warning
dotnet_diagnostic.IDE0032.severity = warning
dotnet_diagnostic.IDE0036.severity = warning
dotnet_diagnostic.IDE0038.severity = warning
dotnet_diagnostic.IDE0065.severity = warning
csharp_using_directive_placement = outside_namespace
dotnet_diagnostic.IDE0075.severity = warning
dotnet_diagnostic.IDE0078.severity = warning
dotnet_diagnostic.IDE0150.severity = warning
dotnet_diagnostic.IDE0290.severity = warning
dotnet_diagnostic.IDE0300.severity = warning
dotnet_diagnostic.IDE0301.severity = warning


39 changes: 15 additions & 24 deletions Src/CSharpier.Cli/CommandLineOptions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ namespace CSharpier.Cli;

internal class CommandLineOptions
{
public string[] DirectoryOrFilePaths { get; init; } = Array.Empty<string>();
public string[] DirectoryOrFilePaths { get; init; } = [];
public bool Check { get; init; }
public bool Fast { get; init; }
public bool SkipWrite { get; init; }
Expand All @@ -16,7 +16,7 @@ internal class CommandLineOptions
public bool IncludeGenerated { get; init; }
public string? StandardInFileContents { get; init; }
public string? ConfigPath { get; init; }
public string[] OriginalDirectoryOrFilePaths { get; init; } = Array.Empty<string>();
public string[] OriginalDirectoryOrFilePaths { get; init; } = [];

internal delegate Task<int> Handler(
string[] directoryOrFile,
Expand Down Expand Up @@ -46,57 +46,48 @@ public static RootCommand Create()
Description =
"One or more paths to a directory containing C# files to format or a C# file to format. It may be ommited when piping data via stdin.",
}.LegalFilePathsOnly(),
new Option(
new[] { "--check" },
"Check that files are formatted. Will not write any changes."
),
new Option(["--check"], "Check that files are formatted. Will not write any changes."),
new Option<string>(
new[] { "--loglevel" },
["--loglevel"],
() => LogLevel.Information.ToString(),
"Specify the log level - Debug, Information (default), Warning, Error, None"
),
new Option(
new[] { "--no-cache" },
["--no-cache"],
"Bypass the cache to determine if a file needs to be formatted."
),
new Option(
new[] { "--no-msbuild-check" },
["--no-msbuild-check"],
"Bypass the check to determine if a csproj files references a different version of CSharpier.MsBuild."
),
new Option(
new[] { "--include-generated" },
["--include-generated"],
"Include files generated by the SDK and files that begin with <autogenerated /> comments"
),
new Option(
new[] { "--fast" },
["--fast"],
"Skip comparing syntax tree of formatted file to original file to validate changes."
),
new Option(
new[] { "--skip-write" },
["--skip-write"],
"Skip writing changes. Generally used for testing to ensure csharpier doesn't throw any errors or cause syntax tree validation failures."
),
new Option(["--write-stdout"], "Write the results of formatting any files to stdout."),
new Option(
new[] { "--write-stdout" },
"Write the results of formatting any files to stdout."
),
new Option(
new[] { "--pipe-multiple-files" },
["--pipe-multiple-files"],
"Keep csharpier running so that multiples files can be piped to it via stdin."
),
new Option(
new[] { "--server" },
["--server"],
"Run CSharpier as a server so that multiple files may be formatted."
),
new Option<int?>(
new[] { "--server-port" },
["--server-port"],
"Specify the port that CSharpier should start on. Defaults to a random unused port."
),
new Option<string>(
new[] { "--config-path" },
"Path to the CSharpier configuration file"
),
new Option<string>(["--config-path"], "Path to the CSharpier configuration file"),
new Option(
new[] { "--compilation-errors-as-warnings" },
["--compilation-errors-as-warnings"],
"Treat compilation errors from files as warnings instead of errors."
),
};
Expand Down
25 changes: 8 additions & 17 deletions Src/CSharpier.Cli/ConsoleLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,10 @@

namespace CSharpier.Cli;

internal class ConsoleLogger : ILogger
internal class ConsoleLogger(IConsole console, LogLevel loggingLevel) : ILogger
{
private static readonly object ConsoleLock = new();

private readonly IConsole console;
private readonly LogLevel loggingLevel;

public ConsoleLogger(IConsole console, LogLevel loggingLevel)
{
this.console = console;
this.loggingLevel = loggingLevel;
}

public virtual void Log<TState>(
LogLevel logLevel,
EventId eventId,
Expand All @@ -23,7 +14,7 @@ public virtual void Log<TState>(
Func<TState, Exception, string> formatter
)
{
if (logLevel < this.loggingLevel)
if (logLevel < loggingLevel)
{
return;
}
Expand All @@ -32,23 +23,23 @@ void Write(string value)
{
if (logLevel >= LogLevel.Error)
{
this.console.WriteError(value);
console.WriteError(value);
}
else
{
this.console.Write(value);
console.Write(value);
}
}

void WriteLine(string? value = null)
{
if (logLevel >= LogLevel.Error)
{
this.console.WriteErrorLine(value);
console.WriteErrorLine(value);
}
else
{
this.console.WriteLine(value);
console.WriteLine(value);
}
}

Expand All @@ -63,9 +54,9 @@ void WriteLine(string? value = null)

if (logLevel >= LogLevel.Warning)
{
this.console.ForegroundColor = GetColorLevel(logLevel);
console.ForegroundColor = GetColorLevel(logLevel);
Write($"{logLevel} ");
this.console.ResetColor();
console.ResetColor();
}

var stringReader = new StringReader(message);
Expand Down
34 changes: 13 additions & 21 deletions Src/CSharpier.Cli/EditorConfig/GlobMatcher.cs
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,8 @@ private GlobMatcher(
this.myEmpty = empty;
}

private static readonly char[] ourUnixPathSeparators = { '/' };
private static readonly char[] ourWinPathSeparators = { '/', '\\' };
private static readonly char[] ourUnixPathSeparators = ['/'];
private static readonly char[] ourWinPathSeparators = ['/', '\\'];

///<summary>Checks whether a given string matches this pattern.</summary>
public bool IsMatch(string input)
Expand Down Expand Up @@ -646,7 +646,7 @@ public void Build()
for (var i = 0; i < this.Count; i++)
{
var item = this[i];
if (item is PathSeparator || item is DoubleAsterisk)
if (item is PathSeparator or DoubleAsterisk)
{
this.HasPathSeparators = true;
}
Expand Down Expand Up @@ -697,27 +697,19 @@ public void Build()

private interface IPatternElement { }

private class Literal : IPatternElement
private class Literal(string source) : IPatternElement
{
public Literal(string source) => this.Source = source;

public string Source { get; }
public string Source { get; } = source;
}

private class OneChar : IPatternElement
private class OneChar(string possibleChars, bool negate) : IPatternElement
{
static OneChar() { }

public static readonly OneChar EmptyInstance = new OneChar(null, false);

public OneChar(string possibleChars, bool negate)
{
this.PossibleChars = possibleChars;
this.Negate = negate;
}

private string PossibleChars { get; }
private bool Negate { get; }
private string PossibleChars { get; } = possibleChars;
private bool Negate { get; } = negate;

public bool CheckChar(GlobMatcherOptions options, char c, StringComparison comparison)
{
Expand Down Expand Up @@ -848,7 +840,7 @@ private static IList<string> BraceExpand(string pattern, GlobMatcherOptions opti
if (options.NoBrace || !ourHasBraces.IsMatch(pattern))
{
// shortcut. no need to expand.
return new[] { pattern };
return [pattern];
}

var escaping = false;
Expand Down Expand Up @@ -894,7 +886,7 @@ private static IList<string> BraceExpand(string pattern, GlobMatcherOptions opti
if (prefix == null)
{
// console.error("no sets")
return new[] { pattern };
return [pattern];
}

var braceExpand = BraceExpand(pattern.Substring(i), options);
Expand Down Expand Up @@ -1051,7 +1043,7 @@ private static IList<string> BraceExpand(string pattern, GlobMatcherOptions opti
private static PatternCase Parse(GlobMatcherOptions options, string pattern)
{
if (pattern == "")
return new PatternCase();
return [];

var result = new PatternCase();
var sb = new StringBuilder();
Expand Down Expand Up @@ -1123,7 +1115,7 @@ void AppendChar(char c1)

FinishLiteral();

if (!(result.LastOrDefault() is PathSeparator))
if (result.LastOrDefault() is not PathSeparator)
{
result.Add(PathSeparator.Instance);
}
Expand Down Expand Up @@ -1175,7 +1167,7 @@ void AppendChar(char c1)
result.RemoveAt(result.Count - 1);
result.Add(new DoubleAsterisk());
}
else if (!(result.LastOrDefault() is SimpleAsterisk))
else if (result.LastOrDefault() is not SimpleAsterisk)
{
result.Add(new SimpleAsterisk());
}
Expand Down
27 changes: 8 additions & 19 deletions Src/CSharpier.Cli/EditorConfig/Section.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,27 +2,16 @@

namespace CSharpier.Cli.EditorConfig;

internal class Section
internal class Section(SectionData section, string directory)
{
private readonly GlobMatcher matcher;
private readonly GlobMatcher matcher = Globber.Create(section.SectionName, directory);

public string? IndentStyle { get; }
public string? IndentSize { get; }
public string? TabWidth { get; }
public string? MaxLineLength { get; }
public string? EndOfLine { get; }
public string? Formatter { get; }

public Section(SectionData section, string directory)
{
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"];
this.MaxLineLength = section.Keys["max_line_length"];
this.EndOfLine = section.Keys["end_of_line"];
this.Formatter = section.Keys["csharpier_formatter"];
}
public string? IndentStyle { get; } = section.Keys["indent_style"];
public string? IndentSize { get; } = section.Keys["indent_size"];
public string? TabWidth { get; } = section.Keys["tab_width"];
public string? MaxLineLength { get; } = section.Keys["max_line_length"];
public string? EndOfLine { get; } = section.Keys["end_of_line"];
public string? Formatter { get; } = section.Keys["csharpier_formatter"];

public bool IsMatch(string fileName)
{
Expand Down
17 changes: 4 additions & 13 deletions Src/CSharpier.Cli/FileIssueLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,20 @@

namespace CSharpier.Cli;

internal class FileIssueLogger
internal class FileIssueLogger(string filePath, ILogger logger)
{
private readonly string filePath;
private readonly ILogger logger;

public FileIssueLogger(string filePath, ILogger logger)
{
this.filePath = filePath;
this.logger = logger;
}

public void WriteError(string value, Exception? exception = null)
{
this.logger.LogError(exception, $"{this.GetPath()} - {value}");
logger.LogError(exception, $"{this.GetPath()} - {value}");
}

public void WriteWarning(string value)
{
this.logger.LogWarning($"{this.GetPath()} - {value}");
logger.LogWarning($"{this.GetPath()} - {value}");
}

private string GetPath()
{
return this.filePath;
return filePath;
}
}
Loading

0 comments on commit 0f20247

Please sign in to comment.