Skip to content

Commit ffb7b78

Browse files
authored
Merge pull request #290 from dotnet/remove-static-argv-access
Rip out the static ParseResult and instead compute a PR once and flow it through the command handlers
2 parents 243661f + 2b4495f commit ffb7b78

File tree

9 files changed

+57
-111
lines changed

9 files changed

+57
-111
lines changed

src/dotnet-core-uninstall/Shared/Commands/CommandBundleFilter.cs

Lines changed: 4 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -18,28 +18,8 @@ namespace Microsoft.DotNet.Tools.Uninstall.Shared.Commands
1818
{
1919
internal static class CommandBundleFilter
2020
{
21-
private static readonly Lazy<string> _assemblyVersion =
22-
new Lazy<string>(() =>
23-
{
24-
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
25-
var assemblyVersionAttribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
26-
if (assemblyVersionAttribute == null)
27-
{
28-
return assembly.GetName().Version.ToString();
29-
}
30-
else
31-
{
32-
return assemblyVersionAttribute.InformationalVersion;
33-
}
34-
});
35-
36-
public static IEnumerable<Bundle> GetFilteredBundles(IEnumerable<Bundle> allBundles, ParseResult parseResult = null)
21+
public static IEnumerable<Bundle> GetFilteredBundles(IEnumerable<Bundle> allBundles, ParseResult parseResult)
3722
{
38-
if (parseResult == null)
39-
{
40-
parseResult = CommandLineConfigs.CommandLineParseResult;
41-
}
42-
4323
var option = parseResult.CommandResult.GetUninstallMainOption();
4424
var typeSelection = parseResult.GetTypeSelection();
4525
var archSelection = parseResult.GetArchSelection();
@@ -52,7 +32,7 @@ public static IEnumerable<Bundle> GetFilteredBundles(IEnumerable<Bundle> allBund
5232
throw new RequiredArgMissingForUninstallCommandException();
5333
}
5434

55-
bundles = OptionFilterers.UninstallNoOptionFilterer.Filter(
35+
bundles = OptionFilterers.UninstallNoOptionFilterer.Filter(
5636
parseResult.CommandResult.Tokens.Select(t => t.Value),
5737
bundles,
5838
typeSelection,
@@ -79,24 +59,15 @@ public static IEnumerable<Bundle> GetFilteredBundles(IEnumerable<Bundle> allBund
7959
return bundles;
8060
}
8161

82-
public static IDictionary<Bundle, string> GetFilteredWithRequirementStrings(IBundleCollector bundleCollector)
62+
public static IDictionary<Bundle, string> GetFilteredWithRequirementStrings(IBundleCollector bundleCollector, ParseResult parseResult)
8363
{
8464
var allBundles = bundleCollector.GetAllInstalledBundles();
85-
var filteredBundles = GetFilteredBundles(allBundles);
65+
var filteredBundles = GetFilteredBundles(allBundles, parseResult);
8666
return VisualStudioSafeVersionsExtractor.GetReasonRequiredStrings(allBundles)
8767
.Where(pair => filteredBundles.Contains(pair.Key))
8868
.ToDictionary(i => i.Key, i => i.Value);
8969
}
9070

91-
public static void HandleVersionOption()
92-
{
93-
if (CommandLineConfigs.CommandLineParseResult.FindResultFor(CommandLineConfigs.VersionOption) != null)
94-
{
95-
Console.WriteLine(_assemblyVersion.Value);
96-
Environment.Exit(0);
97-
}
98-
}
99-
10071
private static IEnumerable<Bundle> FilterRequiredBundles(IEnumerable<Bundle> allBundles, IEnumerable<Token> tokens)
10172
{
10273
var explicitlyListedBundles = tokens

src/dotnet-core-uninstall/Shared/Commands/DryRunCommandExec.cs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,29 +7,28 @@
77
using System.Linq;
88
using Microsoft.DotNet.Tools.Uninstall.Shared.Utils;
99
using Microsoft.DotNet.Tools.Uninstall.MacOs;
10+
using System.CommandLine.Parsing;
1011

1112
namespace Microsoft.DotNet.Tools.Uninstall.Shared.Commands
1213
{
1314
internal static class DryRunCommandExec
1415
{
15-
public static void Execute(IBundleCollector bundleCollector)
16+
public static void Execute(IBundleCollector bundleCollector, ParseResult parseResult)
1617
{
17-
CommandBundleFilter.HandleVersionOption();
18-
19-
var filtered = CommandBundleFilter.GetFilteredWithRequirementStrings(bundleCollector);
18+
var filtered = CommandBundleFilter.GetFilteredWithRequirementStrings(bundleCollector, parseResult);
2019
TryIt(filtered);
2120
}
2221

2322
private static void TryIt(IDictionary<Bundle, string> bundles)
2423
{
2524
var displayNames = string.Join("\n", bundles.Select(bundle => $" {bundle.Key.DisplayName}"));
26-
Console.WriteLine(string.Format(RuntimeInfo.RunningOnWindows ?
25+
Console.WriteLine(string.Format(RuntimeInfo.RunningOnWindows ?
2726
LocalizableStrings.WindowsDryRunOutputFormat : LocalizableStrings.MacDryRunOutputFormat, displayNames));
2827

2928
foreach (var pair in bundles.Where(b => !b.Value.Equals(string.Empty)))
3029
{
3130
Console.ForegroundColor = ConsoleColor.Red;
32-
Console.Write(string.Format(RuntimeInfo.RunningOnWindows ? LocalizableStrings.WindowsRequiredBundleConfirmationPromptWarningFormat :
31+
Console.Write(string.Format(RuntimeInfo.RunningOnWindows ? LocalizableStrings.WindowsRequiredBundleConfirmationPromptWarningFormat :
3332
LocalizableStrings.MacRequiredBundleConfirmationPromptWarningFormat, pair.Key.DisplayName, pair.Value));
3433
Console.ResetColor();
3534
}

src/dotnet-core-uninstall/Shared/Commands/ListCommandExec.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ private static void Execute(
7070

7171
public static Dictionary<BundleTypePrintInfo, Dictionary<Bundle, string>> GetFilteredBundlesWithRequirements(
7272
IEnumerable<Bundle> bundles,
73-
IEnumerable<BundleTypePrintInfo> supportedBundleTypes,
73+
IEnumerable<BundleTypePrintInfo> supportedBundleTypes,
7474
ParseResult parseResult)
7575
{
7676
var uninstallMap = VisualStudioSafeVersionsExtractor.GetReasonRequiredStrings(bundles);

src/dotnet-core-uninstall/Shared/Commands/UninstallCommandExec.cs

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@
1515
using System.Runtime.InteropServices;
1616
using System.ComponentModel;
1717
using Microsoft.DotNet.Tools.Uninstall.MacOs;
18+
using System.CommandLine.Parsing;
1819

1920
namespace Microsoft.DotNet.Tools.Uninstall.Shared.Commands
2021
{
@@ -30,20 +31,19 @@ private static extern IntPtr CommandLineToArgvW(
3031
[MarshalAs(UnmanagedType.LPWStr)] string lpCmdLine,
3132
out int pNumArgs);
3233

33-
public static void Execute(IBundleCollector bundleCollector)
34+
public static void Execute(IBundleCollector bundleCollector, ParseResult parseResult)
3435
{
35-
CommandBundleFilter.HandleVersionOption();
36+
var filtered = CommandBundleFilter.GetFilteredWithRequirementStrings(bundleCollector, parseResult);
37+
var verbosity = parseResult.CommandResult.GetVerbosityLevel();
3638

37-
var filtered = CommandBundleFilter.GetFilteredWithRequirementStrings(bundleCollector);
38-
39-
if (CommandLineConfigs.CommandLineParseResult.FindResultFor(CommandLineConfigs.YesOption) != null)
39+
if (parseResult.FindResultFor(CommandLineConfigs.YesOption) != null)
4040
{
4141
if (!IsAdmin())
4242
{
4343
throw new NotAdminException();
4444
}
4545

46-
DoIt(filtered.Keys);
46+
DoIt(filtered.Keys, verbosity);
4747
}
4848
else
4949
{
@@ -56,15 +56,14 @@ public static void Execute(IBundleCollector bundleCollector)
5656
{
5757
if (AskWithWarningsForRequiredBundles(filtered))
5858
{
59-
DoIt(filtered.Keys);
59+
DoIt(filtered.Keys, verbosity);
6060
}
6161
}
6262
}
6363
}
6464

65-
private static void DoIt(IEnumerable<Bundle> bundles)
65+
private static void DoIt(IEnumerable<Bundle> bundles, VerbosityLevel verbosityLevel)
6666
{
67-
var verbosityLevel = CommandLineConfigs.CommandLineParseResult.CommandResult.GetVerbosityLevel();
6867
var verbosityLogger = new VerbosityLogger(verbosityLevel);
6968

7069
var canceled = false;
@@ -214,7 +213,7 @@ private static IEnumerable<string> ParseCommandToArgs(string command)
214213
public static bool AskItAndReturnUserAnswer(IDictionary<Bundle, string> bundles, string userResponse = null)
215214
{
216215
var displayNames = string.Join("\n", bundles.Select(bundle => $" {bundle.Key.DisplayName}"));
217-
Console.Write(string.Format(RuntimeInfo.RunningOnWindows ? LocalizableStrings.WindowsConfirmationPromptOutputFormat :
216+
Console.Write(string.Format(RuntimeInfo.RunningOnWindows ? LocalizableStrings.WindowsConfirmationPromptOutputFormat :
218217
LocalizableStrings.MacConfirmationPromptOutputFormat, displayNames));
219218

220219
var response = userResponse == null ? Console.ReadLine().Trim().ToUpper() : userResponse.ToUpper();
@@ -233,19 +232,19 @@ public static bool AskItAndReturnUserAnswer(IDictionary<Bundle, string> bundles,
233232
}
234233
}
235234

236-
public static bool AskWithWarningsForRequiredBundles(IDictionary<Bundle, string> bundles, string userResponse = null)
235+
public static bool AskWithWarningsForRequiredBundles(IDictionary<Bundle, string> bundles, string userResponse = null)
237236
{
238237
var requiredBundles = bundles.Where(b => !b.Value.Equals(string.Empty));
239238
foreach (var pair in requiredBundles)
240239
{
241240
Console.ForegroundColor = ConsoleColor.Red;
242-
Console.Write(string.Format(RuntimeInfo.RunningOnWindows ? LocalizableStrings.WindowsRequiredBundleConfirmationPromptOutputFormat :
241+
Console.Write(string.Format(RuntimeInfo.RunningOnWindows ? LocalizableStrings.WindowsRequiredBundleConfirmationPromptOutputFormat :
243242
LocalizableStrings.MacRequiredBundleConfirmationPromptOutputFormat, pair.Key.DisplayName, pair.Value));
244243
Console.ResetColor();
245244
var response = userResponse == null ? Console.ReadLine().Trim().ToUpper() : userResponse.ToUpper();
246245
if (response.Equals("N"))
247246
{
248-
return false ;
247+
return false;
249248
}
250249
else if (!(response.Equals("Y") || response.Equals("YES")))
251250
{

src/dotnet-core-uninstall/Shared/Configs/CommandLineConfigs.cs

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
using System.CommandLine.Invocation;
99
using System.CommandLine.Parsing;
1010
using System.Linq;
11+
using System.Reflection;
1112
using System.Runtime.InteropServices;
1213
using Microsoft.DotNet.Tools.Uninstall.MacOs;
1314
using Microsoft.DotNet.Tools.Uninstall.Shared.BundleInfo;
@@ -29,7 +30,7 @@ internal static class CommandLineConfigs
2930
private static readonly string RemoveCommandName = "remove";
3031

3132
public static readonly RootCommand UninstallRootCommand = new RootCommand(
32-
RuntimeInfo.RunningOnWindows ? LocalizableStrings.UninstallNoOptionDescriptionWindows
33+
RuntimeInfo.RunningOnWindows ? LocalizableStrings.UninstallNoOptionDescriptionWindows
3334
: LocalizableStrings.UninstallNoOptionDescriptionMac);
3435

3536
public static readonly Command ListCommand = new Command(
@@ -120,7 +121,7 @@ internal static class CommandLineConfigs
120121
$"--{X86OptionName}",
121122
LocalizableStrings.ListX86OptionDescription);
122123

123-
public static readonly Option VersionOption = new Option("--version")
124+
public static readonly Command VersionSubcommand = new Command("--version")
124125
{
125126
IsHidden = true
126127
};
@@ -171,11 +172,10 @@ internal static class CommandLineConfigs
171172
public static readonly Option[] AdditionalUninstallOptions = new Option[]
172173
{
173174
VerbosityOption,
174-
VersionOption,
175175
ForceOption
176176
};
177177

178-
public static readonly Dictionary<string, VerbosityLevel> VerbosityLevels = new Dictionary<string, VerbosityLevel>
178+
public static readonly Dictionary<string, VerbosityLevel> VerbosityLevels = new Dictionary<string, VerbosityLevel>
179179
{
180180
{ "q", VerbosityLevel.Quiet }, { "quiet", VerbosityLevel.Quiet },
181181
{ "m", VerbosityLevel.Minimal }, { "minimal", VerbosityLevel.Minimal },
@@ -184,19 +184,34 @@ internal static class CommandLineConfigs
184184
{ "diag", VerbosityLevel.Diagnostic }, { "diagnostic", VerbosityLevel.Diagnostic }
185185
};
186186

187-
public static ParseResult CommandLineParseResult;
188187
public static readonly IEnumerable<Option> RemoveAuxOptions;
189188
public static readonly IEnumerable<Option> DryRunAuxOptions;
190189
public static readonly IEnumerable<Option> WhatIfAuxOptions;
191190
public static readonly IEnumerable<Option> ListAuxOptions;
192191

193-
static CommandLineConfigs()
192+
private static readonly Lazy<string> _assemblyVersion =
193+
new Lazy<string>(() =>
194+
{
195+
var assembly = Assembly.GetEntryAssembly() ?? Assembly.GetExecutingAssembly();
196+
var assemblyVersionAttribute = assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>();
197+
if (assemblyVersionAttribute == null)
198+
{
199+
return assembly.GetName().Version.ToString();
200+
}
201+
else
202+
{
203+
return assemblyVersionAttribute.InformationalVersion;
204+
}
205+
});
206+
207+
static CommandLineConfigs()
194208
{
195209
DryRunCommand.AddAlias(WhatIfCommandName);
196210

197211
UninstallRootCommand.AddCommand(ListCommand);
198212
UninstallRootCommand.AddCommand(DryRunCommand);
199213
UninstallRootCommand.AddCommand(RemoveCommand);
214+
UninstallRootCommand.AddCommand(VersionSubcommand);
200215

201216
var supportedBundleTypeNames = SupportedBundleTypeConfigs.GetSupportedBundleTypes().Select(type => type.OptionName);
202217

@@ -233,15 +248,18 @@ static CommandLineConfigs()
233248
AssignOptionsToCommand(ListCommand, ListAuxOptions);
234249

235250
var bundleCollector = OperatingSystem.IsWindows() ? new RegistryQuery() as IBundleCollector : new FileSystemExplorer() as IBundleCollector;
236-
ListCommand.Handler = CommandHandler.Create(ExceptionHandler.HandleException(() => ListCommandExec.Execute(bundleCollector)));
237-
DryRunCommand.Handler = CommandHandler.Create(ExceptionHandler.HandleException(() => DryRunCommandExec.Execute(bundleCollector)));
238-
RemoveCommand.Handler = CommandHandler.Create(ExceptionHandler.HandleException(() => UninstallCommandExec.Execute(bundleCollector)));
251+
ListCommand.Handler = CommandHandler.Create(ExceptionHandler.HandleException((ParseResult parseResult) => ListCommandExec.Execute(bundleCollector)));
252+
DryRunCommand.Handler = CommandHandler.Create(ExceptionHandler.HandleException((ParseResult parseResult) => DryRunCommandExec.Execute(bundleCollector, parseResult)));
253+
RemoveCommand.Handler = CommandHandler.Create(ExceptionHandler.HandleException((ParseResult parseResult) => UninstallCommandExec.Execute(bundleCollector, parseResult)));
254+
VersionSubcommand.Handler = CommandHandler.Create(() =>
255+
{
256+
Console.WriteLine(_assemblyVersion.Value);
257+
});
239258

240259
UninstallCommandParser = new CommandLineBuilder(UninstallRootCommand)
241260
.UseDefaults()
242261
.UseHelpBuilder(context => new UninstallHelpBuilder(context.Console))
243262
.Build();
244-
CommandLineParseResult = UninstallCommandParser.Parse(Environment.GetCommandLineArgs());
245263
}
246264

247265
public static Option GetUninstallMainOption(this CommandResult commandResult)

src/dotnet-core-uninstall/Shared/Exceptions/ExceptionHandler.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@ namespace Microsoft.DotNet.Tools.Uninstall.Shared.Exceptions
77
{
88
internal static class ExceptionHandler
99
{
10-
public static Action HandleException(Action action)
10+
public static Action<T> HandleException<T>(Action<T> action)
1111
{
12-
return () =>
12+
return (x) =>
1313
{
1414
try
1515
{
16-
action.Invoke();
16+
action.Invoke(x);
1717
}
1818
catch (DotNetUninstallException e)
1919
{

src/redist/targets/GenerateLayout.targets

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
<_PublishSingleFileForRid Condition="'$(RID)' == 'win-x86'">false</_PublishSingleFileForRid>
77
<_GenerateLayoutDependsOnTargets>CleanLayoutPath;PublishDotnetCoreUninstallProject</_GenerateLayoutDependsOnTargets>
88
<_GenerateLayoutDependsOnTargets Condition="'$(RID)' == 'win-x86'">CleanLayoutPath;PublishDotnetCoreUninstallProject;SignLayout</_GenerateLayoutDependsOnTargets>
9+
910
</PropertyGroup>
1011

1112
<Target Name="CleanLayoutPath">

test/dotnet-core-uninstall.Tests/Shared/Configs/CommandLineConfigsTests.cs

Lines changed: 3 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ internal void TestListCommandReject(string command)
104104
[InlineData("--all-previews")]
105105
[InlineData("--all-previews-but-latest")]
106106
[InlineData("--major-minor", "2.2", "2.2")]
107-
[InlineData("", "2.2.300", new[] { "2.2.300" })]
107+
[InlineData("", "2.2.300", new[] { "2.2.300" })]
108108
[InlineData("", "2.2.300 3.0.100", new[] { "2.2.300", "3.0.100" })]
109109
[InlineData("", "--unknown-option", new[] { "--unknown-option" })]
110110
[InlineData("", "--unknown-option argument", new[] { "--unknown-option", "argument" })]
@@ -408,7 +408,7 @@ internal void TestOptionsRejectMacOs(string command)
408408
[InlineData("--all-previews")]
409409
[InlineData("--all-previews-but-latest")]
410410
[InlineData("--major-minor", "2.2")]
411-
[InlineData("", "2.2.300")]
411+
[InlineData("", "2.2.300")]
412412
[InlineData("", "2.2.300 3.0.100")]
413413
[InlineData("", "--unknown-option")]
414414
[InlineData("", "--unknown-option argument")]
@@ -419,7 +419,7 @@ internal void TestGetUninstallRemoveOptionAccept(string option, string argValue
419419
if (option.Equals(string.Empty))
420420
{
421421
commandResult.GetUninstallMainOption().Should().BeNull();
422-
}
422+
}
423423
else
424424
{
425425
commandResult.GetUninstallMainOption().Name
@@ -796,26 +796,5 @@ internal void TestGetVerbosityLevelVerbosityLevelInvalidException(string command
796796

797797
action.Should().Throw<VerbosityLevelInvalidException>(LocalizableStrings.VerbosityLevelInvalidExceptionMessage);
798798
}
799-
800-
[Theory]
801-
[InlineData("remove --version")]
802-
[InlineData("remove --all --sdk --version")]
803-
[InlineData("remove 2.2.300 --runtime --version")]
804-
[InlineData("remove --version 2.2.300 --runtime")]
805-
[InlineData("remove --version --major-minor 2.1")]
806-
[InlineData("remove --version --all-but 2.2.300 2.1.700")]
807-
[InlineData("remove 2.2.5 --runtime -y --version")]
808-
[InlineData("remove --version --sdk 2.2.300 2.1.700 --yes")]
809-
internal void TestVersionOption(string command)
810-
{
811-
var parseResult = CommandLineConfigs.UninstallRootCommand.Parse(command);
812-
813-
parseResult.Errors.Should().BeEmpty();
814-
parseResult.UnparsedTokens.Should().BeEmpty();
815-
parseResult.UnmatchedTokens.Should().BeEmpty();
816-
817-
parseResult.CommandResult.FindResultFor(CommandLineConfigs.VersionOption)
818-
.Should().NotBeNull();
819-
}
820799
}
821800
}

test/dotnet-core-uninstall.Tests/Shared/IntegrationTests/IntegrationTests.cs

Lines changed: 0 additions & 21 deletions
This file was deleted.

0 commit comments

Comments
 (0)