Skip to content

Commit b6a4516

Browse files
Merge pull request #338 from kindermannhubert/improvedHelp
Improved and colorized help output + code quality improvements.
2 parents 51230d1 + 9746e7f commit b6a4516

File tree

56 files changed

+265
-259
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+265
-259
lines changed

CSharpRepl.Services/Configuration.cs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -37,11 +37,11 @@ public sealed class Configuration
3737
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ??
3838
Environment.CurrentDirectory;
3939

40-
public static readonly IReadOnlyCollection<string> SymbolServers = new[]
41-
{
40+
public static readonly IReadOnlyCollection<string> SymbolServers =
41+
[
4242
"https://symbols.nuget.org/download/symbols/",
4343
"http://msdl.microsoft.com/download/symbols/"
44-
};
44+
];
4545

4646
public HashSet<string> References { get; }
4747
public HashSet<string> Usings { get; }
@@ -84,8 +84,8 @@ public Configuration(
8484
OpenAIConfiguration? openAIConfiguration = null,
8585
string? cultureName = null)
8686
{
87-
References = references?.ToHashSet() ?? new HashSet<string>();
88-
Usings = usings?.ToHashSet() ?? new HashSet<string>();
87+
References = references?.ToHashSet() ?? [];
88+
Usings = usings?.ToHashSet() ?? [];
8989
Framework = framework ?? FrameworkDefault;
9090
Trace = trace;
9191
UseTerminalPaletteTheme = useTerminalPaletteTheme;
@@ -136,7 +136,7 @@ public Configuration(
136136
StreamPipedInput = streamPipedInput;
137137
TabSize = tabSize;
138138
LoadScript = loadScript;
139-
LoadScriptArgs = loadScriptArgs ?? Array.Empty<string>();
139+
LoadScriptArgs = loadScriptArgs ?? [];
140140
OutputForEarlyExit = outputForEarlyExit;
141141
OpenAIConfiguration = openAIConfiguration;
142142
var triggerCompletionList =
@@ -148,19 +148,19 @@ public Configuration(
148148

149149
if (submitPromptKeyPatterns?.Any() != true)
150150
{
151-
submitPromptKeyPatterns = new[] { "Enter" };
151+
submitPromptKeyPatterns = ["Enter"];
152152
}
153153
if (submitPromptDetailedKeyPatterns?.Any() != true)
154154
{
155-
submitPromptDetailedKeyPatterns = new[] { "Ctrl+Enter", "Ctrl+Alt+Enter" };
155+
submitPromptDetailedKeyPatterns = ["Ctrl+Enter", "Ctrl+Alt+Enter"];
156156
}
157157

158158
var submitPrompt = ParseKeyPressPatterns(submitPromptKeyPatterns.Concat(submitPromptDetailedKeyPatterns).ToArray());
159159
SubmitPromptDetailedKeys = ParseKeyPressPatterns(submitPromptDetailedKeyPatterns);
160160

161161
var commitCompletion = new KeyPressPatterns(
162162
CompletionRules.Default.DefaultCommitCharacters.Select(c => new KeyPressPattern(c))
163-
.Concat(new KeyPressPattern[] { new(ConsoleKey.Enter), new(ConsoleKey.Tab) })
163+
.Concat([new(ConsoleKey.Enter), new(ConsoleKey.Tab)])
164164
.ToArray());
165165

166166
KeyBindings = new(

CSharpRepl.Services/Disassembly/Disassembler.cs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ public Disassembler(CSharpCompilationOptions compilationOptions, AssemblyReferen
3535
this.referenceService = referenceService;
3636

3737
// we will try to compile the user's code several different ways. The first one that succeeds will be used.
38-
this.compilers = new (string name, CompileDelegate compile)[]
39-
{
38+
this.compilers =
39+
[
4040
// "console application" will work for standalone statements, due to C#'s top-level statement feature.
4141
(name: "Console Application (with top-level statements)",
4242
compile: (code, optimizationLevel) => Compile(code, optimizationLevel, OutputKind.ConsoleApplication)),
@@ -46,7 +46,7 @@ public Disassembler(CSharpCompilationOptions compilationOptions, AssemblyReferen
4646
// Compiling as a script will work for most other cases, but it's quite verbose so we use it as a last resort.
4747
(name: "Scripting session (will be overly verbose)",
4848
compile: (code, optimizationLevel) => scriptRunner.CompileTransient(code, optimizationLevel))
49-
};
49+
];
5050
}
5151

5252
public EvaluationResult Disassemble(string code, bool debugMode)
@@ -88,7 +88,7 @@ public EvaluationResult Disassemble(string code, bool debugMode)
8888
.Select(line => line.TrimEnd()) // output has trailing spaces on some lines, clean those up
8989
)
9090
+ string.Join('\n', commentFooter);
91-
return new EvaluationResult.Success(code, ilCode, Array.Empty<MetadataReference>());
91+
return new EvaluationResult.Success(code, ilCode, []);
9292
}
9393

9494
// failure, we couldn't compile it, move on to the next compiler configuration.
@@ -118,7 +118,7 @@ private static PlainTextOutput DisassembleFile(PEFile file)
118118
var asmReader = asm.GetMetadataReader();
119119
var definedTypes = asmReader.TypeDefinitions.ToArray();
120120
var definedTypeNames = definedTypes.Select(t => asmReader.GetString(asmReader.GetTypeDefinition(t).Name)).ToArray();
121-
if (definedTypeNames.Except(new[] { "<Module>", "Program", "RefSafetyRulesAttribute", "EmbeddedAttribute" }).Any())
121+
if (definedTypeNames.Except(["<Module>", "Program", "RefSafetyRulesAttribute", "EmbeddedAttribute"]).Any())
122122
{
123123
new ReflectionDisassembler(ilCodeOutput, CancellationToken.None).WriteModuleContents(file); // writes to the "ilCodeOutput" variable
124124
return ilCodeOutput;
@@ -133,7 +133,7 @@ private static PlainTextOutput DisassembleFile(PEFile file)
133133
var programType = asmReader.GetTypeDefinition(definedTypes[programTypeIndex]);
134134
var methods = programType.GetMethods().ToArray();
135135
var methodNames = methods.Select(m => asmReader.GetString(asmReader.GetMethodDefinition(m).Name)).ToArray();
136-
if (methodNames.Except(new[] { "<Main>$", ".ctor" }).Any())
136+
if (methodNames.Except(["<Main>$", ".ctor"]).Any())
137137
{
138138
return DisassembleAll(file, ilCodeOutput);
139139
}
@@ -153,7 +153,7 @@ private Compilation Compile(string code, OptimizationLevel optimizationLevel, Ou
153153
{
154154
var ast = CSharpSyntaxTree.ParseText(code, new CSharpParseOptions(LanguageVersion.Latest));
155155
var compilation = CSharpCompilation.Create("CompilationForDisassembly",
156-
new[] { ast },
156+
[ast],
157157
referenceService.LoadedReferenceAssemblies,
158158
compilationOptions
159159
.WithOutputKind(outputKind)

CSharpRepl.Services/Dotnet/DotnetBuilder.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public DotnetBuilder(IConsoleEx console)
3636

3737
private Process StartBuild(string path, out List<string> output)
3838
{
39-
output = new List<string>();
39+
output = [];
4040
var process = new Process
4141
{
4242
StartInfo =

CSharpRepl.Services/Extensions/KeyExtensions.cs

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,15 +6,14 @@ namespace CSharpRepl.Services.Extensions;
66

77
public static class KeyExtensions
88
{
9-
private static string GetStringValue(this KeyPressPattern pattern)
9+
public static string GetStringValue(this KeyPressPattern pattern)
1010
{
1111
if (pattern.Key != default)
1212
{
1313
return pattern.Modifiers == default
1414
? $"{pattern.Key}"
1515
: $"{pattern.Modifiers.GetStringValue()}+{pattern.Key}";
1616
}
17-
1817
return $"{pattern.Character}";
1918
}
2019

@@ -26,7 +25,4 @@ private static string GetStringValue(this ConsoleModifiers modifiers)
2625
.Select(x => x.ToString());
2726
return string.Join("+", values);
2827
}
29-
30-
public static string GetStringValue(this KeyPressPatterns patterns)
31-
=> patterns.DefinedPatterns!.First().GetStringValue();
3228
}

CSharpRepl.Services/Nuget/ConsoleNugetLogger.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ internal sealed class ConsoleNugetLogger : ILogger
2525
private readonly Configuration configuration;
2626
private readonly string successPrefix;
2727
private readonly string errorPrefix;
28-
private readonly List<Line> lines = new();
28+
private readonly List<Line> lines = [];
2929
private readonly object linesLock = new(); // Lock for the lines list
3030
private int linesRendered;
3131

@@ -83,7 +83,7 @@ public void LogMinimal(string data)
8383

8484
public void LogError(string data)
8585
{
86-
lock(linesLock)
86+
lock (linesLock)
8787
{
8888
lines.Add(CreateLine(data, isError: true));
8989
}

CSharpRepl.Services/Nuget/NugetHelper.cs

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
44

55
using System;
6+
using System.Diagnostics.CodeAnalysis;
67
using System.IO;
78
using System.Reflection;
89
using System.Runtime.Versioning;
@@ -31,7 +32,7 @@ public static RuntimeGraph GetRuntimeGraph(Action<string>? error)
3132
return new RuntimeGraph();
3233
}
3334

34-
public static NuGetFramework GetCurrentFramework()
35+
public static bool TryGetCurrentFramework([NotNullWhen(true)] out NuGetFramework? result)
3536
{
3637
var assembly = Assembly.GetEntryAssembly();
3738
if (assembly is null ||
@@ -41,6 +42,13 @@ public static NuGetFramework GetCurrentFramework()
4142
}
4243

4344
var targetFrameworkAttribute = assembly.GetCustomAttribute<TargetFrameworkAttribute>();
44-
return NuGetFramework.Parse(targetFrameworkAttribute?.FrameworkName);
45+
if (targetFrameworkAttribute is null)
46+
{
47+
result = null;
48+
return false;
49+
}
50+
51+
result = NuGetFramework.Parse(targetFrameworkAttribute.FrameworkName);
52+
return true;
4553
}
4654
}

CSharpRepl.Services/Nuget/NugetPackageInstaller.cs

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
using System;
66
using System.Collections.Generic;
77
using System.Collections.Immutable;
8-
using System.Globalization;
98
using System.IO;
109
using System.Linq;
1110
using System.Runtime.InteropServices;
@@ -51,9 +50,14 @@ public async Task<ImmutableArray<PortableExecutableReference>> InstallAsync(
5150

5251
try
5352
{
54-
ISettings settings = ReadSettings();
55-
var targetFramework = NugetHelper.GetCurrentFramework();
53+
if (!NugetHelper.TryGetCurrentFramework(out var targetFramework))
54+
{
55+
logger.LogFinish($"Unable to get current target framework.", success: false);
56+
return [];
57+
}
58+
5659
var nuGetProject = CreateFolderProject(targetFramework, Path.Combine(Configuration.ApplicationDirectory, "packages"));
60+
var settings = ReadSettings();
5761
var sourceRepositoryProvider = new SourceRepositoryProvider(new PackageSourceProvider(settings), Repository.Provider.GetCoreV3());
5862
var packageManager = CreatePackageManager(settings, nuGetProject, sourceRepositoryProvider);
5963

@@ -74,7 +78,7 @@ public async Task<ImmutableArray<PortableExecutableReference>> InstallAsync(
7478
if (!packageIdentity.HasVersion)
7579
{
7680
logger.LogFinish($"Could not find package '{packageIdentity}'", success: false);
77-
return ImmutableArray<PortableExecutableReference>.Empty;
81+
return [];
7882
}
7983

8084
var skipInstall = nuGetProject.PackageExists(packageIdentity);
@@ -100,7 +104,7 @@ public async Task<ImmutableArray<PortableExecutableReference>> InstallAsync(
100104
catch (Exception ex)
101105
{
102106
logger.LogFinish($"Could not find package '{packageId}'. Error: {ex}", success: false);
103-
return ImmutableArray<PortableExecutableReference>.Empty;
107+
return [];
104108
}
105109
}
106110

@@ -161,7 +165,7 @@ string[] FindDlls(NuGetFramework framework) =>
161165
.Select(i => i.Path)
162166
.Where(p => p.EndsWith(".dll", StringComparison.OrdinalIgnoreCase))
163167
.ToArray()
164-
?? Array.Empty<string>();
168+
?? [];
165169

166170
var supportedFrameworks = (await reader.GetSupportedFrameworksAsync(cancellationToken))
167171
.Where(f => FindDlls(f).Any()) //Not all supported frameworks contains dlls. E.g. Microsoft.CSharp.4.7.0\lib\netcoreapp2.0 contains only empty file '_._'.
@@ -230,7 +234,7 @@ private async Task DownloadPackageAsync(
230234

231235
await packageManager.InstallPackageAsync(packageManager.PackagesFolderNuGetProject,
232236
packageIdentity, resolutionContext, projectContext,
233-
primarySourceRepositories, Array.Empty<SourceRepository>(), cancellationToken);
237+
primarySourceRepositories, [], cancellationToken);
234238
}
235239

236240
private async Task<PackageIdentity> QueryLatestPackageVersion(

CSharpRepl.Services/Roslyn/DocumentationComment.cs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -26,9 +26,9 @@ internal sealed class DocumentationComment
2626
{
2727
private static readonly ThreadLocal<StringBuilder> stringBuilder = new(() => new());
2828

29-
private readonly Dictionary<string, FormattedString> _parameterTexts = new();
30-
private readonly Dictionary<string, FormattedString> _typeParameterTexts = new();
31-
private readonly Dictionary<string, ImmutableArray<FormattedString>> _exceptionTexts = new();
29+
private readonly Dictionary<string, FormattedString> _parameterTexts = [];
30+
private readonly Dictionary<string, FormattedString> _typeParameterTexts = [];
31+
private readonly Dictionary<string, ImmutableArray<FormattedString>> _exceptionTexts = [];
3232

3333
/// <summary>
3434
/// True if an error occurred when parsing.
@@ -68,17 +68,17 @@ internal sealed class DocumentationComment
6868
/// <summary>
6969
/// The names of items in &lt;param&gt; tags.
7070
/// </summary>
71-
public ImmutableArray<string> ParameterNames { get; private set; } = ImmutableArray<string>.Empty;
71+
public ImmutableArray<string> ParameterNames { get; private set; } = [];
7272

7373
/// <summary>
7474
/// The names of items in &lt;typeparam&gt; tags.
7575
/// </summary>
76-
public ImmutableArray<string> TypeParameterNames { get; private set; } = ImmutableArray<string>.Empty;
76+
public ImmutableArray<string> TypeParameterNames { get; private set; } = [];
7777

7878
/// <summary>
7979
/// The types of items in &lt;exception&gt; tags.
8080
/// </summary>
81-
public ImmutableArray<string> ExceptionTypes { get; private set; } = ImmutableArray<string>.Empty;
81+
public ImmutableArray<string> ExceptionTypes { get; private set; } = [];
8282

8383
/// <summary>
8484
/// The item named in the &lt;completionlist&gt; tag's cref attribute.
@@ -89,7 +89,7 @@ internal sealed class DocumentationComment
8989
/// <summary>
9090
/// Used for <see cref="CommentBuilder.TrimEachLine"/> method, to prevent new allocation of string
9191
/// </summary>
92-
private static readonly string[] s_NewLineAsStringArray = new string[] { "\n" };
92+
private static readonly string[] s_NewLineAsStringArray = ["\n"];
9393

9494
private DocumentationComment(string fullXmlFragment)
9595
{
@@ -175,9 +175,9 @@ private DocumentationComment ParseInternal(string xml)
175175
}
176176
}
177177

178-
_comment.ParameterNames = _parameterNamesBuilder == null ? ImmutableArray<string>.Empty : _parameterNamesBuilder.ToImmutable();
179-
_comment.TypeParameterNames = _typeParameterNamesBuilder == null ? ImmutableArray<string>.Empty : _typeParameterNamesBuilder.ToImmutable();
180-
_comment.ExceptionTypes = _exceptionTypesBuilder == null ? ImmutableArray<string>.Empty : _exceptionTypesBuilder.ToImmutable();
178+
_comment.ParameterNames = _parameterNamesBuilder == null ? [] : _parameterNamesBuilder.ToImmutable();
179+
_comment.TypeParameterNames = _typeParameterNamesBuilder == null ? [] : _typeParameterNamesBuilder.ToImmutable();
180+
_comment.ExceptionTypes = _exceptionTypesBuilder == null ? [] : _exceptionTypesBuilder.ToImmutable();
181181

182182
return _comment;
183183
}
@@ -314,7 +314,7 @@ private void ParseCallback(XmlReader reader)
314314
if (_exceptionTextBuilders == null || !_exceptionTextBuilders.ContainsKey(type))
315315
{
316316
(_exceptionTypesBuilder ??= ImmutableArray.CreateBuilder<string>()).Add(type);
317-
(_exceptionTextBuilders ??= new Dictionary<string, ImmutableArray<FormattedString>.Builder>()).Add(type, ImmutableArray.CreateBuilder<FormattedString>());
317+
(_exceptionTextBuilders ??= []).Add(type, ImmutableArray.CreateBuilder<FormattedString>());
318318
}
319319

320320
_exceptionTextBuilders[type].Add(exceptionText);

CSharpRepl.Services/Roslyn/Formatting/CustomObjectFormatters/GuidFormatter.cs

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,7 @@ public override StyledString FormatToText(Guid value, Level level, Formatter for
2020
var parts = value.ToString().Split('-');
2121
var style = formatter.GetStyle(ClassificationTypeNames.NumericLiteral);
2222
return new StyledString(
23-
new StyledStringSegment[]
24-
{
23+
[
2524
new(parts[0], style),
2625
new("-"),
2726
new(parts[1], style),
@@ -31,6 +30,6 @@ public override StyledString FormatToText(Guid value, Level level, Formatter for
3130
new(parts[3], style),
3231
new("-"),
3332
new(parts[4], style)
34-
});
33+
]);
3534
}
3635
}

CSharpRepl.Services/Roslyn/Formatting/FormattedObject.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public FormattedObject(IRenderable renderable, object? value)
1717

1818
public IEnumerable<FormattedObject> FormatMembers(PrettyPrinter prettyPrinter, Level level, bool includeNonPublic)
1919
{
20-
if (Value is null) return Array.Empty<FormattedObject>();
20+
if (Value is null) return [];
2121

2222
return prettyPrinter.FormatMembers(Value, level.Increment(), includeNonPublic);
2323
}

0 commit comments

Comments
 (0)