dotnet-watch: add --verbose and --quiet command line flags

This commit is contained in:
Nate McMaster 2016-10-13 09:05:17 -07:00
parent f8a1a66ab7
commit 4cbd904154
8 changed files with 245 additions and 34 deletions

View File

@ -4,6 +4,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Watcher.Tools;
using Microsoft.Extensions.CommandLineUtils;
namespace Microsoft.DotNet.Watcher
@ -11,8 +13,10 @@ namespace Microsoft.DotNet.Watcher
internal class CommandLineOptions
{
public bool IsHelp { get; private set; }
public bool IsQuiet { get; private set; }
public bool IsVerbose { get; private set; }
public IList<string> RemainingArguments { get; private set; }
public static CommandLineOptions Parse(string[] args, TextWriter consoleOutput)
public static CommandLineOptions Parse(string[] args, TextWriter stdout, TextWriter stderr)
{
if (args == null)
{
@ -23,11 +27,16 @@ namespace Microsoft.DotNet.Watcher
{
Name = "dotnet watch",
FullName = "Microsoft DotNet File Watcher",
Out = consoleOutput,
Out = stdout,
Error = stderr,
AllowArgumentSeparator = true
};
app.HelpOption("-?|-h|--help");
var optQuiet = app.Option("-q|--quiet", "Suppresses all output except warnings and errors",
CommandOptionType.NoValue);
var optVerbose = app.Option("-v|--verbose", "Show verbose output",
CommandOptionType.NoValue);
app.OnExecute(() =>
{
@ -44,8 +53,16 @@ namespace Microsoft.DotNet.Watcher
return null;
}
if (optQuiet.HasValue() && optVerbose.HasValue())
{
stderr.WriteLine(Resources.Error_QuietAndVerboseSpecified.Bold().Red());
return null;
}
return new CommandLineOptions
{
IsQuiet = optQuiet.HasValue(),
IsVerbose = optVerbose.HasValue(),
RemainingArguments = app.RemainingArguments,
IsHelp = app.IsShowingInformation
};

View File

@ -50,12 +50,12 @@ namespace Microsoft.DotNet.Watcher
{
switch (logLevel)
{
case LogLevel.Trace: return "\x1b[35mtrace\x1b[39m";
case LogLevel.Debug: return "\x1b[35mdebug\x1b[39m";
case LogLevel.Trace: return "\x1b[35mtrce\x1b[39m";
case LogLevel.Debug: return "\x1b[35mdbug\x1b[39m";
case LogLevel.Information: return "\x1b[32minfo\x1b[39m";
case LogLevel.Warning: return "\x1b[33mwarn\x1b[39m";
case LogLevel.Error: return "\x1b[31mfail\x1b[39m";
case LogLevel.Critical: return "\x1b[31mcritical\x1b[39m";
case LogLevel.Critical: return "\x1b[31mcrit\x1b[39m";
}
throw new Exception("Unknown LogLevel");

View File

@ -121,7 +121,7 @@ namespace Microsoft.DotNet.Watcher
private Task<int> WaitForDotnetToExitAsync(string dotnetArguments, string workingDir, CancellationToken cancellationToken)
{
_logger.LogInformation($"Running dotnet with the following arguments: {dotnetArguments}");
_logger.LogDebug($"Running dotnet with the following arguments: {dotnetArguments}");
var dotnetWatcher = _processWatcherFactory();
int dotnetProcessId = dotnetWatcher.Start("dotnet", dotnetArguments, workingDir);

View File

@ -6,16 +6,18 @@ using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Watcher
{
public class Program
{
private readonly ILoggerFactory _loggerFactory;
private readonly ILoggerFactory _loggerFactory = new LoggerFactory();
private readonly CancellationToken _cancellationToken;
private readonly TextWriter _out;
private readonly TextWriter _stdout;
private readonly TextWriter _stderr;
public Program(TextWriter consoleOutput, CancellationToken cancellationToken)
public Program(TextWriter consoleOutput, TextWriter consoleError, CancellationToken cancellationToken)
{
if (consoleOutput == null)
{
@ -28,23 +30,8 @@ namespace Microsoft.DotNet.Watcher
}
_cancellationToken = cancellationToken;
_out = consoleOutput;
_loggerFactory = new LoggerFactory();
var logVar = Environment.GetEnvironmentVariable("DOTNET_WATCH_LOG_LEVEL");
LogLevel logLevel;
if (string.IsNullOrEmpty(logVar) || !Enum.TryParse<LogLevel>(logVar, out logLevel))
{
logLevel = LogLevel.Information;
}
var commandProvider = new CommandOutputProvider()
{
LogLevel = logLevel
};
_loggerFactory.AddProvider(commandProvider);
_stdout = consoleOutput;
_stderr = consoleError;
}
public static int Main(string[] args)
@ -60,7 +47,7 @@ namespace Microsoft.DotNet.Watcher
int exitCode;
try
{
exitCode = new Program(Console.Out, ctrlCTokenSource.Token)
exitCode = new Program(Console.Out, Console.Error, ctrlCTokenSource.Token)
.MainInternalAsync(args)
.GetAwaiter()
.GetResult();
@ -76,7 +63,7 @@ namespace Microsoft.DotNet.Watcher
private async Task<int> MainInternalAsync(string[] args)
{
var options = CommandLineOptions.Parse(args, _out);
var options = CommandLineOptions.Parse(args, _stdout, _stdout);
if (options == null)
{
// invalid args syntax
@ -88,6 +75,12 @@ namespace Microsoft.DotNet.Watcher
return 2;
}
var commandProvider = new CommandOutputProvider
{
LogLevel = ResolveLogLevel(options)
};
_loggerFactory.AddProvider(commandProvider);
var projectToWatch = Path.Combine(Directory.GetCurrentDirectory(), ProjectModel.Project.FileName);
await DotNetWatcher
@ -96,5 +89,24 @@ namespace Microsoft.DotNet.Watcher
return 0;
}
private LogLevel ResolveLogLevel(CommandLineOptions options)
{
if (options.IsQuiet)
{
return LogLevel.Warning;
}
bool globalVerbose;
bool.TryParse(Environment.GetEnvironmentVariable(CommandContext.Variables.Verbose), out globalVerbose);
if (options.IsVerbose // dotnet watch --verbose
|| globalVerbose) // dotnet --verbose watch
{
return LogLevel.Debug;
}
return LogLevel.Information;
}
}
}

View File

@ -0,0 +1,46 @@
// <auto-generated />
namespace Microsoft.DotNet.Watcher.Tools
{
using System.Globalization;
using System.Reflection;
using System.Resources;
internal static class Resources
{
private static readonly ResourceManager _resourceManager
= new ResourceManager("Microsoft.DotNet.Watcher.Tools.Resources", typeof(Resources).GetTypeInfo().Assembly);
/// <summary>
/// Cannot specify both '--quiet' and '--verbose' options.
/// </summary>
internal static string Error_QuietAndVerboseSpecified
{
get { return GetString("Error_QuietAndVerboseSpecified"); }
}
/// <summary>
/// Cannot specify both '--quiet' and '--verbose' options.
/// </summary>
internal static string FormatError_QuietAndVerboseSpecified()
{
return GetString("Error_QuietAndVerboseSpecified");
}
private static string GetString(string name, params string[] formatterNames)
{
var value = _resourceManager.GetString(name);
System.Diagnostics.Debug.Assert(value != null);
if (formatterNames != null)
{
for (var i = 0; i < formatterNames.Length; i++)
{
value = value.Replace("{" + formatterNames[i] + "}", "{" + i + "}");
}
}
return value;
}
}
}

View File

@ -20,7 +20,12 @@ Add `Microsoft.DotNet.Watcher.Tools` to the `tools` section of your `project.jso
dotnet watch [-?|-h|--help]
dotnet watch [[--] <dotnet arguments>...]
dotnet watch [options] [[--] <dotnet arguments>...]
Options:
-?|-h|--help Show help information
-q|--quiet Suppresses all output except warnings and errors
-v|--verbose Show verbose output
Add `watch` after `dotnet` in the command that you want to run:
@ -31,11 +36,10 @@ Add `watch` after `dotnet` in the command that you want to run:
| dotnet run --framework net451 -- --arg1 value1 | dotnet **watch** run --framework net451 -- --arg1 value1 |
| dotnet test | dotnet **watch** test |
### Advanced configuration options
### Environment variables
Configuration options can be passed to `dotnet watch` through environment variables. The available variables are:
Some configuration options can be passed to `dotnet watch` through environment variables. The available variables are:
| Variable | Effect |
| ---------------------------------------------- | -------------------------------------------------------- |
| DOTNET_USE_POLLING_FILE_WATCHER | If set to "1" or "true", `dotnet watch` will use a polling file watcher instead of CoreFx's `FileSystemWatcher`. Used when watching files on network shares or Docker mounted volumes. |
| DOTNET_WATCH_LOG_LEVEL | Used to set the logging level for messages coming from `dotnet watch`. Accepted values `None`, `Trace`, `Debug`, `Information`, `Warning`, `Error`, `Critical`. Default: `Information`. |

View File

@ -0,0 +1,123 @@
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<data name="Error_QuietAndVerboseSpecified" xml:space="preserve">
<value>Cannot specify both '--quiet' and '--verbose' options.</value>
</data>
</root>

View File

@ -21,7 +21,7 @@ namespace Microsoft.DotNet.Watcher.Tools.FunctionalTests
{
var stdout = new StringBuilder();
var options = CommandLineOptions.Parse(args, new StringWriter(stdout));
var options = CommandLineOptions.Parse(args, new StringWriter(stdout), new StringWriter());
Assert.True(options.IsHelp);
Assert.Contains("Usage: dotnet watch ", stdout.ToString());
@ -36,11 +36,20 @@ namespace Microsoft.DotNet.Watcher.Tools.FunctionalTests
{
var stdout = new StringBuilder();
var options = CommandLineOptions.Parse(args, new StringWriter(stdout));
var options = CommandLineOptions.Parse(args, new StringWriter(stdout), new StringWriter());
Assert.Equal(expected, options.RemainingArguments.ToArray());
Assert.False(options.IsHelp);
Assert.Empty(stdout.ToString());
}
[Fact]
public void CannotHaveQuietAndVerbose()
{
var sb = new StringBuilder();
var stderr = new StringWriter(sb);
Assert.Null(CommandLineOptions.Parse(new[] { "--quiet", "--verbose" }, new StringWriter(), stderr));
Assert.Contains(Resources.Error_QuietAndVerboseSpecified, sb.ToString());
}
}
}