diff --git a/src/System.CommandLine.Tests/RootCommandTests.cs b/src/System.CommandLine.Tests/RootCommandTests.cs index d5be20a34d..8dff7c4051 100644 --- a/src/System.CommandLine.Tests/RootCommandTests.cs +++ b/src/System.CommandLine.Tests/RootCommandTests.cs @@ -1,6 +1,8 @@ // Copyright (c) .NET Foundation and contributors. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System; +using System.Reflection; using FluentAssertions; using Xunit; @@ -48,5 +50,22 @@ public void Setting_HelpName_does_not_change_Name() rootCommand.Name.Should().Be(RootCommand.ExecutableName); } + + [Fact] + public void ExecutablePath_falls_back_to_empty_string_when_command_line_args_are_empty() + { + GetExecutablePath(Array.Empty()).Should().Be(""); + } + + [Fact] + public void ExecutablePath_uses_first_command_line_arg() + { + GetExecutablePath(new[] { "my-tool", "--help" }).Should().Be("my-tool"); + } + + private static string GetExecutablePath(string[] commandLineArgs) + => (string)typeof(RootCommand) + .GetMethod("GetExecutablePath", BindingFlags.NonPublic | BindingFlags.Static)! + .Invoke(null, new object[] { commandLineArgs })!; } } diff --git a/src/System.CommandLine/RootCommand.cs b/src/System.CommandLine/RootCommand.cs index b9172510f1..caf45e18be 100644 --- a/src/System.CommandLine/RootCommand.cs +++ b/src/System.CommandLine/RootCommand.cs @@ -74,7 +74,10 @@ public static string ExecutableName /// /// The path to the currently running executable. /// - public static string ExecutablePath => _executablePath ??= Environment.GetCommandLineArgs()[0]; + public static string ExecutablePath => _executablePath ??= GetExecutablePath(Environment.GetCommandLineArgs()); + + private static string GetExecutablePath(IReadOnlyList commandLineArgs) + => commandLineArgs.Count > 0 ? commandLineArgs[0] : string.Empty; private static string? ToolCommandName {