Skip to content
Open
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
19 changes: 19 additions & 0 deletions src/System.CommandLine.Tests/RootCommandTests.cs
Original file line number Diff line number Diff line change
@@ -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;

Expand Down Expand Up @@ -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<string>()).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 })!;
}
}
5 changes: 4 additions & 1 deletion src/System.CommandLine/RootCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,10 @@ public static string ExecutableName
/// <summary>
/// The path to the currently running executable.
/// </summary>
public static string ExecutablePath => _executablePath ??= Environment.GetCommandLineArgs()[0];
public static string ExecutablePath => _executablePath ??= GetExecutablePath(Environment.GetCommandLineArgs());

private static string GetExecutablePath(IReadOnlyList<string> commandLineArgs)
=> commandLineArgs.Count > 0 ? commandLineArgs[0] : string.Empty;

private static string? ToolCommandName
{
Expand Down