diff --git a/DevProxy.Tests/ConfigValidateTests.cs b/DevProxy.Tests/ConfigValidateTests.cs index 921d14764..887b585a9 100644 --- a/DevProxy.Tests/ConfigValidateTests.cs +++ b/DevProxy.Tests/ConfigValidateTests.cs @@ -383,19 +383,22 @@ public async Task AcceptsCaseInsensitiveKeyCollisionsInYaml() [Theory] [InlineData(new[] { "validate" }, true)] [InlineData(new[] { "config", "validate" }, true)] - [InlineData(new[] { "--output", "json", "validate" }, true)] - [InlineData(new[] { "--output=json", "config", "validate" }, true)] - [InlineData(new[] { "--output:json", "validate" }, true)] - [InlineData(new[] { "--log-level:Warning", "validate" }, true)] + [InlineData(new[] { "validate", "--output", "json" }, true)] + [InlineData(new[] { "config", "validate", "--output=json" }, true)] + [InlineData(new[] { "--output", "json", "validate" }, false)] [InlineData(new[] { "validate", "--help" }, false)] [InlineData(new[] { "config", "get", "validate" }, false)] [InlineData(new[] { "--config-file", "validate" }, false)] + [InlineData(new[] { "config", "--output", "json", "validate" }, true)] + [InlineData(new[] { "config", "--no-color", "--log-level:Warning", "validate" }, true)] + [InlineData(new[] { "config", "--output", "validate" }, false)] public void DetectsValidateInvocation(string[] args, bool expected) => Assert.Equal(expected, DevProxyCommand.IsValidateInvocation(args)); [Theory] [InlineData(new[] { "validate", "--config-file=my.json" }, "my.json")] - [InlineData(new[] { "--output", "json", "config", "validate", "-c", "my.json" }, "my.json")] + [InlineData(new[] { "config", "validate", "--output", "json", "-c", "my.json" }, "my.json")] + [InlineData(new[] { "config", "--output", "json", "validate", "-c", "my.json" }, "my.json")] public void ParsesValidateArgs(string[] args, string expectedConfigFile) { var parseResult = ConfigCommand.ParseValidateArgs(args, out var configFileOptions, out _); diff --git a/DevProxy.Tests/DevProxyCommandTests.cs b/DevProxy.Tests/DevProxyCommandTests.cs index f1f79b8d9..0f8e3e990 100644 --- a/DevProxy.Tests/DevProxyCommandTests.cs +++ b/DevProxy.Tests/DevProxyCommandTests.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using DevProxy.Commands; +using System.CommandLine; using Xunit; @@ -54,15 +55,39 @@ public void ApplyDiscoverOption_False_KeepsRecordingEnabledFromOtherSources() [Theory] [InlineData(true, "stdio", "npx", "@devproxy/mcp")] - [InlineData(true, "--log-level", "debug", "stdio", "npx")] + [InlineData(true, "stdio", "-c", "myconfig.json", "node", "app.js")] + [InlineData(false, "--log-level", "debug", "stdio", "npx")] [InlineData(false, "jwt", "create", "--name", "stdio", "--output", "json")] - [InlineData(true, "--env", "A=1", "B=2", "stdio", "node", "server.js")] - [InlineData(true, "-e", "A=1", "B=2", "--log-level", "debug", "stdio", "node")] - [InlineData(true, "--urls-to-watch", "https://a/*", "https://b/*", "stdio", "node")] - [InlineData(true, "--watch-pids", "1", "2", "stdio", "node")] - [InlineData(true, "--watch-process-names", "a", "b", "stdio", "node")] [InlineData(false, "config", "get", "stdio")] [InlineData(false)] - public void IsStdioSubcommand_DetectsSubcommandNotArgumentValues(bool expected, params string[] args) => + public void IsStdioSubcommand_DetectsSubcommandOnlyAsFirstArgument(bool expected, params string[] args) => Assert.Equal(expected, DevProxyCommand.IsStdioSubcommand(args)); + + [Theory] + [InlineData(null)] + [InlineData(null, "--port", "0")] + [InlineData(null, "--help")] + [InlineData(null, "api", "show", "--log-level", "debug")] + [InlineData("api show", "--log-level", "debug", "api", "show")] + [InlineData("api show", "--port", "1", "api", "show")] + [InlineData("api", "--output", "json", "api")] + public void GetLeadingOptionsError_RejectsOptionsBeforeSubcommand(string? expectedCommandPath, params string[] args) + { + var logLevelOption = new Option(DevProxyCommand.LogLevelOptionName) { Recursive = true }; + var outputOption = new Option(DevProxyCommand.OutputOptionName) { Recursive = true }; + var portOption = new Option(DevProxyCommand.PortOptionName); + var apiCommand = new Command("api") { new Command("show") }; + var rootCommand = new RootCommand { logLevelOption, outputOption, portOption, apiCommand }; + + var error = DevProxyCommand.GetLeadingOptionsError(rootCommand.Parse(args), args); + + if (expectedCommandPath is null) + { + Assert.Null(error); + } + else + { + Assert.Contains($"devproxy {expectedCommandPath} [options]", error, StringComparison.Ordinal); + } + } } diff --git a/DevProxy.Tests/DevProxyConfigOptionsTests.cs b/DevProxy.Tests/DevProxyConfigOptionsTests.cs index 04801deeb..b4a173136 100644 --- a/DevProxy.Tests/DevProxyConfigOptionsTests.cs +++ b/DevProxy.Tests/DevProxyConfigOptionsTests.cs @@ -23,14 +23,4 @@ public void Discover_ParsesOptionalValue(string[] args, bool expected) Assert.Equal(expected, options.Discover); } - - [Fact] - public void ParseOptions_MultipleEnvValuesBeforeStdio_SelectsStdio() - { - var options = new DevProxyConfigOptions(); - options.ParseOptions(["--env", "A=1", "B=2", "stdio", "node", "server.js"]); - - Assert.True(options.IsStdioMode); - Assert.Equal(new Dictionary { ["A"] = "1", ["B"] = "2" }, options.Env); - } } diff --git a/DevProxy.Tests/LoggingConfigurationTests.cs b/DevProxy.Tests/LoggingConfigurationTests.cs index 18f367bb8..7b10dd817 100644 --- a/DevProxy.Tests/LoggingConfigurationTests.cs +++ b/DevProxy.Tests/LoggingConfigurationTests.cs @@ -34,6 +34,21 @@ public void ConfigureDevProxyLogging_Interactive_HonorsShowTimestamps(bool showT Assert.False(options.IncludeFullTimestamps); } + [Theory] + [InlineData(true, false)] + [InlineData(false, true)] + public void ConfigureDevProxyLogging_UsesPlainOutputOnlyForSubcommands(bool isRootCommand, bool expectedPlainOutput) + { + using var configuration = new ConfigurationManager(); + var services = new ServiceCollection(); + services.AddLogging(builder => builder.ConfigureDevProxyLogging(configuration, new DevProxyConfigOptions(), isStdioCommand: false, isJwtCommand: false, isRootCommand)); + using var provider = services.BuildServiceProvider(); + + var options = provider.GetRequiredService>().Value; + + Assert.Equal(expectedPlainOutput, options.PlainOutput); + } + [Theory] [InlineData(LogLevel.Warning)] [InlineData(LogLevel.Error)] diff --git a/DevProxy.Tests/ProxyConsoleFormatterTests.cs b/DevProxy.Tests/ProxyConsoleFormatterTests.cs index 7948b9eff..0285cd6aa 100644 --- a/DevProxy.Tests/ProxyConsoleFormatterTests.cs +++ b/DevProxy.Tests/ProxyConsoleFormatterTests.cs @@ -35,6 +35,22 @@ public void FinishedProcessingRequest_WriterThrows_ReleasesBufferedLines() Assert.DoesNotContain("https://first", output, StringComparison.Ordinal); } + [Theory] + [InlineData(LogLevel.Information, "Base URL: http://127.0.0.1:8897")] + [InlineData(LogLevel.Warning, "warning: Base URL: http://127.0.0.1:8897")] + [InlineData(LogLevel.Error, "error: Base URL: http://127.0.0.1:8897")] + [InlineData(LogLevel.Critical, "error: Base URL: http://127.0.0.1:8897")] + public void PlainOutput_WritesMessageWithoutLevelLabel(LogLevel level, string expected) + { + var formatter = new ProxyConsoleFormatter(Options.Create(new ProxyConsoleFormatterOptions { PlainOutput = true })); + using var writer = new StringWriter(CultureInfo.InvariantCulture); + var entry = new LogEntry(level, "Tests", new EventId(0), "Base URL: http://127.0.0.1:8897", null, (state, _) => state); + + formatter.Write(entry, null, writer); + + Assert.Equal(expected + Environment.NewLine, writer.ToString()); + } + private static void Write(ProxyConsoleFormatter formatter, IExternalScopeProvider scopeProvider, TextWriter writer, string message, MessageType type) { var log = new RequestLog(message, type, context: null); diff --git a/DevProxy/Commands/ConfigCommand.cs b/DevProxy/Commands/ConfigCommand.cs index f0e7b602f..ed3e898d9 100644 --- a/DevProxy/Commands/ConfigCommand.cs +++ b/DevProxy/Commands/ConfigCommand.cs @@ -111,6 +111,7 @@ internal static async Task RunValidateStandaloneAsync(string[] args) formatterOptions.IncludeScopes = false; formatterOptions.ShowSkipMessages = true; formatterOptions.ShowTimestamps = false; + formatterOptions.PlainOutput = true; }) .AddConsoleFormatter(formatterOptions => { diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 5ff34d65d..75c897e3f 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -102,46 +102,11 @@ public static bool IsStdioCommand } } - // Detects the stdio subcommand rather than any argument equal to "stdio" - // (e.g. `jwt create --name stdio`). Tokens before the subcommand may only be - // options or their values. args excludes the program name. - internal static bool IsStdioSubcommand(string[] args) - { - var inMultiValueOption = false; - for (var i = 0; i < args.Length; i++) - { - if (string.Equals(args[i], "stdio", StringComparison.Ordinal)) - { - return true; - } - - if (args[i].StartsWith('-', StringComparison.Ordinal)) - { - inMultiValueOption = _multiValueRootOptions.Contains(args[i]); - continue; - } - - var isOptionValue = inMultiValueOption || (i > 0 && args[i - 1].StartsWith('-', StringComparison.Ordinal)); - if (!isOptionValue) - { - return false; - } - } - - return false; - } - - // Root options that accept multiple values per token, so every value - // following them precedes the subcommand. - private static readonly HashSet _multiValueRootOptions = - [ - EnvOptionName, - "-e", - UrlsToWatchOptionName, - "-u", - WatchPidsOptionName, - WatchProcessNamesOptionName - ]; + // Subcommands must be the first argument (see GetLeadingOptionsError), so an + // argument equal to "stdio" elsewhere (e.g. `jwt create --name stdio`) isn't + // the subcommand. args excludes the program name. + internal static bool IsStdioSubcommand(string[] args) => + args.Length > 0 && string.Equals(args[0], "stdio", StringComparison.Ordinal); public static bool IsJwtCommand { @@ -176,9 +141,8 @@ public static bool IsConfigValidateCommand } /// - /// Returns true when args invoke 'validate' or 'config validate', allowing - /// global options (like --output) before the command. Help is excluded so - /// it's rendered by the full command tree. + /// Returns true when args invoke 'validate' or 'config validate'. Help is + /// excluded so it's rendered by the full command tree. /// internal static bool IsValidateInvocation(string[] args) { @@ -187,8 +151,21 @@ internal static bool IsValidateInvocation(string[] args) return false; } - var commandTokens = new List(2); - for (var i = 0; i < args.Length && commandTokens.Count < 2; i++) + if (args.Length == 0) + { + return false; + } + if (string.Equals(args[0], "validate", StringComparison.OrdinalIgnoreCase)) + { + return true; + } + if (!string.Equals(args[0], "config", StringComparison.OrdinalIgnoreCase)) + { + return false; + } + + // Recursive options are allowed between 'config' and 'validate' + for (var i = 1; i < args.Length; i++) { var arg = args[i]; if (string.Equals(arg, OutputOptionName, StringComparison.OrdinalIgnoreCase) || @@ -197,28 +174,13 @@ internal static bool IsValidateInvocation(string[] args) i++; continue; } - if (arg.StartsWith(OutputOptionName + "=", StringComparison.OrdinalIgnoreCase) || - arg.StartsWith(OutputOptionName + ":", StringComparison.OrdinalIgnoreCase) || - arg.StartsWith(LogLevelOptionName + "=", StringComparison.OrdinalIgnoreCase) || - arg.StartsWith(LogLevelOptionName + ":", StringComparison.OrdinalIgnoreCase) || - string.Equals(arg, NoColorOptionName, StringComparison.OrdinalIgnoreCase) || - (commandTokens.Count > 0 && arg.StartsWith('-', StringComparison.Ordinal))) - { - continue; - } if (arg.StartsWith('-', StringComparison.Ordinal)) { - // other root options may take values, so we can't tell what follows - break; + continue; } - commandTokens.Add(arg); + return string.Equals(arg, "validate", StringComparison.OrdinalIgnoreCase); } - - return commandTokens.Count > 0 && - (string.Equals(commandTokens[0], "validate", StringComparison.OrdinalIgnoreCase) || - (commandTokens.Count > 1 && - string.Equals(commandTokens[0], "config", StringComparison.OrdinalIgnoreCase) && - string.Equals(commandTokens[1], "validate", StringComparison.OrdinalIgnoreCase))); + return false; } public static bool IsPluginCommand @@ -231,30 +193,7 @@ public static bool IsPluginCommand } var args = Environment.GetCommandLineArgs(); - // skip global options supported by the standalone plugin command - // so that e.g. `devproxy --output json plugin list` is detected too - var i = 1; - while (i < args.Length) - { - if (string.Equals(args[i], OutputOptionName, StringComparison.OrdinalIgnoreCase) || - string.Equals(args[i], LogLevelOptionName, StringComparison.OrdinalIgnoreCase)) - { - i += 2; - } - else if (args[i].StartsWith($"{OutputOptionName}=", StringComparison.OrdinalIgnoreCase) || - args[i].StartsWith($"{OutputOptionName}:", StringComparison.OrdinalIgnoreCase) || - args[i].StartsWith($"{LogLevelOptionName}=", StringComparison.OrdinalIgnoreCase) || - args[i].StartsWith($"{LogLevelOptionName}:", StringComparison.OrdinalIgnoreCase) || - string.Equals(args[i], NoColorOptionName, StringComparison.OrdinalIgnoreCase)) - { - i++; - } - else - { - break; - } - } - field = i < args.Length && string.Equals(args[i], "plugin", StringComparison.OrdinalIgnoreCase); + field = args.Length > 1 && string.Equals(args[1], "plugin", StringComparison.OrdinalIgnoreCase); _isPluginCommandResolved = true; return field; } @@ -278,8 +217,8 @@ public static bool IsDetachedMode /// /// Determines if the root command (proxy itself) is being invoked. - /// Returns true when no subcommand is specified (only options or no args). - /// A subcommand is detected when the first non-program argument doesn't start with '-'. + /// Subcommands must be the first argument (enforced by GetLeadingOptionsError), + /// so it's the root command when there are no arguments or the first one is an option. /// public static bool IsRootCommand { @@ -412,6 +351,12 @@ public async Task InvokeAsync(string[] args, WebApplication app) ? StdioCommand.ParseStdioArgs(this, args) : Parse(args); + if (GetLeadingOptionsError(parseResult, args) is { } leadingOptionsError) + { + WriteErrors([leadingOptionsError], IsJsonOutputRequested(parseResult)); + return 2; + } + if (parseResult.Action is ParseErrorAction parseErrorAction) { if (IsJsonOutputRequested(parseResult)) @@ -468,23 +413,54 @@ internal static bool IsJsonOutputRequested(ParseResult parseResult) => parseResult.GetResult(OutputOptionName) is OptionResult { Tokens: [var token, ..] } && string.Equals(token.Value, nameof(OutputFormat.Json), StringComparison.OrdinalIgnoreCase); - internal static void WriteJsonParseErrors(ParseResult parseResult) + // Subcommands must be the first argument. This lets the root command be + // detected from the first argument (see IsRootCommand) before plugins, + // which can contribute their own subcommands, are loaded. + internal static string? GetLeadingOptionsError(ParseResult parseResult, string[] args) + { + if (args.Length == 0 || + !args[0].StartsWith('-', StringComparison.Ordinal) || + parseResult.CommandResult.Command is RootCommand) + { + return null; + } + + var commandPath = new List(); + for (SymbolResult? result = parseResult.CommandResult; + result is CommandResult { Command: not RootCommand } commandResult; + result = result.Parent) + { + commandPath.Insert(0, commandResult.Command.Name); + } + + return $"Options must follow the subcommand. Use: devproxy {string.Join(' ', commandPath)} [options]"; + } + + internal static void WriteJsonParseErrors(ParseResult parseResult) => + WriteErrors(parseResult.Errors.Select(e => e.Message), json: true); + + private static void WriteErrors(IEnumerable errors, bool json) { // Usage errors must still be visible when normal logging is disabled, // for example by the jwt command or --log-level None. - using var loggerFactory = LoggerFactory.Create(builder => builder - .SetMinimumLevel(LogLevel.Error) - .AddConsole(options => - { - options.FormatterName = JsonConsoleFormatter.FormatterName; - options.LogToStandardErrorThreshold = LogLevel.Error; - }) - .AddConsoleFormatter()); + using var loggerFactory = LoggerFactory.Create(builder => + { + _ = builder + .SetMinimumLevel(LogLevel.Error) + .AddConsole(options => + { + options.FormatterName = json ? JsonConsoleFormatter.FormatterName : ProxyConsoleFormatter.DefaultCategoryName; + options.LogToStandardErrorThreshold = LogLevel.Error; + }); + _ = json + ? builder.AddConsoleFormatter() + : builder.AddConsoleFormatter(options => options.PlainOutput = true); + }); var logger = loggerFactory.CreateLogger(); - foreach (var error in parseResult.Errors) + foreach (var error in errors) { - logger.LogError("{ParseError}", error.Message); + logger.LogError("{ParseError}", error); } } diff --git a/DevProxy/Commands/PluginCommand.cs b/DevProxy/Commands/PluginCommand.cs index 0583f6185..3f8a31105 100644 --- a/DevProxy/Commands/PluginCommand.cs +++ b/DevProxy/Commands/PluginCommand.cs @@ -75,6 +75,7 @@ internal static async Task RunStandaloneAsync(string[] args) .AddConsoleFormatter(formatterOptions => { formatterOptions.ShowTimestamps = false; + formatterOptions.PlainOutput = true; }) .AddConsoleFormatter(formatterOptions => { diff --git a/DevProxy/Extensions/ILoggingBuilderExtensions.cs b/DevProxy/Extensions/ILoggingBuilderExtensions.cs index f3017194b..5b2f39178 100644 --- a/DevProxy/Extensions/ILoggingBuilderExtensions.cs +++ b/DevProxy/Extensions/ILoggingBuilderExtensions.cs @@ -110,8 +110,8 @@ internal static ILoggingBuilder ConfigureDevProxyLogging( return builder; } - // For other subcommands (cert, config, outdated, msgraphdb), use rich logging - // but with plugin messages filtered out + // For other subcommands (cert, config, outdated, msgraphdb), use plain + // logging without level labels, with plugin messages filtered out // Structured results are logged at Information. When JSON output is // requested with a higher log level, let Information through the @@ -138,6 +138,7 @@ internal static ILoggingBuilder ConfigureDevProxyLogging( formatterOptions.IncludeScopes = true; formatterOptions.ShowSkipMessages = showSkipMessages; formatterOptions.ShowTimestamps = showTimestamps; + formatterOptions.PlainOutput = true; } ) .AddConsoleFormatter(formatterOptions => diff --git a/DevProxy/Logging/ProxyConsoleFormatter.cs b/DevProxy/Logging/ProxyConsoleFormatter.cs index e74cc8443..57a6343bb 100644 --- a/DevProxy/Logging/ProxyConsoleFormatter.cs +++ b/DevProxy/Logging/ProxyConsoleFormatter.cs @@ -196,11 +196,18 @@ private void WriteMessageWithLabel(string? message, string category, LogLevel lo return; } - var label = GetLogLevelString(logLevel); - var (bgColor, fgColor) = GetLogLevelColor(logLevel); + if (_options.PlainOutput) + { + textWriter.Write(GetPlainPrefix(logLevel)); + } + else + { + var label = GetLogLevelString(logLevel); + var (bgColor, fgColor) = GetLogLevelColor(logLevel); - WriteLabel(textWriter, label, bgColor, fgColor); - textWriter.Write($"{_labelSpacing}{_boxSpacing}"); + WriteLabel(textWriter, label, bgColor, fgColor); + textWriter.Write($"{_labelSpacing}{_boxSpacing}"); + } if (_options.IncludeFullTimestamps) { @@ -297,6 +304,15 @@ private void WriteScopes(IExternalScopeProvider? scopeProvider, TextWriter textW private static string GetLogLevelString(LogLevel logLevel) => _logLevelStrings.TryGetValue(logLevel, out var str) ? str : throw new ArgumentOutOfRangeException(nameof(logLevel)); + private static string GetPlainPrefix(LogLevel logLevel) => logLevel switch + { + LogLevel.Trace => "trace: ", + LogLevel.Debug => "debug: ", + LogLevel.Warning => "warning: ", + LogLevel.Error or LogLevel.Critical => "error: ", + _ => "" + }; + private static (ConsoleColor bg, ConsoleColor fg) GetLogLevelColor(LogLevel logLevel) => _logLevelColors.TryGetValue(logLevel, out var color) ? color : (Console.BackgroundColor, Console.ForegroundColor); diff --git a/DevProxy/Logging/ProxyConsoleFormatterOptions.cs b/DevProxy/Logging/ProxyConsoleFormatterOptions.cs index 161b1f387..630aa4f47 100644 --- a/DevProxy/Logging/ProxyConsoleFormatterOptions.cs +++ b/DevProxy/Logging/ProxyConsoleFormatterOptions.cs @@ -15,6 +15,10 @@ sealed class ProxyConsoleFormatterOptions : ConsoleFormatterOptions public bool IncludeFullTimestamps { get; set; } + // Writes regular messages without level labels, for commands other than + // the root command. Messages other than information get a short prefix. + public bool PlainOutput { get; set; } + // Minimum level for diagnostic messages. Structured output (command // results) is always written regardless of this level. public LogLevel MinimumLogLevel { get; set; } = LogLevel.Trace;