Skip to content

dotnet CLI: Add --cli-schema option for CLI structure JSON #49118

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
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
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.CommandLine;
using System.Reflection;

namespace Microsoft.DotNet.Cli.Utils.Extensions;

public static class ArgumentExtensions
{
private static readonly PropertyInfo[] s_nonPublicProperties = typeof(Argument).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);

public static bool? GetHasValidators(this Argument argument) =>
s_nonPublicProperties.First(pi => pi.Name == "HasValidators").GetValue(argument) as bool?;
}

27 changes: 27 additions & 0 deletions src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/CommandExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Reflection;

namespace Microsoft.DotNet.Cli.Utils.Extensions;

#pragma warning disable IDE0065 // Misplaced using directive
using Command = System.CommandLine.Command;
#pragma warning restore IDE0065 // Misplaced using directive
Comment on lines +8 to +10
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is bizarre but necessary since declaring the using above the namespace means that anything in the namespace scope will override it. Meaning, System.DotNet.Cli.Utils.Command will be used even if an alias is declared. So, you put the alias inside the namespace to have it be used properly.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TODO: We should just change that Command class to not be called Command since CliCommand from S.CL was changed back to Command, which causes situations like this to happen.


public static class CommandExtensions
{
private static readonly PropertyInfo[] s_nonPublicProperties = typeof(Command).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);

public static bool? GetHasArguments(this Command command) =>
s_nonPublicProperties.First(pi => pi.Name == "HasArguments").GetValue(command) as bool?;

public static bool? GetHasOptions(this Command command) =>
s_nonPublicProperties.First(pi => pi.Name == "HasOptions").GetValue(command) as bool?;

public static bool? GetHasSubcommands(this Command command) =>
s_nonPublicProperties.First(pi => pi.Name == "HasSubcommands").GetValue(command) as bool?;

public static bool? GetHasValidators(this Command command) =>
s_nonPublicProperties.First(pi => pi.Name == "HasValidators").GetValue(command) as bool?;
}
18 changes: 18 additions & 0 deletions src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/OptionExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.CommandLine;
using System.Reflection;

namespace Microsoft.DotNet.Cli.Utils.Extensions;

public static class OptionExtensions
{
private static readonly PropertyInfo[] s_nonPublicProperties = typeof(Option).GetProperties(BindingFlags.Instance | BindingFlags.NonPublic);

public static Argument? GetArgument(this Option option) =>
s_nonPublicProperties.First(pi => pi.Name == "Argument").GetValue(option) as Argument;

public static bool? GetHasValidators(this Option option) =>
s_nonPublicProperties.First(pi => pi.Name == "HasValidators").GetValue(option) as bool?;
}
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Text.Json;

namespace Microsoft.DotNet.Cli.Utils.Extensions;

public static class StringExtensions
Expand All @@ -26,4 +28,7 @@ static int GetPrefixLength(string name)
return 0;
}
}

// https://stackoverflow.com/a/66342091/294804
public static string ToCamelCase(this string value) => JsonNamingPolicy.CamelCase.ConvertName(value);
}
21 changes: 21 additions & 0 deletions src/Cli/Microsoft.DotNet.Cli.Utils/Extensions/TypeExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

namespace Microsoft.DotNet.Cli.Utils.Extensions;

public static class TypeExtensions
{
// This is used when outputting the Type information for the CLI schema JSON.
public static string ToCliTypeString(this Type type)
{
var typeName = type.FullName ?? string.Empty;
if (!type.IsGenericType)
{
return typeName;
}

var genericTypeName = typeName.Substring(0, typeName.IndexOf('`'));
var genericTypes = string.Join(", ", type.GenericTypeArguments.Select(generic => generic.ToCliTypeString()));
return $"{genericTypeName}<{genericTypes}>";
}
}
149 changes: 149 additions & 0 deletions src/Cli/dotnet/CliSchema.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.CommandLine;
using System.Text.Encodings.Web;
using System.Text.Json;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Cli.Utils.Extensions;
using Command = System.CommandLine.Command;

namespace Microsoft.DotNet.Cli;

internal static class CliSchema
{
// Using UnsafeRelaxedJsonEscaping because this JSON is not transmitted over the web. Therefore, HTML-sensitive characters are not encoded.
// See: https://learn.microsoft.com/dotnet/api/system.text.encodings.web.javascriptencoder.unsaferelaxedjsonescaping
private static readonly JsonWriterOptions s_jsonWriterOptions = new() { Indented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };
private static readonly JsonSerializerOptions s_jsonSerializerOptions = new() { WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping };

public static void PrintCliSchema(Command command)
{
using var writer = new Utf8JsonWriter(Console.OpenStandardOutput(), s_jsonWriterOptions);
writer.WriteStartObject();

// Explicitly write "name" into the root JSON object as the name for any sub-commands are used as the key to the sub-command object.
writer.WriteString("name", command.Name);
writer.WriteString("version", Product.Version);
WriteCommand(command, writer);

writer.WriteEndObject();
writer.Flush();
}

private static void WriteCommand(Command command, Utf8JsonWriter writer)
{
writer.WriteString(nameof(command.Description).ToCamelCase(), command.Description);
writer.WriteBoolean(nameof(command.Hidden).ToCamelCase(), command.Hidden);

writer.WriteStartArray(nameof(command.Aliases).ToCamelCase());
foreach (var alias in command.Aliases.Order())
{
writer.WriteStringValue(alias);
}
writer.WriteEndArray();

writer.WriteStartObject(nameof(command.Arguments).ToCamelCase());
// Leave default ordering for arguments. Do not order by name.
foreach (var argument in command.Arguments)
{
WriteArgument(argument, writer);
}
writer.WriteEndObject();

writer.WriteStartObject(nameof(command.Options).ToCamelCase());
foreach (var option in command.Options.OrderBy(o => o.Name))
{
WriteOption(option, writer);
}
writer.WriteEndObject();

writer.WriteStartObject(nameof(command.Subcommands).ToCamelCase());
foreach (var subCommand in command.Subcommands.OrderBy(sc => sc.Name))
{
writer.WriteStartObject(subCommand.Name);
WriteCommand(subCommand, writer);
writer.WriteEndObject();
}
writer.WriteEndObject();
}

private static void WriteArgument(Argument argument, Utf8JsonWriter writer)
{
writer.WriteStartObject(argument.Name);

writer.WriteString(nameof(argument.Description).ToCamelCase(), argument.Description);
writer.WriteBoolean(nameof(argument.Hidden).ToCamelCase(), argument.Hidden);
writer.WriteString(nameof(argument.HelpName).ToCamelCase(), argument.HelpName);
writer.WriteString(nameof(argument.ValueType).ToCamelCase(), argument.ValueType.ToCliTypeString());

WriteDefaultValue(argument, writer);
WriteArity(argument.Arity, writer);

writer.WriteEndObject();
}

private static void WriteOption(Option option, Utf8JsonWriter writer)
{
writer.WriteStartObject(option.Name);

writer.WriteString(nameof(option.Description).ToCamelCase(), option.Description);
writer.WriteBoolean(nameof(option.Hidden).ToCamelCase(), option.Hidden);

writer.WriteStartArray(nameof(option.Aliases).ToCamelCase());
foreach (var alias in option.Aliases.Order())
{
writer.WriteStringValue(alias);
}
writer.WriteEndArray();

writer.WriteString(nameof(option.HelpName).ToCamelCase(), option.HelpName);
writer.WriteString(nameof(option.ValueType).ToCamelCase(), option.ValueType.ToCliTypeString());

// GetArgument will only return null if System.CommandLine is changed to no longer contain an Argument property within Option.
var internalArgument = option.GetArgument() ?? new DynamicArgument<string>(string.Empty);
WriteDefaultValue(internalArgument, writer);
WriteArity(option.Arity, writer);

writer.WriteBoolean(nameof(option.Required).ToCamelCase(), option.Required);
writer.WriteBoolean(nameof(option.Recursive).ToCamelCase(), option.Recursive);

writer.WriteEndObject();
}

private static void WriteDefaultValue(Argument argument, Utf8JsonWriter writer)
{
writer.WriteBoolean(nameof(argument.HasDefaultValue).ToCamelCase(), argument.HasDefaultValue);
writer.WritePropertyName("defaultValue");
if (!argument.HasDefaultValue)
{
writer.WriteNullValue();
return;
}

// Encode the value automatically based on the System.Type of the argument.
JsonSerializer.Serialize(writer, argument.GetDefaultValue(), argument.ValueType, s_jsonSerializerOptions);
return;
}

private static void WriteArity(ArgumentArity arity, Utf8JsonWriter writer)
{
writer.WriteStartObject(nameof(arity));

writer.WriteNumber("minimum", arity.MinimumNumberOfValues);
writer.WritePropertyName("maximum");
// ArgumentArity.ZeroOrMore.MaximumNumberOfValues is required as MaximumArity in ArgumentArity is a private field.
if (arity.MaximumNumberOfValues == ArgumentArity.ZeroOrMore.MaximumNumberOfValues)
{
// When the "OrMore" arity is present, write the maximum as null (thus unbounded).
// The literal max integer value is set to an arbitrary amount (ATTOW 100000), which is not necessary to know for an external consumer.
writer.WriteNullValue();
}
else
{
writer.WriteNumberValue(arity.MaximumNumberOfValues);
}

writer.WriteEndObject();
}
}
5 changes: 4 additions & 1 deletion src/Cli/dotnet/CliStrings.resx
Original file line number Diff line number Diff line change
Expand Up @@ -803,4 +803,7 @@ For a list of locations searched, specify the "-d" option before the tool name.<
<value>Cannot specify --version when the package argument already contains a version.</value>
<comment>{Locked="--version"}</comment>
</data>
</root>
<data name="SDKSchemaCommandDefinition" xml:space="preserve">
<value>Display the command schema as JSON.</value>
</data>
</root>
1 change: 1 addition & 0 deletions src/Cli/dotnet/CliUsage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ internal static class CliUsage
--list-runtimes {CliCommandStrings.SDKListRuntimesCommandDefinition}
--list-sdks {CliCommandStrings.SDKListSdksCommandDefinition}
--version {CliCommandStrings.SDKVersionCommandDefinition}
--cli-schema {CliStrings.SDKSchemaCommandDefinition}

{CliCommandStrings.Commands}:
build {CliCommandStrings.BuildDefinition}
Expand Down
2 changes: 1 addition & 1 deletion src/Cli/dotnet/Extensions/ParseResultExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,7 +99,7 @@ public static bool IsDotnetBuiltInCommand(this ParseResult parseResult)

public static bool IsTopLevelDotnetCommand(this ParseResult parseResult)
{
return parseResult.CommandResult.Command.Equals(Microsoft.DotNet.Cli.Parser.RootCommand) && string.IsNullOrEmpty(parseResult.RootSubCommandResult());
return parseResult.CommandResult.Command.Equals(Parser.RootCommand) && string.IsNullOrEmpty(parseResult.RootSubCommandResult());
}

public static bool CanBeInvoked(this ParseResult parseResult)
Expand Down
21 changes: 13 additions & 8 deletions src/Cli/dotnet/Parser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -98,22 +98,29 @@ public static class Parser

public static readonly Option<bool> VersionOption = new("--version")
{
Arity = ArgumentArity.Zero,
Arity = ArgumentArity.Zero
};

public static readonly Option<bool> InfoOption = new("--info")
{
Arity = ArgumentArity.Zero,
Arity = ArgumentArity.Zero
};

public static readonly Option<bool> ListSdksOption = new("--list-sdks")
{
Arity = ArgumentArity.Zero,
Arity = ArgumentArity.Zero
};

public static readonly Option<bool> ListRuntimesOption = new("--list-runtimes")
{
Arity = ArgumentArity.Zero
};

public static readonly Option<bool> CliSchemaOption = new("--cli-schema")
{
Description = CliStrings.SDKSchemaCommandDefinition,
Arity = ArgumentArity.Zero,
Recursive = true
};

// Argument
Expand Down Expand Up @@ -152,6 +159,7 @@ private static Command ConfigureCommandLine(Command rootCommand)
rootCommand.Options.Add(InfoOption);
rootCommand.Options.Add(ListSdksOption);
rootCommand.Options.Add(ListRuntimesOption);
rootCommand.Options.Add(CliSchemaOption);

// Add argument
rootCommand.Arguments.Add(DotnetSubCommand);
Expand All @@ -175,11 +183,8 @@ private static Command ConfigureCommandLine(Command rootCommand)
return rootCommand;
}

public static Command GetBuiltInCommand(string commandName)
{
return Subcommands
.FirstOrDefault(c => c.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase));
}
public static Command GetBuiltInCommand(string commandName) =>
Subcommands.FirstOrDefault(c => c.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase));

/// <summary>
/// Implements token-per-line response file handling for the CLI. We use this instead of the built-in S.CL handling
Expand Down
17 changes: 9 additions & 8 deletions src/Cli/dotnet/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,17 +134,18 @@ internal static int ProcessArgs(string[] args, TimeSpan startupTime, ITelemetry
}
PerformanceLogEventSource.Log.BuiltInCommandParserStop();

using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel =
new FirstTimeUseNoticeSentinel())
using (IFirstTimeUseNoticeSentinel disposableFirstTimeUseNoticeSentinel = new FirstTimeUseNoticeSentinel())
{
IFirstTimeUseNoticeSentinel firstTimeUseNoticeSentinel = disposableFirstTimeUseNoticeSentinel;
IAspNetCertificateSentinel aspNetCertificateSentinel = new AspNetCertificateSentinel();
IFileSentinel toolPathSentinel = new FileSentinel(
new FilePath(
Path.Combine(
CliFolderPathCalculator.DotnetUserProfileFolderPath,
ToolPathSentinelFileName)));
if (parseResult.GetValue(Parser.DiagOption) && parseResult.IsDotnetBuiltInCommand())
IFileSentinel toolPathSentinel = new FileSentinel(new FilePath(Path.Combine(CliFolderPathCalculator.DotnetUserProfileFolderPath,ToolPathSentinelFileName)));

if (parseResult.GetValue(Parser.CliSchemaOption))
{
CliSchema.PrintCliSchema(parseResult.CommandResult.Command);
return 0;
}
else if (parseResult.GetValue(Parser.DiagOption) && parseResult.IsDotnetBuiltInCommand())
{
// We found --diagnostic or -d, but we still need to determine whether the option should
// be attached to the dotnet command or the subcommand.
Expand Down
5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.cs.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.de.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions src/Cli/dotnet/xlf/CliStrings.es.xlf

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading
Loading