diff --git a/DevProxy.Integration.Tests/ProcessSmokeTests.cs b/DevProxy.Integration.Tests/ProcessSmokeTests.cs index 520c7636..15c65d0c 100644 --- a/DevProxy.Integration.Tests/ProcessSmokeTests.cs +++ b/DevProxy.Integration.Tests/ProcessSmokeTests.cs @@ -486,11 +486,10 @@ private static JsonElement GetResultData(string output) } } - // Options before a command can't be fully resolved until plugins register theirs, so these - // run the real host to verify which command runs and where its output goes. + // Run the real host to verify which command runs and where its output goes. [Theory] [InlineData(new[] { "cert", "export" }, "text")] - [InlineData(new[] { "--log-level", "debug", "cert", "export" }, "text")] + [InlineData(new[] { "cert", "export", "--log-level", "debug" }, "text")] [InlineData(new[] { "cert", "export", "--output", "json" }, "json")] public async Task CertExport_WritesOnlyResultToStdout(string[] args, string output) { @@ -529,10 +528,10 @@ public async Task CertExport_WritesOnlyResultToStdout(string[] args, string outp } } - // cert is the value of a plugin option here, so the export runs but plugins that initialize - // before the command is resolved may still log to stdout + // Options must follow the subcommand, so a plugin option before cert export is rejected + // without exporting the certificate [Fact] - public async Task CertExport_AfterPluginOptionWithCertValue_ExportsCertificate() + public async Task CertExport_AfterPluginOptionWithCertValue_IsRejected() { var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-"); try @@ -545,9 +544,8 @@ public async Task CertExport_AfterPluginOptionWithCertValue_ExportsCertificate() ["--mocks-file", "cert", "cert", "export", "--output", "json", "--file", file], environment); - Assert.Equal(0, result.ExitCode); - Assert.True(File.Exists(file), result.Error); - Assert.Contains("\"path\"", result.Output, StringComparison.Ordinal); + Assert.Equal(2, result.ExitCode); + Assert.False(File.Exists(file)); } finally { @@ -557,8 +555,7 @@ public async Task CertExport_AfterPluginOptionWithCertValue_ExportsCertificate() // cert and export are values of plugin options or arguments of a plugin command here [Theory] - [InlineData("--failure-rate", "10", "mocks", "from-http-responses", "cert", "export", "--mocks-file", "out.json")] - [InlineData("--no-mocks", "mocks", "from-http-responses", "cert", "export", "--mocks-file", "generated.json")] + [InlineData("mocks", "from-http-responses", "cert", "export", "--mocks-file", "out.json")] public async Task PluginCommand_WithCertExportArguments_ReportsPluginErrors(params string[] args) { var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-"); @@ -580,8 +577,8 @@ public async Task PluginCommand_WithCertExportArguments_ReportsPluginErrors(para } [Theory] - [InlineData("--mocks-file", "cert", "--watch-process-names", "export", "jwt", "create", "--output", "json")] - [InlineData("--mocks-file", "cert", "jwt", "create", "--scopes", "export", "--output", "json")] + [InlineData("jwt", "create", "--name", "cert", "--scopes", "export", "--output", "json")] + [InlineData("jwt", "create", "--scopes", "cert", "export", "--output", "json")] public async Task JwtCreate_WithCertExportArguments_WritesResultToStdout(params string[] args) { var workDir = Directory.CreateTempSubdirectory("devproxy-cert-export-"); diff --git a/DevProxy.Tests/ConfigValidateTests.cs b/DevProxy.Tests/ConfigValidateTests.cs index 921d1476..887b585a 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 f1f79b8d..0b604e6f 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,106 @@ 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); + } + } + + [Theory] + [InlineData("mocks", "from-http-responses", "r.http", "-c", "{0}")] + [InlineData("mocks", "--config-file", "{0}", "from-http-responses", "r.http")] + public void AddConfigFileOption_AcceptsConfigFileAfterPluginSubcommand(params string[] args) + { + var configFile = Path.GetTempFileName(); + try + { + var mocksCommand = new Command("mocks") { new Command("from-http-responses") { new Argument("files") } }; + DevProxyCommand.AddConfigFileOption(mocksCommand, resolvedConfigFile: null); + var rootCommand = new RootCommand { mocksCommand }; + + var parseResult = rootCommand.Parse([.. args.Select(a => a == "{0}" ? configFile : a)]); + + Assert.Empty(parseResult.Errors); + Assert.Equal(configFile, parseResult.GetValue(DevProxyCommand.ConfigFileOptionName)); + } + finally + { + File.Delete(configFile); + } + } + + [Fact] + public void AddConfigFileOption_RejectsMissingConfigFile() + { + var command = new Command("open"); + DevProxyCommand.AddConfigFileOption(command, resolvedConfigFile: null); + var rootCommand = new RootCommand { new Command("config") { command } }; + + var parseResult = rootCommand.Parse(["config", "open", "-c", "missing-devproxyrc.json"]); + + Assert.Contains(parseResult.Errors, e => e.Message.Contains("does not exist", StringComparison.Ordinal)); + } + + [Fact] + public void AddConfigFileOption_ValidatesResolvedConfigFile() + { + // --env can change what a token such as ~dataFolder expands to after the + // config file was resolved and loaded, so validate the resolved path. + var configFile = Path.GetTempFileName(); + try + { + var command = new Command("open"); + DevProxyCommand.AddConfigFileOption(command, configFile); + var rootCommand = new RootCommand { new Command("config") { command } }; + + var parseResult = rootCommand.Parse(["config", "open", "-c", "missing-devproxyrc.json"]); + + Assert.Empty(parseResult.Errors); + } + finally + { + File.Delete(configFile); + } + } + + [Fact] + public void AddConfigFileOption_KeepsPluginDeclaredOption() + { + var pluginOption = new Option("--count", "-c"); + var mocksCommand = new Command("mocks") { new Command("from-http-responses") { pluginOption } }; + DevProxyCommand.AddConfigFileOption(mocksCommand, resolvedConfigFile: null); + + Assert.Empty(mocksCommand.Options); + } } diff --git a/DevProxy.Tests/DevProxyConfigOptionsTests.cs b/DevProxy.Tests/DevProxyConfigOptionsTests.cs index 04801dee..d01c376f 100644 --- a/DevProxy.Tests/DevProxyConfigOptionsTests.cs +++ b/DevProxy.Tests/DevProxyConfigOptionsTests.cs @@ -25,12 +25,11 @@ public void Discover_ParsesOptionalValue(string[] args, bool expected) } [Fact] - public void ParseOptions_MultipleEnvValuesBeforeStdio_SelectsStdio() + public void ParseOptions_ReadsConfigFileAfterPluginSubcommand() { var options = new DevProxyConfigOptions(); - options.ParseOptions(["--env", "A=1", "B=2", "stdio", "node", "server.js"]); + options.ParseOptions(["mocks", "from-http-responses", "r.http", "--mocks-file", "out.json", "-c", "mocks.json"]); - Assert.True(options.IsStdioMode); - Assert.Equal(new Dictionary { ["A"] = "1", ["B"] = "2" }, options.Env); + Assert.Equal(Path.GetFullPath("mocks.json"), options.ConfigFile); } } diff --git a/DevProxy.Tests/LoggingConfigurationTests.cs b/DevProxy.Tests/LoggingConfigurationTests.cs index 18f367bb..c66b5870 100644 --- a/DevProxy.Tests/LoggingConfigurationTests.cs +++ b/DevProxy.Tests/LoggingConfigurationTests.cs @@ -34,6 +34,43 @@ 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); + } + + [Fact] + public void ConfigureDevProxyLogging_Subcommand_ShowsPluginMessagesOnlyWhilePluginCommandRuns() + { + using var configuration = new ConfigurationManager(); + var services = new ServiceCollection(); + services.AddLogging(builder => builder.ConfigureDevProxyLogging(configuration, new DevProxyConfigOptions(), isStdioCommand: false, isJwtCommand: false, isRootCommand: false)); + using var provider = services.BuildServiceProvider(); + var logger = provider.GetRequiredService().CreateLogger("DevProxy.Plugins.Mocking.MockResponsePlugin"); + + Assert.False(logger.IsEnabled(LogLevel.Error)); + DevProxyCommand.IsPluginCommandRunning = true; + try + { + Assert.True(logger.IsEnabled(LogLevel.Error)); + Assert.False(logger.IsEnabled(LogLevel.Debug)); + } + finally + { + DevProxyCommand.IsPluginCommandRunning = false; + } + } + [Theory] [InlineData(LogLevel.Warning)] [InlineData(LogLevel.Error)] diff --git a/DevProxy.Tests/ProxyConsoleFormatterTests.cs b/DevProxy.Tests/ProxyConsoleFormatterTests.cs index 7948b9ef..0285cd6a 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.Tests/SystemProxyManagerTests.cs b/DevProxy.Tests/SystemProxyManagerTests.cs index 3c1f8bad..d05972a7 100644 --- a/DevProxy.Tests/SystemProxyManagerTests.cs +++ b/DevProxy.Tests/SystemProxyManagerTests.cs @@ -342,6 +342,18 @@ public async Task RunResetStandalone_InvalidArguments_ReturnsUsageError(params s Assert.Equal(2, exitCode); } + // Must be rejected before reset changes any system proxy settings + [Theory] + [InlineData("--output", "json", "system-proxy", "reset", "--force")] + [InlineData("--log-level", "debug", "system-proxy", "reset")] + [InlineData("-c", "devproxyrc.json", "system-proxy", "reset")] + public async Task RunResetStandalone_LeadingOptions_ReturnsUsageError(params string[] args) + { + var exitCode = await DevProxy.Commands.SystemProxyCommand.RunResetStandaloneAsync(args); + + Assert.Equal(2, exitCode); + } + [Theory] [InlineData("system-proxy", "reset")] [InlineData("system-proxy", "reset", "--force")] diff --git a/DevProxy/Commands/ApiCommand.cs b/DevProxy/Commands/ApiCommand.cs index 4810f960..da86de8b 100644 --- a/DevProxy/Commands/ApiCommand.cs +++ b/DevProxy/Commands/ApiCommand.cs @@ -15,12 +15,14 @@ namespace DevProxy.Commands; sealed class ApiCommand : Command { private readonly IProxyConfiguration _proxyConfiguration; + private readonly DevProxyConfigOptions _configOptions; private readonly ILogger _logger; - public ApiCommand(IProxyConfiguration proxyConfiguration, ILogger logger) : + public ApiCommand(IProxyConfiguration proxyConfiguration, DevProxyConfigOptions configOptions, ILogger logger) : base("api", "Manage Dev Proxy API information") { _proxyConfiguration = proxyConfiguration; + _configOptions = configOptions; _logger = logger; ConfigureCommand(); } @@ -33,6 +35,7 @@ private void ConfigureCommand() var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; PrintApiInfo(outputFormat); }); + DevProxyCommand.AddConfigFileOption(apiShowCommand, _configOptions.ConfigFile); var apiTokenCommand = new Command("token", """ Print the API token of a running Dev Proxy instance. diff --git a/DevProxy/Commands/ConfigCommand.cs b/DevProxy/Commands/ConfigCommand.cs index f0e7b602..a1ca3a9e 100644 --- a/DevProxy/Commands/ConfigCommand.cs +++ b/DevProxy/Commands/ConfigCommand.cs @@ -48,18 +48,21 @@ private enum ConfigFileFormat private readonly ILogger _logger; private readonly IProxyConfiguration _proxyConfiguration; private readonly HttpClient _httpClient; + private readonly DevProxyConfigOptions _configOptions; private const string ConfigTemplatesFolder = "config-templates"; private static readonly string[] configFilePatterns = ["*.json", "*.yaml", "*.yml"]; public ConfigCommand( HttpClient httpClient, IProxyConfiguration proxyConfiguration, + DevProxyConfigOptions configOptions, ILogger logger) : base("config", "Manage Dev Proxy configs") { _proxyConfiguration = proxyConfiguration; _logger = logger; _httpClient = httpClient; + _configOptions = configOptions; _httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("dev-proxy", ProxyUtils.ProductVersion)); ConfigureCommand(); } @@ -111,6 +114,7 @@ internal static async Task RunValidateStandaloneAsync(string[] args) formatterOptions.IncludeScopes = false; formatterOptions.ShowSkipMessages = true; formatterOptions.ShowTimestamps = false; + formatterOptions.PlainOutput = true; }) .AddConsoleFormatter(formatterOptions => { @@ -210,6 +214,7 @@ private void ConfigureCommand() }; _ = Process.Start(cfgPsi); }); + DevProxyCommand.AddConfigFileOption(configOpenCommand, _configOptions.ConfigFile); var configValidateCommand = new Command("validate", "Validate a Dev Proxy configuration file without starting the proxy"); var validateConfigFileOption = CreateValidateConfigFileOption(); diff --git a/DevProxy/Commands/DevProxyCommand.cs b/DevProxy/Commands/DevProxyCommand.cs index 04baa30f..32872ceb 100644 --- a/DevProxy/Commands/DevProxyCommand.cs +++ b/DevProxy/Commands/DevProxyCommand.cs @@ -23,6 +23,7 @@ sealed class DevProxyCommand : RootCommand private readonly IProxyConfiguration _proxyConfiguration; private readonly ISet _urlsToWatch; private readonly UpdateNotification _updateNotification; + private readonly DevProxyConfigOptions _configOptions; private WebApplication? _app; internal static readonly TimeSpan NewVersionCheckTimeout = TimeSpan.FromSeconds(5); @@ -71,6 +72,8 @@ sealed class DevProxyCommand : RootCommand private static bool _isInternalDaemonResolved; private static bool _stdioLogFilePathResolved; private static bool _detachedLogFilePathResolved; + private static volatile bool _isPluginCommandRunning; + private readonly HashSet _pluginCommands = []; public static bool HasGlobalOptions { @@ -104,46 +107,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 { @@ -245,9 +213,8 @@ public static bool IsSystemProxyResetCommand } /// - /// 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) { @@ -256,8 +223,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) || @@ -266,28 +246,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 @@ -300,35 +265,22 @@ 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; } } + /// + /// True while a plugin-provided command is being invoked, so its messages + /// aren't filtered out like plugin initialization messages are. + /// + internal static bool IsPluginCommandRunning + { + get => _isPluginCommandRunning; + set => _isPluginCommandRunning = value; + } + public static bool IsDetachedMode { get @@ -347,8 +299,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 { @@ -459,7 +411,7 @@ public DevProxyCommand( IProxyConfiguration proxyConfiguration, IServiceProvider serviceProvider, UpdateNotification updateNotification, - DevProxyConfigOptions options, + DevProxyConfigOptions configOptions, ILogger logger) : base($"Start Dev Proxy\n\nAPI:\n Dev Proxy exposes an authenticated REST API for runtime management.\n Use --api-port (default: {proxyConfiguration.ApiPort}) and --api-ip-address (default: 127.0.0.1).\n The API bind address is independent of --ip-address.\n Run 'devproxy status' for the API URL and token, or 'devproxy api show' for endpoints\n ('devproxy api show --output json' includes request and response schemas).\n Set the DEV_PROXY_API_TOKEN environment variable (at least 32 characters) to use a fixed API token instead of a generated one.") { _serviceProvider = serviceProvider; @@ -467,9 +419,10 @@ public DevProxyCommand( _urlsToWatch = urlsToWatch; _proxyConfiguration = proxyConfiguration; _updateNotification = updateNotification; + _configOptions = configOptions; _logger = logger; - ConfigureCommand(options); + ConfigureCommand(); } public async Task InvokeAsync(string[] args, WebApplication app) @@ -481,6 +434,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)) @@ -492,6 +451,7 @@ public async Task InvokeAsync(string[] args, WebApplication app) parseErrorAction.ShowHelp = false; } + IsPluginCommandRunning = IsPluginProvidedCommand(parseResult); var exitCode = await parseResult.InvokeAsync(null, app.Lifetime.ApplicationStopping); // Return exit code 2 for input validation and parse errors to distinguish @@ -505,6 +465,48 @@ public async Task InvokeAsync(string[] args, WebApplication app) return exitCode; } + // Subcommands that use the configuration, including plugin commands that + // only exist when the configuration that loads their plugin is selected, + // must accept the config file option. Options must follow the subcommand + // (see GetLeadingOptionsError) and ConfigFileOption isn't recursive, so + // add a recursive copy. resolvedConfigFile is the config file path resolved + // before --env changed the environment, which is the file that was loaded. + internal static void AddConfigFileOption(Command command, string? resolvedConfigFile) + { + static bool DeclaresConfigFile(Command c) => + c.Options.Any(o => o.Name == ConfigFileOptionName || o.Aliases.Contains("-c")) || + c.Subcommands.Any(DeclaresConfigFile); + + if (DeclaresConfigFile(command)) + { + return; + } + + var option = new Option(ConfigFileOptionName, "-c") + { + HelpName = ConfigFileOption.HelpName, + Description = ConfigFileOption.Description, + Recursive = true + }; + option.Validators.Add(CreateConfigFileValidator(resolvedConfigFile)); + command.Add(option); + } + + private static Action CreateConfigFileValidator(string? resolvedConfigFile) => input => + { + var filePath = resolvedConfigFile ?? ProxyUtils.ReplacePathTokens(input.Tokens[0].Value); + if (string.IsNullOrEmpty(filePath)) + { + return; + } + + filePath = Path.GetFullPath(filePath); + if (!File.Exists(filePath)) + { + input.AddError($"Configuration file '{filePath}' does not exist. Check the file path and try again."); + } + }; + internal static Option CreateInstallCertOption(Option asSystemProxyOption, IProxyConfiguration proxyConfiguration) { var installCertOption = new Option(InstallCertOptionName) @@ -537,23 +539,67 @@ 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. + private bool IsPluginProvidedCommand(ParseResult parseResult) + { + for (SymbolResult? result = parseResult.CommandResult; result is CommandResult commandResult; result = result.Parent) + { + if (_pluginCommands.Contains(commandResult.Command)) + { + return true; + } + } + + return false; + } + + 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); + + internal 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); } } @@ -707,22 +753,10 @@ await PortConflict.CheckAsync(PortKind.Proxy, _proxyConfiguration.IPAddress, _pr } } - private void ConfigureCommand(DevProxyConfigOptions configOptions) + private void ConfigureCommand() { ConfigFileOption.Validators.Clear(); - ConfigFileOption.Validators.Add(input => - { - var filePath = configOptions.ConfigFile ?? ProxyUtils.ReplacePathTokens(input.Tokens[0].Value); - if (string.IsNullOrEmpty(filePath)) - { - return; - } - - if (!File.Exists(filePath)) - { - input.AddError($"Configuration file '{filePath}' does not exist. Check the file path and try again."); - } - }); + ConfigFileOption.Validators.Add(CreateConfigFileValidator(_configOptions.ConfigFile)); var options = CreateRootOptions(_proxyConfiguration); options.Add(ConfigFileOption); @@ -754,7 +788,9 @@ private void ConfigureCommand(DevProxyConfigOptions configOptions) { var (plugin, command) = group.First(); HelpDocs.Set(command, DocsLinks.ForPlugin(plugin.GetType())); + AddConfigFileOption(command, _configOptions.ConfigFile); commands.Add(command); + _ = _pluginCommands.Add(command); if (group.Count() > 1) { _logger.LogWarning( diff --git a/DevProxy/Commands/OutdatedCommand.cs b/DevProxy/Commands/OutdatedCommand.cs index ce820828..d37d759d 100644 --- a/DevProxy/Commands/OutdatedCommand.cs +++ b/DevProxy/Commands/OutdatedCommand.cs @@ -14,16 +14,19 @@ sealed class OutdatedCommand : Command { private readonly IProxyConfiguration _proxyConfiguration; private readonly UpdateNotification _updateNotification; + private readonly DevProxyConfigOptions _configOptions; private readonly ILogger _logger; public OutdatedCommand( IProxyConfiguration proxyConfiguration, UpdateNotification updateNotification, + DevProxyConfigOptions configOptions, ILogger logger) : base("outdated", "Check for new version") { _proxyConfiguration = proxyConfiguration; _updateNotification = updateNotification; + _configOptions = configOptions; _logger = logger; ConfigureCommand(); @@ -48,6 +51,7 @@ private void ConfigureCommand() var outputFormat = parseResult.GetValueOrDefault(DevProxyCommand.OutputOptionName) ?? OutputFormat.Text; await CheckVersionAsync(versionOnly, outputFormat); }); + DevProxyCommand.AddConfigFileOption(this, _configOptions.ConfigFile); } private async Task CheckVersionAsync(bool versionOnly, OutputFormat outputFormat) diff --git a/DevProxy/Commands/PluginCommand.cs b/DevProxy/Commands/PluginCommand.cs index 3ba6c8b9..66327be7 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/Commands/SystemProxyCommand.cs b/DevProxy/Commands/SystemProxyCommand.cs index b7cfb681..2a018d2a 100644 --- a/DevProxy/Commands/SystemProxyCommand.cs +++ b/DevProxy/Commands/SystemProxyCommand.cs @@ -90,9 +90,16 @@ internal static async Task RunResetStandaloneAsync(string[] args) { var (rootCommand, forceOption) = CreateStandaloneResetParser(); var parseResult = rootCommand.Parse(args); + // Validate like the full command tree before changing any system settings + if (DevProxyCommand.GetLeadingOptionsError(parseResult, args) is { } leadingOptionsError) + { + DevProxyCommand.WriteErrors([leadingOptionsError], DevProxyCommand.IsJsonOutputRequested(parseResult)); + return 2; + } + if (parseResult.Errors.Count > 0) { - WriteParseErrors(parseResult); + DevProxyCommand.WriteErrors(parseResult.Errors.Select(e => e.Message), DevProxyCommand.IsJsonOutputRequested(parseResult)); return 2; } @@ -105,23 +112,6 @@ internal static async Task RunResetStandaloneAsync(string[] args) loggerFactory.CreateLogger(), CancellationToken.None); } - // Usage errors must stay visible whatever --log-level requests, like in the full command tree. - private static void WriteParseErrors(ParseResult parseResult) - { - if (DevProxyCommand.IsJsonOutputRequested(parseResult)) - { - DevProxyCommand.WriteJsonParseErrors(parseResult); - return; - } - - using var loggerFactory = CreateConsoleLoggerFactory(OutputFormat.Text, LogLevel.Error); - var logger = loggerFactory.CreateLogger(); - foreach (var error in parseResult.Errors) - { - logger.LogError("{Message}", error.Message); - } - } - /// /// Creates console logging for system-proxy work that runs without the application host, /// formatted like the host's output (text or JSON lines). @@ -147,6 +137,7 @@ internal static ILoggerFactory CreateConsoleLoggerFactory(OutputFormat outputFor { formatterOptions.IncludeScopes = false; formatterOptions.ShowTimestamps = false; + formatterOptions.PlainOutput = true; }) .AddConsoleFormatter(formatterOptions => { diff --git a/DevProxy/Extensions/ILoggingBuilderExtensions.cs b/DevProxy/Extensions/ILoggingBuilderExtensions.cs index 553a446e..0ebd1e24 100644 --- a/DevProxy/Extensions/ILoggingBuilderExtensions.cs +++ b/DevProxy/Extensions/ILoggingBuilderExtensions.cs @@ -91,7 +91,8 @@ internal static ILoggingBuilder ConfigureDevProxyLogging( .AddFilter("Microsoft.Hosting.*", LogLevel.Error) .AddFilter("Microsoft.AspNetCore.*", LogLevel.Error) .AddFilter("Microsoft.Extensions.*", LogLevel.Error) - .AddFilter("System.*", LogLevel.Error) + .AddFilter("System.*", LogLevel.Error) + // Only show plugin messages when no global options are set .AddFilter("DevProxy.Plugins.*", level => level >= configuredLogLevel && @@ -122,8 +123,10 @@ 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. Plugin messages are filtered out, + // except while a plugin-provided command runs, so that plugin + // initialization messages are hidden but the command's own aren't. // Structured results are logged at Information. When JSON output is // requested with a higher log level, let Information through the @@ -137,8 +140,11 @@ internal static ILoggingBuilder ConfigureDevProxyLogging( .AddFilter("Microsoft.Hosting.*", LogLevel.Error) .AddFilter("Microsoft.AspNetCore.*", LogLevel.Error) .AddFilter("Microsoft.Extensions.*", LogLevel.Error) - .AddFilter("System.*", LogLevel.Error) - .AddFilter("DevProxy.Plugins.*", LogLevel.None) + .AddFilter("System.*", LogLevel.Error) + + .AddFilter("DevProxy.Plugins.*", level => + level >= pipelineLogLevel && + DevProxyCommand.IsPluginCommandRunning) .AddConsole(consoleOptions => { consoleOptions.FormatterName = formatterName; @@ -150,6 +156,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 e74cc844..57a6343b 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 161b1f38..630aa4f4 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;