Merge remote-tracking branch 'jonsequitur/tab-completion' into tab-completion

This commit is contained in:
Piotr Puszkiewicz 2017-03-10 17:37:26 -08:00
commit 23d4fb32f3
38 changed files with 360 additions and 449 deletions

View file

@ -16,7 +16,7 @@
<TemplateEngineTemplate2_0Version>1.0.0-beta1-20170209-117</TemplateEngineTemplate2_0Version> <TemplateEngineTemplate2_0Version>1.0.0-beta1-20170209-117</TemplateEngineTemplate2_0Version>
<PlatformAbstractionsVersion>1.0.3</PlatformAbstractionsVersion> <PlatformAbstractionsVersion>1.0.3</PlatformAbstractionsVersion>
<DependencyModelVersion>1.0.3</DependencyModelVersion> <DependencyModelVersion>1.0.3</DependencyModelVersion>
<CliCommandLineParserVersion>0.1.0-alpha-74</CliCommandLineParserVersion> <CliCommandLineParserVersion>0.1.0-alpha-84</CliCommandLineParserVersion>
</PropertyGroup> </PropertyGroup>

View file

@ -313,9 +313,12 @@ namespace Microsoft.DotNet.Tools.Common
return Path.GetFullPath(path); return Path.GetFullPath(path);
} }
public static void EnsureAllPathsExist(List<string> paths, string pathDoesNotExistLocalizedFormatString) public static void EnsureAllPathsExist(
IReadOnlyCollection<string> paths,
string pathDoesNotExistLocalizedFormatString)
{ {
var notExisting = new List<string>(); var notExisting = new List<string>();
foreach (var p in paths) foreach (var p in paths)
{ {
if (!File.Exists(p)) if (!File.Exists(p))
@ -329,7 +332,7 @@ namespace Microsoft.DotNet.Tools.Common
throw new GracefulException( throw new GracefulException(
string.Join( string.Join(
Environment.NewLine, Environment.NewLine,
notExisting.Select((p) => string.Format(pathDoesNotExistLocalizedFormatString, p)))); notExisting.Select(p => string.Format(pathDoesNotExistLocalizedFormatString, p))));
} }
} }
} }

10
src/dotnet/CommandBase.cs Normal file
View file

@ -0,0 +1,10 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DotNet.Cli
{
public abstract class CommandBase
{
public abstract int Execute();
}
}

View file

@ -11,7 +11,7 @@ namespace Microsoft.DotNet.Cli
Create.Option( Create.Option(
"-h|--help", "-h|--help",
"Show help information", "Show help information",
Accept.NoArguments, Accept.NoArguments(),
materialize: o => o.Option.Command().HelpView()); materialize: o => o.Option.Command().HelpView());
public static Option VerbosityOption() => public static Option VerbosityOption() =>

View file

@ -1,16 +0,0 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.DotNet.Cli.CommandLine;
namespace Microsoft.DotNet.Cli
{
internal abstract class DotNetSubCommandBase : CommandLineApplication
{
internal DotNetSubCommandBase() : base(throwOnUnexpectedArg: false)
{
}
public abstract int Run(string fileOrDirectory);
}
}

View file

@ -3,12 +3,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO;
using System.Linq; using System.Linq;
using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.Tools.Common;
namespace Microsoft.DotNet.Cli namespace Microsoft.DotNet.Cli
{ {
@ -18,60 +15,34 @@ namespace Microsoft.DotNet.Cli
protected abstract string FullCommandNameLocalized { get; } protected abstract string FullCommandNameLocalized { get; }
protected abstract string ArgumentName { get; } protected abstract string ArgumentName { get; }
protected abstract string ArgumentDescriptionLocalized { get; } protected abstract string ArgumentDescriptionLocalized { get; }
internal abstract List<Func<DotNetSubCommandBase>> SubCommands { get; } internal abstract Dictionary<string, Func<AppliedOption, CommandBase>> SubCommands { get; }
public int RunCommand(string[] args) public int RunCommand(string[] args)
{ {
DebugHelper.HandleDebugSwitch(ref args); DebugHelper.HandleDebugSwitch(ref args);
CommandLineApplication command = new CommandLineApplication(throwOnUnexpectedArg: true) var parser = Parser.Instance;
{
Name = $"dotnet {CommandName}",
FullName = FullCommandNameLocalized,
};
command.HelpOption("-h|--help"); var result = parser.ParseFrom($"dotnet {CommandName}", args);
command.Argument(ArgumentName, ArgumentDescriptionLocalized); Reporter.Output.WriteLine(result.Diagram());
foreach (var subCommandCreator in SubCommands) result.ShowHelpIfRequested();
{
var subCommand = subCommandCreator();
command.AddCommand(subCommand);
subCommand.OnExecute(() => { var subcommandName = result.Command().Name;
try
{
if (!command.Arguments.Any())
{
throw new GracefulException(CommonLocalizableStrings.RequiredArgumentNotPassed, ArgumentDescriptionLocalized);
}
var projectOrDirectory = command.Arguments.First().Value; var create = SubCommands[subcommandName];
if (string.IsNullOrEmpty(projectOrDirectory))
{
projectOrDirectory = PathUtility.EnsureTrailingSlash(Directory.GetCurrentDirectory());
}
return subCommand.Run(projectOrDirectory); var command = create(result["dotnet"][CommandName]);
}
catch (GracefulException e)
{
Reporter.Error.WriteLine(e.Message.Red());
subCommand.ShowHelp();
return 1;
}
});
}
try try
{ {
return command.Execute(args); return command.Execute();
} }
catch (GracefulException e) catch (GracefulException e)
{ {
Reporter.Error.WriteLine(e.Message.Red()); Reporter.Error.WriteLine(e.Message.Red());
command.ShowHelp(); result.ShowHelp();
return 1; return 1;
} }
catch (CommandParsingException e) catch (CommandParsingException e)

View file

@ -14,11 +14,9 @@ namespace Microsoft.DotNet.Cli
public static void ShowHelpIfRequested(this ParseResult parseResult) public static void ShowHelpIfRequested(this ParseResult parseResult)
{ {
if (parseResult.HasOption("help")) if (parseResult.AppliedOptions.Any(o => o.HasOption("help")))
{ {
// NOTE: this is a temporary stage in refactoring toward the ClicCommandLineParser being used at the CLI entry point. // NOTE: this is a temporary stage in refactoring toward the ClicCommandLineParser being used at the CLI entry point.
throw new HelpException(parseResult.Command().HelpView()); throw new HelpException(parseResult.Command().HelpView());
} }
} }

View file

@ -12,7 +12,7 @@ namespace Microsoft.DotNet.Cli
delimiters: Array.Empty<char>(), delimiters: Array.Empty<char>(),
options: Create.Command("dotnet", options: Create.Command("dotnet",
".NET Command Line Tools", ".NET Command Line Tools",
Accept.NoArguments, Accept.NoArguments(),
NewCommandParser.New(), NewCommandParser.New(),
RestoreCommandParser.Restore(), RestoreCommandParser.Restore(),
BuildCommandParser.Build(), BuildCommandParser.Build(),

View file

@ -54,7 +54,7 @@ namespace Microsoft.DotNet.Cli
["test"] = TestCommand.Run, ["test"] = TestCommand.Run,
["vstest"] = VSTestCommand.Run, ["vstest"] = VSTestCommand.Run,
["complete"] = CompleteCommand.Run, ["complete"] = CompleteCommand.Run,
["parse"] = ParseCommand.Run, ["parse"] = ParseCommand.Run
}; };
public static int Main(string[] args) public static int Main(string[] args)

View file

@ -3,6 +3,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using System.Net.Http; using System.Net.Http;
using System.Threading; using System.Threading;
using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.CommandLine;
@ -13,36 +14,48 @@ namespace Microsoft.DotNet.Cli
internal static class AddCommandParser internal static class AddCommandParser
{ {
public static Command Add() => public static Command Add() =>
Create.Command("add", Create.Command(
".NET Add Command", "add",
Accept.ExactlyOneArgument.DefaultToCurrentDirectory(), ".NET Add Command",
Create.Command("package", Accept.ExactlyOneArgument()
".NET Add Package reference Command", .DefaultToCurrentDirectory(),
Accept.ExactlyOneArgument Create.Command(
.WithSuggestionsFrom(QueryNuGet), CommonOptions.HelpOption(), "package",
Create.Option("-v|--version", ".NET Add Package reference Command",
"Version for the package to be added.", Accept.ExactlyOneArgument()
Accept.ExactlyOneArgument .WithSuggestionsFrom(QueryNuGet), CommonOptions.HelpOption(),
.With(name: "VERSION")), Create.Option("-v|--version",
Create.Option("-f|--framework", "Version for the package to be added.",
"Add reference only when targetting a specific framework", Accept.ExactlyOneArgument()
Accept.ExactlyOneArgument .With(name: "VERSION")
.With(name: "FRAMEWORK")), .ForwardAs(o => $"--version {o.Arguments.Single()}")),
Create.Option("-n|--no-restore ", Create.Option("-f|--framework",
"Add reference without performing restore preview and compatibility check."), "Add reference only when targetting a specific framework",
Create.Option("-s|--source", Accept.ExactlyOneArgument()
"Use specific NuGet package sources to use during the restore."), .With(name: "FRAMEWORK")
Create.Option("--package-directory", .ForwardAs(o => $"--framework {o.Arguments.Single()}")),
"Restore the packages to this Directory .", Create.Option("-n|--no-restore ",
Accept.ExactlyOneArgument "Add reference without performing restore preview and compatibility check."),
.With(name: "PACKAGE_DIRECTORY"))), Create.Option("-s|--source",
Create.Command("reference", "Use specific NuGet package sources to use during the restore.",
"Command to add project to project reference", Accept.ExactlyOneArgument()
Accept.OneOrMoreArguments, CommonOptions.HelpOption(), .With(name: "SOURCE")
Create.Option("-f|--framework", .ForwardAs(o => $"--source {o.Arguments.Single()}")),
"Add reference only when targetting a specific framework", Create.Option("--package-directory",
Accept.AnyOneOf(Suggest.TargetFrameworksFromProjectFile) "Restore the packages to this Directory .",
.With(name: "FRAMEWORK"))), CommonOptions.HelpOption()); Accept.ExactlyOneArgument()
.With(name: "PACKAGE_DIRECTORY")
.ForwardAs(o => $"--package-directory {o.Arguments.Single()}"))),
Create.Command(
"reference",
"Command to add project to project reference",
Accept.OneOrMoreArguments(),
CommonOptions.HelpOption(),
Create.Option("-f|--framework",
"Add reference only when targetting a specific framework",
Accept.AnyOneOf(Suggest.TargetFrameworksFromProjectFile)
.With(name: "FRAMEWORK"))),
CommonOptions.HelpOption());
public static IEnumerable<string> QueryNuGet(string match) public static IEnumerable<string> QueryNuGet(string match)
{ {

View file

@ -3,7 +3,9 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Add.PackageReference; using Microsoft.DotNet.Tools.Add.PackageReference;
using Microsoft.DotNet.Tools.Add.ProjectToProjectReference; using Microsoft.DotNet.Tools.Add.ProjectToProjectReference;
@ -16,11 +18,22 @@ namespace Microsoft.DotNet.Tools.Add
protected override string FullCommandNameLocalized => LocalizableStrings.NetAddCommand; protected override string FullCommandNameLocalized => LocalizableStrings.NetAddCommand;
protected override string ArgumentName => Constants.ProjectArgumentName; protected override string ArgumentName => Constants.ProjectArgumentName;
protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsProjectDescription; protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsProjectDescription;
internal override List<Func<DotNetSubCommandBase>> SubCommands =>
new List<Func<DotNetSubCommandBase>> internal override Dictionary<string, Func<AppliedOption, CommandBase>> SubCommands =>
new Dictionary<string, Func<AppliedOption, CommandBase>>
{ {
AddProjectToProjectReferenceCommand.Create, {
AddPackageReferenceCommand.Create, "reference",
add => new AddProjectToProjectReferenceCommand(
add["reference"],
add.Value<string>())
},
{
"package",
add => new AddPackageReferenceCommand(
add["package"],
add.Value<string>())
}
}; };
public static int Run(string[] args) public static int Run(string[] args)

View file

@ -1,105 +1,65 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Evaluation; using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.MSBuild; using Microsoft.DotNet.Tools.MSBuild;
using Microsoft.DotNet.Tools.NuGet; using Microsoft.DotNet.Tools.NuGet;
using NuGet.Frameworks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.DotNet.Tools.Add.PackageReference namespace Microsoft.DotNet.Tools.Add.PackageReference
{ {
internal class AddPackageReferenceCommand : DotNetSubCommandBase internal class AddPackageReferenceCommand : CommandBase
{ {
private CommandOption _versionOption; private readonly AppliedOption _appliedCommand;
private CommandOption _frameworkOption;
private CommandOption _noRestoreOption;
private CommandOption _sourceOption;
private CommandOption _packageDirectoryOption;
private CommandArgument _packageNameArgument;
public static DotNetSubCommandBase Create() private readonly string _packageId;
private readonly string _fileOrDirectory;
public AddPackageReferenceCommand(AppliedOption appliedCommand, string fileOrDirectory)
{ {
var command = new AddPackageReferenceCommand _appliedCommand = appliedCommand;
{ _fileOrDirectory = fileOrDirectory;
Name = "package", _packageId = appliedCommand.Value<string>();
FullName = LocalizableStrings.AppFullName,
Description = LocalizableStrings.AppDescription,
HandleRemainingArguments = false
};
command.HelpOption("-h|--help");
command._packageNameArgument = command.Argument( if ( string.IsNullOrWhiteSpace(_packageId) || _appliedCommand.Arguments.Count > 1)
$"<{LocalizableStrings.CmdPackage}>",
LocalizableStrings.CmdPackageDescription,
multipleValues: false);
command._versionOption = command.Option(
$"-v|--version <{LocalizableStrings.CmdVersion}>",
description: LocalizableStrings.CmdVersionDescription,
optionType: CommandOptionType.SingleValue);
command._frameworkOption = command.Option(
$"-f|--framework <{LocalizableStrings.CmdFramework}>",
LocalizableStrings.CmdFrameworkDescription,
CommandOptionType.SingleValue);
command._noRestoreOption = command.Option(
"-n|--no-restore ",
LocalizableStrings.CmdNoRestoreDescription,
CommandOptionType.NoValue);
command._sourceOption = command.Option(
$"-s|--source <{LocalizableStrings.CmdSource}>",
LocalizableStrings.CmdSourceDescription,
CommandOptionType.SingleValue);
command._packageDirectoryOption = command.Option(
$"--package-directory <{LocalizableStrings.CmdPackageDirectory}>",
LocalizableStrings.CmdPackageDirectoryDescription,
CommandOptionType.SingleValue);
return command;
}
public override int Run(string fileOrDirectory)
{
if (_packageNameArgument.Values.Count != 1 || string.IsNullOrWhiteSpace(_packageNameArgument.Value) || RemainingArguments.Count > 0)
{ {
throw new GracefulException(LocalizableStrings.SpecifyExactlyOnePackageReference); throw new GracefulException(LocalizableStrings.SpecifyExactlyOnePackageReference);
} }
}
public override int Execute()
{
var projectFilePath = string.Empty; var projectFilePath = string.Empty;
if (!File.Exists(fileOrDirectory)) if (!File.Exists(_fileOrDirectory))
{ {
projectFilePath = MsbuildProject.GetProjectFileFromDirectory(fileOrDirectory).FullName; projectFilePath = MsbuildProject.GetProjectFileFromDirectory(_fileOrDirectory).FullName;
} }
else else
{ {
projectFilePath = fileOrDirectory; projectFilePath = _fileOrDirectory;
} }
var tempDgFilePath = string.Empty; var tempDgFilePath = string.Empty;
if (!_noRestoreOption.HasValue()) if (!_appliedCommand.HasOption("no-restore"))
{ {
// Create a Dependency Graph file for the project // Create a Dependency Graph file for the project
tempDgFilePath = Path.GetTempFileName(); tempDgFilePath = Path.GetTempFileName();
GetProjectDependencyGraph(projectFilePath, tempDgFilePath); GetProjectDependencyGraph(projectFilePath, tempDgFilePath);
} }
var result = NuGetCommand.Run(TransformArgs(_packageNameArgument.Value, tempDgFilePath, projectFilePath)); var result = NuGetCommand.Run(
TransformArgs(
_packageId,
tempDgFilePath,
projectFilePath));
DisposeTemporaryFile(tempDgFilePath); DisposeTemporaryFile(tempDgFilePath);
return result; return result;
@ -136,7 +96,8 @@ namespace Microsoft.DotNet.Tools.Add.PackageReference
private string[] TransformArgs(string packageId, string tempDgFilePath, string projectFilePath) private string[] TransformArgs(string packageId, string tempDgFilePath, string projectFilePath)
{ {
var args = new List<string>(){ var args = new List<string>
{
"package", "package",
"add", "add",
"--package", "--package",
@ -145,27 +106,11 @@ namespace Microsoft.DotNet.Tools.Add.PackageReference
projectFilePath projectFilePath
}; };
if (_versionOption.HasValue()) args.AddRange(_appliedCommand
{ .OptionValuesToBeForwarded()
args.Add("--version"); .SelectMany(a => a.Split(' ')));
args.Add(_versionOption.Value());
} if (_appliedCommand.HasOption("no-restore"))
if (_sourceOption.HasValue())
{
args.Add("--source");
args.Add(_sourceOption.Value());
}
if (_frameworkOption.HasValue())
{
args.Add("--framework");
args.Add(_frameworkOption.Value());
}
if (_packageDirectoryOption.HasValue())
{
args.Add("--package-directory");
args.Add(_packageDirectoryOption.Value());
}
if (_noRestoreOption.HasValue())
{ {
args.Add("--no-restore"); args.Add("--no-restore");
} }

View file

@ -1,59 +1,46 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Build.Evaluation; using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common; using Microsoft.DotNet.Tools.Common;
using NuGet.Frameworks; using NuGet.Frameworks;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference
{ {
internal class AddProjectToProjectReferenceCommand : DotNetSubCommandBase internal class AddProjectToProjectReferenceCommand : CommandBase
{ {
private CommandOption _frameworkOption; private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;
public static DotNetSubCommandBase Create() public AddProjectToProjectReferenceCommand(AppliedOption appliedCommand, string fileOrDirectory)
{ {
var command = new AddProjectToProjectReferenceCommand() if (appliedCommand == null)
{ {
Name = "reference", throw new ArgumentNullException(nameof(appliedCommand));
FullName = LocalizableStrings.AppFullName, }
Description = LocalizableStrings.AppDescription, _appliedCommand = appliedCommand;
HandleRemainingArguments = true, _fileOrDirectory = fileOrDirectory;
ArgumentSeparatorHelpText = LocalizableStrings.AppHelpText,
};
command.HelpOption("-h|--help");
command._frameworkOption = command.Option(
$"-f|--framework <{CommonLocalizableStrings.CmdFramework}>",
LocalizableStrings.CmdFrameworkDescription,
CommandOptionType.SingleValue);
return command;
} }
public override int Run(string fileOrDirectory) public override int Execute()
{ {
var projects = new ProjectCollection(); var projects = new ProjectCollection();
MsbuildProject msbuildProj = MsbuildProject.FromFileOrDirectory(projects, fileOrDirectory); MsbuildProject msbuildProj = MsbuildProject.FromFileOrDirectory(projects, _fileOrDirectory);
if (RemainingArguments.Count == 0) var frameworkString = _appliedCommand["framework"].Value<string>();
{
throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneReferenceToAdd);
}
string frameworkString = _frameworkOption.Value(); PathUtility.EnsureAllPathsExist(_appliedCommand.Arguments, CommonLocalizableStrings.ReferenceDoesNotExist);
PathUtility.EnsureAllPathsExist(RemainingArguments, CommonLocalizableStrings.ReferenceDoesNotExist); List<MsbuildProject> refs = _appliedCommand.Arguments
List<MsbuildProject> refs = RemainingArguments .Select((r) => MsbuildProject.FromFile(projects, r))
.Select((r) => MsbuildProject.FromFile(projects, r)) .ToList();
.ToList();
if (frameworkString == null) if (frameworkString == null)
{ {
@ -64,8 +51,8 @@ namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference
if (!@ref.CanWorkOnFramework(tfm)) if (!@ref.CanWorkOnFramework(tfm))
{ {
Reporter.Error.Write(GetProjectNotCompatibleWithFrameworksDisplayString( Reporter.Error.Write(GetProjectNotCompatibleWithFrameworksDisplayString(
@ref, @ref,
msbuildProj.GetTargetFrameworks().Select((fx) => fx.GetShortFolderName()))); msbuildProj.GetTargetFrameworks().Select((fx) => fx.GetShortFolderName())));
return 1; return 1;
} }
} }
@ -77,9 +64,9 @@ namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference
if (!msbuildProj.IsTargetingFramework(framework)) if (!msbuildProj.IsTargetingFramework(framework))
{ {
Reporter.Error.WriteLine(string.Format( Reporter.Error.WriteLine(string.Format(
CommonLocalizableStrings.ProjectDoesNotTargetFramework, CommonLocalizableStrings.ProjectDoesNotTargetFramework,
msbuildProj.ProjectRootElement.FullPath, msbuildProj.ProjectRootElement.FullPath,
frameworkString)); frameworkString));
return 1; return 1;
} }
@ -88,18 +75,19 @@ namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference
if (!@ref.CanWorkOnFramework(framework)) if (!@ref.CanWorkOnFramework(framework))
{ {
Reporter.Error.Write(GetProjectNotCompatibleWithFrameworksDisplayString( Reporter.Error.Write(GetProjectNotCompatibleWithFrameworksDisplayString(
@ref, @ref,
new string[] { frameworkString })); new string[] { frameworkString }));
return 1; return 1;
} }
} }
} }
var relativePathReferences = RemainingArguments.Select((r) => var relativePathReferences = _appliedCommand.Arguments.Select((r) =>
PathUtility.GetRelativePath(msbuildProj.ProjectDirectory, Path.GetFullPath(r))).ToList(); PathUtility.GetRelativePath(msbuildProj.ProjectDirectory, Path.GetFullPath(r)))
.ToList();
int numberOfAddedReferences = msbuildProj.AddProjectToProjectReferences( int numberOfAddedReferences = msbuildProj.AddProjectToProjectReferences(
_frameworkOption.Value(), frameworkString,
relativePathReferences); relativePathReferences);
if (numberOfAddedReferences != 0) if (numberOfAddedReferences != 0)

View file

@ -13,12 +13,11 @@ namespace Microsoft.DotNet.Cli
Create.Command( Create.Command(
"build", "build",
LocalizableStrings.AppFullName, LocalizableStrings.AppFullName,
Accept.ZeroOrMoreArguments,
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
Create.Option( Create.Option(
"-o|--output", "-o|--output",
LocalizableStrings.OutputOptionDescription, LocalizableStrings.OutputOptionDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.OutputOptionName) .With(name: LocalizableStrings.OutputOptionName)
.ForwardAs(o => $"/p:OutputPath={o.Arguments.Single()}")), .ForwardAs(o => $"/p:OutputPath={o.Arguments.Single()}")),
CommonOptions.FrameworkOption(), CommonOptions.FrameworkOption(),
@ -31,7 +30,7 @@ namespace Microsoft.DotNet.Cli
Create.Option( Create.Option(
"--no-dependencies", "--no-dependencies",
LocalizableStrings.NoDependenciesOptionDescription, LocalizableStrings.NoDependenciesOptionDescription,
Accept.NoArguments Accept.NoArguments()
.ForwardAs("/p:BuildProjectReferences=false")), .ForwardAs("/p:BuildProjectReferences=false")),
CommonOptions.VerbosityOption()); CommonOptions.VerbosityOption());
} }

View file

@ -17,7 +17,7 @@ namespace Microsoft.DotNet.Cli
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
Create.Option("-o|--output", Create.Option("-o|--output",
LocalizableStrings.CmdOutputDirDescription, LocalizableStrings.CmdOutputDirDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdOutputDir) .With(name: LocalizableStrings.CmdOutputDir)
.ForwardAs(o => $"/p:OutputPath={o.Arguments.Single()}")), .ForwardAs(o => $"/p:OutputPath={o.Arguments.Single()}")),
CommonOptions.FrameworkOption(), CommonOptions.FrameworkOption(),

View file

@ -11,10 +11,11 @@ namespace Microsoft.DotNet.Cli
public static Command Complete() => public static Command Complete() =>
Create.Command( Create.Command(
"complete", "", "complete", "",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "path"), .With(name: "path"),
Create.Option("--position", "", Create.Option("--position", "",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "command"))); .With(name: "command")
.MaterializeAs(o => int.Parse(o.Arguments.Single()))));
} }
} }

View file

@ -10,14 +10,14 @@ namespace Microsoft.DotNet.Cli
public static Command List() => public static Command List() =>
Create.Command("list", Create.Command("list",
".NET List Command", ".NET List Command",
Accept.ZeroOrOneArgument Accept.ZeroOrOneArgument()
.With(name: "PROJECT", .With(name: "PROJECT",
description: description:
"The project file to operate on. If a file is not specified, the command will search the current directory for one.") "The project file to operate on. If a file is not specified, the command will search the current directory for one.")
.DefaultToCurrentDirectory(), .DefaultToCurrentDirectory(),
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
Create.Command("reference", "Command to list project to project references", Create.Command("reference", "Command to list project to project references",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "PROJECT", .With(name: "PROJECT",
description: description:
"The project file to operate on. If a file is not specified, the command will search the current directory for one."), "The project file to operate on. If a file is not specified, the command will search the current directory for one."),

View file

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.List.ProjectToProjectReferences; using Microsoft.DotNet.Tools.List.ProjectToProjectReferences;
@ -15,10 +16,11 @@ namespace Microsoft.DotNet.Tools.List
protected override string FullCommandNameLocalized => LocalizableStrings.NetListCommand; protected override string FullCommandNameLocalized => LocalizableStrings.NetListCommand;
protected override string ArgumentName => Constants.ProjectArgumentName; protected override string ArgumentName => Constants.ProjectArgumentName;
protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsProjectDescription; protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsProjectDescription;
internal override List<Func<DotNetSubCommandBase>> SubCommands =>
new List<Func<DotNetSubCommandBase>> internal override Dictionary<string, Func<AppliedOption, CommandBase>> SubCommands =>
new Dictionary<string, Func<AppliedOption, CommandBase>>
{ {
ListProjectToProjectReferencesCommand.Create, { "list", o => new ListProjectToProjectReferencesCommand(o) }
}; };
public static int Run(string[] args) public static int Run(string[] args)

View file

@ -1,40 +1,40 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.Build.Evaluation; using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using System.Linq;
namespace Microsoft.DotNet.Tools.List.ProjectToProjectReferences namespace Microsoft.DotNet.Tools.List.ProjectToProjectReferences
{ {
internal class ListProjectToProjectReferencesCommand : DotNetSubCommandBase internal class ListProjectToProjectReferencesCommand : CommandBase
{ {
public static DotNetSubCommandBase Create() private readonly string _fileOrDirectory;
public ListProjectToProjectReferencesCommand(AppliedOption appliedCommand)
{ {
var command = new ListProjectToProjectReferencesCommand() if (appliedCommand == null)
{ {
Name = "reference", throw new ArgumentNullException(nameof(appliedCommand));
FullName = LocalizableStrings.AppFullName, }
Description = LocalizableStrings.AppDescription,
};
command.HelpOption("-h|--help"); _fileOrDirectory = appliedCommand.Arguments.Single();
return command;
} }
public override int Run(string fileOrDirectory) public override int Execute()
{ {
var msbuildProj = MsbuildProject.FromFileOrDirectory(new ProjectCollection(), fileOrDirectory); var msbuildProj = MsbuildProject.FromFileOrDirectory(new ProjectCollection(), _fileOrDirectory);
var p2ps = msbuildProj.GetProjectToProjectReferences(); var p2ps = msbuildProj.GetProjectToProjectReferences();
if (!p2ps.Any()) if (!p2ps.Any())
{ {
Reporter.Output.WriteLine(string.Format( Reporter.Output.WriteLine(string.Format(
CommonLocalizableStrings.NoReferencesFound, CommonLocalizableStrings.NoReferencesFound,
CommonLocalizableStrings.P2P, CommonLocalizableStrings.P2P,
fileOrDirectory)); _fileOrDirectory));
return 0; return 0;
} }

View file

@ -11,7 +11,7 @@ namespace Microsoft.DotNet.Cli
Create.Command("new", Create.Command("new",
"Initialize .NET projects.", "Initialize .NET projects.",
Accept Accept
.ExactlyOneArgument .ExactlyOneArgument()
.WithSuggestionsFrom( .WithSuggestionsFrom(
"console", "console",
"classlib", "classlib",

View file

@ -15,11 +15,11 @@ namespace Microsoft.DotNet.Cli
"Show version information"), "Show version information"),
Create.Option("-v|--verbosity", Create.Option("-v|--verbosity",
"The verbosity of logging to use. Allowed values: Debug, Verbose, Information, Minimal, Warning, Error.", "The verbosity of logging to use. Allowed values: Debug, Verbose, Information, Minimal, Warning, Error.",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "verbosity")), .With(name: "verbosity")),
Create.Command("delete", Create.Command("delete",
"Deletes a package from the server.", "Deletes a package from the server.",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "root", .With(name: "root",
description: "The Package Id and version."), description: "The Package Id and version."),
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
@ -27,13 +27,13 @@ namespace Microsoft.DotNet.Cli
"Forces the application to run using an invariant, English-based culture."), "Forces the application to run using an invariant, English-based culture."),
Create.Option("-s|--source", Create.Option("-s|--source",
"Specifies the server URL", "Specifies the server URL",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "source")), .With(name: "source")),
Create.Option("--non-interactive", Create.Option("--non-interactive",
"Do not prompt for user input or confirmations."), "Do not prompt for user input or confirmations."),
Create.Option("-k|--api-key", Create.Option("-k|--api-key",
"The API key for the server.", "The API key for the server.",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "apiKey"))), .With(name: "apiKey"))),
Create.Command("locals", Create.Command("locals",
"Clears or lists local NuGet resources such as http requests cache, packages cache or machine-wide global packages folder.", "Clears or lists local NuGet resources such as http requests cache, packages cache or machine-wide global packages folder.",
@ -54,21 +54,21 @@ namespace Microsoft.DotNet.Cli
"Forces the application to run using an invariant, English-based culture."), "Forces the application to run using an invariant, English-based culture."),
Create.Option("-s|--source", Create.Option("-s|--source",
"Specifies the server URL", "Specifies the server URL",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "source")), .With(name: "source")),
Create.Option("-ss|--symbol-source", Create.Option("-ss|--symbol-source",
"Specifies the symbol server URL. If not specified, nuget.smbsrc.net is used when pushing to nuget.org.", "Specifies the symbol server URL. If not specified, nuget.smbsrc.net is used when pushing to nuget.org.",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "source")), .With(name: "source")),
Create.Option("-t|--timeout", Create.Option("-t|--timeout",
"Specifies the timeout for pushing to a server in seconds. Defaults to 300 seconds (5 minutes).", "Specifies the timeout for pushing to a server in seconds. Defaults to 300 seconds (5 minutes).",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "timeout")), .With(name: "timeout")),
Create.Option("-k|--api-key", "The API key for the server.", Create.Option("-k|--api-key", "The API key for the server.",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "apiKey")), .With(name: "apiKey")),
Create.Option("-sk|--symbol-api-key", "The API key for the symbol server.", Create.Option("-sk|--symbol-api-key", "The API key for the symbol server.",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "apiKey")), .With(name: "apiKey")),
Create.Option("-d|--disable-buffering", Create.Option("-d|--disable-buffering",
"Disable buffering when pushing to an HTTP(S) server to decrease memory usage."), "Disable buffering when pushing to an HTTP(S) server to decrease memory usage."),

View file

@ -18,7 +18,7 @@ namespace Microsoft.DotNet.Cli
Create.Option( Create.Option(
"-o|--output", "-o|--output",
LocalizableStrings.CmdOutputDirDescription, LocalizableStrings.CmdOutputDirDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdOutputDir) .With(name: LocalizableStrings.CmdOutputDir)
.ForwardAs(o => $"/p:PackageOutputPath={o.Arguments.Single()}")), .ForwardAs(o => $"/p:PackageOutputPath={o.Arguments.Single()}")),
Create.Option("--no-build", Create.Option("--no-build",

View file

@ -13,22 +13,20 @@ namespace Microsoft.DotNet.Cli
Create.Command( Create.Command(
"publish", "publish",
LocalizableStrings.AppFullName, LocalizableStrings.AppFullName,
Accept.ZeroOrMoreArguments, Accept.ZeroOrMoreArguments(),
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
CommonOptions.FrameworkOption(), CommonOptions.FrameworkOption(),
CommonOptions.RuntimeOption(), CommonOptions.RuntimeOption(),
Create.Option( Create.Option(
"-o|--output", "-o|--output",
LocalizableStrings.OutputOptionDescription, LocalizableStrings.OutputOptionDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.OutputOption) .With(name: LocalizableStrings.OutputOption)
.ForwardAs(o => $"/p:PublishDir={o.Arguments.Single()}")), .ForwardAs(o => $"/p:PublishDir={o.Arguments.Single()}")),
CommonOptions.ConfigurationOption(), CommonOptions.ConfigurationOption(),
CommonOptions.VersionSuffixOption(),
Create.Option(
"--filter", "--filter",
LocalizableStrings.FilterProjOptionDescription, LocalizableStrings.FilterProjOptionDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.FilterProjOption) .With(name: LocalizableStrings.FilterProjOption)
.ForwardAs(o => $"/p:FilterProjectFiles={o.Arguments.Single()}")), .ForwardAs(o => $"/p:FilterProjectFiles={o.Arguments.Single()}")),
CommonOptions.VerbosityOption()); CommonOptions.VerbosityOption());

View file

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Remove.PackageReference; using Microsoft.DotNet.Tools.Remove.PackageReference;
using Microsoft.DotNet.Tools.Remove.ProjectToProjectReference; using Microsoft.DotNet.Tools.Remove.ProjectToProjectReference;
@ -16,11 +17,12 @@ namespace Microsoft.DotNet.Tools.Remove
protected override string FullCommandNameLocalized => LocalizableStrings.NetRemoveCommand; protected override string FullCommandNameLocalized => LocalizableStrings.NetRemoveCommand;
protected override string ArgumentName => Constants.ProjectArgumentName; protected override string ArgumentName => Constants.ProjectArgumentName;
protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsProjectDescription; protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsProjectDescription;
internal override List<Func<DotNetSubCommandBase>> SubCommands =>
new List<Func<DotNetSubCommandBase>> internal override Dictionary<string, Func<AppliedOption, CommandBase>> SubCommands =>
new Dictionary<string, Func<AppliedOption, CommandBase>>
{ {
RemoveProjectToProjectReferenceCommand.Create, { "reference", o => new RemoveProjectToProjectReferenceCommand(o) },
RemovePackageReferenceCommand.Create { "package", o => new RemovePackageReferenceCommand(o) }
}; };
public static int Run(string[] args) public static int Run(string[] args)

View file

@ -10,7 +10,7 @@ namespace Microsoft.DotNet.Cli
public static Command Remove() => public static Command Remove() =>
Create.Command("remove", Create.Command("remove",
".NET Remove Command", ".NET Remove Command",
Accept.ZeroOrOneArgument Accept.ZeroOrOneArgument()
.With(name: "PROJECT") .With(name: "PROJECT")
.DefaultToCurrentDirectory(), .DefaultToCurrentDirectory(),
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
@ -23,7 +23,7 @@ namespace Microsoft.DotNet.Cli
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
Create.Option("-f|--framework", Create.Option("-f|--framework",
"Remove reference only when targetting a specific framework", "Remove reference only when targetting a specific framework",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "FRAMEWORK")))); .With(name: "FRAMEWORK"))));
} }
} }

View file

@ -1,61 +1,50 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using Microsoft.Build.Evaluation; using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.MSBuild;
using Microsoft.DotNet.Tools.NuGet; using Microsoft.DotNet.Tools.NuGet;
using NuGet.Frameworks;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
namespace Microsoft.DotNet.Tools.Remove.PackageReference namespace Microsoft.DotNet.Tools.Remove.PackageReference
{ {
internal class RemovePackageReferenceCommand : DotNetSubCommandBase internal class RemovePackageReferenceCommand : CommandBase
{ {
private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;
public static DotNetSubCommandBase Create() public RemovePackageReferenceCommand(AppliedOption appliedCommand)
{ {
var command = new RemovePackageReferenceCommand if (appliedCommand == null)
{ {
Name = "package", throw new ArgumentNullException(nameof(appliedCommand));
FullName = LocalizableStrings.AppFullName, }
Description = LocalizableStrings.AppDescription, if (_appliedCommand.Arguments.Count != 1)
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.AppHelpText,
};
command.HelpOption("-h|--help");
return command;
}
public override int Run(string fileOrDirectory)
{
if (RemainingArguments.Count != 1)
{ {
throw new GracefulException(LocalizableStrings.SpecifyExactlyOnePackageReference); throw new GracefulException(LocalizableStrings.SpecifyExactlyOnePackageReference);
} }
_appliedCommand = appliedCommand;
_fileOrDirectory = appliedCommand.Arguments.Single();
}
public override int Execute()
{
var projectFilePath = string.Empty; var projectFilePath = string.Empty;
if (!File.Exists(fileOrDirectory)) if (!File.Exists(_fileOrDirectory))
{ {
projectFilePath = MsbuildProject.GetProjectFileFromDirectory(fileOrDirectory).FullName; projectFilePath = MsbuildProject.GetProjectFileFromDirectory(_fileOrDirectory).FullName;
} }
else else
{ {
projectFilePath = fileOrDirectory; projectFilePath = _fileOrDirectory;
} }
var packageToRemove = RemainingArguments.First(); var packageToRemove = _appliedCommand.Arguments.Single();
var result = NuGetCommand.Run(TransformArgs(packageToRemove, projectFilePath)); var result = NuGetCommand.Run(TransformArgs(packageToRemove, projectFilePath));
return result; return result;
@ -63,7 +52,8 @@ namespace Microsoft.DotNet.Tools.Remove.PackageReference
private string[] TransformArgs(string packageId, string projectFilePath) private string[] TransformArgs(string packageId, string projectFilePath)
{ {
return new string[]{ return new string[]
{
"package", "package",
"remove", "remove",
"--package", "--package",

View file

@ -1,6 +1,8 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.Build.Evaluation; using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine; using Microsoft.DotNet.Cli.CommandLine;
@ -8,42 +10,34 @@ using Microsoft.DotNet.Cli.Utils;
namespace Microsoft.DotNet.Tools.Remove.ProjectToProjectReference namespace Microsoft.DotNet.Tools.Remove.ProjectToProjectReference
{ {
internal class RemoveProjectToProjectReferenceCommand : DotNetSubCommandBase internal class RemoveProjectToProjectReferenceCommand : CommandBase
{ {
private CommandOption _frameworkOption; private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;
public static DotNetSubCommandBase Create() public RemoveProjectToProjectReferenceCommand(AppliedOption appliedCommand)
{ {
var command = new RemoveProjectToProjectReferenceCommand() if (appliedCommand == null)
{ {
Name = "reference", throw new ArgumentNullException(nameof(appliedCommand));
FullName = LocalizableStrings.AppFullName, }
Description = LocalizableStrings.AppDescription,
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.AppHelpText,
};
command.HelpOption("-h|--help"); if (_appliedCommand.Arguments.Count == 0)
command._frameworkOption = command.Option(
$"-f|--framework <{CommonLocalizableStrings.CmdFramework}>",
LocalizableStrings.CmdFrameworkDescription,
CommandOptionType.SingleValue);
return command;
}
public override int Run(string fileOrDirectory)
{
var msbuildProj = MsbuildProject.FromFileOrDirectory(new ProjectCollection(), fileOrDirectory);
if (RemainingArguments.Count == 0)
{ {
throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneReferenceToRemove); throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneReferenceToRemove);
} }
_appliedCommand = appliedCommand;
_fileOrDirectory = appliedCommand.Arguments.Single();
}
public override int Execute()
{
var msbuildProj = MsbuildProject.FromFileOrDirectory(new ProjectCollection(), _fileOrDirectory);
int numberOfRemovedReferences = msbuildProj.RemoveProjectToProjectReferences( int numberOfRemovedReferences = msbuildProj.RemoveProjectToProjectReferences(
_frameworkOption.Value(), _appliedCommand["framework"].Value<string>(),
RemainingArguments); _appliedCommand.Arguments);
if (numberOfRemovedReferences != 0) if (numberOfRemovedReferences != 0)
{ {

View file

@ -13,52 +13,52 @@ namespace Microsoft.DotNet.Cli
Create.Command( Create.Command(
"restore", "restore",
LocalizableStrings.AppFullName, LocalizableStrings.AppFullName,
Accept.ZeroOrMoreArguments, Accept.ZeroOrMoreArguments(),
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
Create.Option( Create.Option(
"-s|--source", "-s|--source",
LocalizableStrings.CmdSourceOptionDescription, LocalizableStrings.CmdSourceOptionDescription,
Accept.OneOrMoreArguments Accept.OneOrMoreArguments()
.With(name: LocalizableStrings.CmdSourceOption) .With(name: LocalizableStrings.CmdSourceOption)
.ForwardAs(o => $"/p:RestoreSources={string.Join("%3B", o.Arguments)}")), .ForwardAs(o => $"/p:RestoreSources={string.Join("%3B", o.Arguments)}")),
Create.Option( Create.Option(
"-r|--runtime", "-r|--runtime",
LocalizableStrings.CmdRuntimeOptionDescription, LocalizableStrings.CmdRuntimeOptionDescription,
Accept.OneOrMoreArguments Accept.OneOrMoreArguments()
.WithSuggestionsFrom(_ => Suggest.RunTimesFromProjectFile()) .WithSuggestionsFrom(_ => Suggest.RunTimesFromProjectFile())
.With(name: LocalizableStrings.CmdRuntimeOption) .With(name: LocalizableStrings.CmdRuntimeOption)
.ForwardAs(o => $"/p:RuntimeIdentifiers={string.Join("%3B", o.Arguments)}")), .ForwardAs(o => $"/p:RuntimeIdentifiers={string.Join("%3B", o.Arguments)}")),
Create.Option( Create.Option(
"--packages", "--packages",
LocalizableStrings.CmdPackagesOptionDescription, LocalizableStrings.CmdPackagesOptionDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdPackagesOption) .With(name: LocalizableStrings.CmdPackagesOption)
.ForwardAs(o => $"/p:RestorePackagesPath={o.Arguments.Single()}")), .ForwardAs(o => $"/p:RestorePackagesPath={o.Arguments.Single()}")),
Create.Option( Create.Option(
"--disable-parallel", "--disable-parallel",
LocalizableStrings.CmdDisableParallelOptionDescription, LocalizableStrings.CmdDisableParallelOptionDescription,
Accept.NoArguments Accept.NoArguments()
.ForwardAs("/p:RestoreDisableParallel=true")), .ForwardAs("/p:RestoreDisableParallel=true")),
Create.Option( Create.Option(
"--configfile", "--configfile",
LocalizableStrings.CmdConfigFileOptionDescription, LocalizableStrings.CmdConfigFileOptionDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdConfigFileOption) .With(name: LocalizableStrings.CmdConfigFileOption)
.ForwardAs(o => $"/p:RestoreConfigFile={o.Arguments.Single()}")), .ForwardAs(o => $"/p:RestoreConfigFile={o.Arguments.Single()}")),
Create.Option( Create.Option(
"--no-cache", "--no-cache",
LocalizableStrings.CmdNoCacheOptionDescription, LocalizableStrings.CmdNoCacheOptionDescription,
Accept.NoArguments Accept.NoArguments()
.ForwardAs("/p:RestoreNoCache=true")), .ForwardAs("/p:RestoreNoCache=true")),
Create.Option( Create.Option(
"--ignore-failed-sources", "--ignore-failed-sources",
LocalizableStrings.CmdIgnoreFailedSourcesOptionDescription, LocalizableStrings.CmdIgnoreFailedSourcesOptionDescription,
Accept.NoArguments Accept.NoArguments()
.ForwardAs("/p:RestoreIgnoreFailedSources=true")), .ForwardAs("/p:RestoreIgnoreFailedSources=true")),
Create.Option( Create.Option(
"--no-dependencies", "--no-dependencies",
LocalizableStrings.CmdNoDependenciesOptionDescription, LocalizableStrings.CmdNoDependenciesOptionDescription,
Accept.NoArguments Accept.NoArguments()
.ForwardAs("/p:RestoreRecursive=false")), .ForwardAs("/p:RestoreRecursive=false")),
CommonOptions.VerbosityOption()); CommonOptions.VerbosityOption());
} }

View file

@ -14,7 +14,7 @@ namespace Microsoft.DotNet.Cli
Create.Command( Create.Command(
"run", "run",
LocalizableStrings.AppFullName, LocalizableStrings.AppFullName,
Accept.ZeroOrMoreArguments Accept.ZeroOrMoreArguments()
.MaterializeAs(o => .MaterializeAs(o =>
{ {
return new RunCommand() return new RunCommand()
@ -31,6 +31,6 @@ namespace Microsoft.DotNet.Cli
Create.Option( Create.Option(
"-p|--project", "-p|--project",
LocalizableStrings.CommandOptionProjectDescription, LocalizableStrings.CommandOptionProjectDescription,
Accept.ExactlyOneArgument)); Accept.ExactlyOneArgument()));
} }
} }

View file

@ -4,6 +4,7 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Sln.Add; using Microsoft.DotNet.Tools.Sln.Add;
using Microsoft.DotNet.Tools.Sln.List; using Microsoft.DotNet.Tools.Sln.List;
@ -17,12 +18,13 @@ namespace Microsoft.DotNet.Tools.Sln
protected override string FullCommandNameLocalized => LocalizableStrings.AppFullName; protected override string FullCommandNameLocalized => LocalizableStrings.AppFullName;
protected override string ArgumentName => Constants.SolutionArgumentName; protected override string ArgumentName => Constants.SolutionArgumentName;
protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsSolutionDescription; protected override string ArgumentDescriptionLocalized => CommonLocalizableStrings.ArgumentsSolutionDescription;
internal override List<Func<DotNetSubCommandBase>> SubCommands =>
new List<Func<DotNetSubCommandBase>> internal override Dictionary<string, Func<AppliedOption, CommandBase>> SubCommands =>
new Dictionary<string, Func<AppliedOption, CommandBase>>
{ {
AddProjectToSolutionCommand.Create, { "add", o => new AddProjectToSolutionCommand(o) },
ListProjectsInSolutionCommand.Create, { "list", o => new ListProjectsInSolutionCommand(o) },
RemoveProjectFromSolutionCommand.Create { "remove", o => new RemoveProjectFromSolutionCommand(o) }
}; };
public static int Run(string[] args) public static int Run(string[] args)

View file

@ -13,12 +13,12 @@ namespace Microsoft.DotNet.Cli
CommonOptions.HelpOption(), CommonOptions.HelpOption(),
Create.Command("add", Create.Command("add",
".NET Add project(s) to a solution file Command", ".NET Add project(s) to a solution file Command",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "SLN_FILE"), .With(name: "SLN_FILE"),
CommonOptions.HelpOption()), CommonOptions.HelpOption()),
Create.Command("list", Create.Command("list",
"List all projects in the solution.", "List all projects in the solution.",
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: "SLN_FILE"), .With(name: "SLN_FILE"),
CommonOptions.HelpOption()), CommonOptions.HelpOption()),
Create.Command("remove", Create.Command("remove",

View file

@ -1,49 +1,50 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common; using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.Sln;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Microsoft.DotNet.Tools.Sln.Add namespace Microsoft.DotNet.Tools.Sln.Add
{ {
internal class AddProjectToSolutionCommand : DotNetSubCommandBase internal class AddProjectToSolutionCommand : CommandBase
{ {
public static DotNetSubCommandBase Create() private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;
public AddProjectToSolutionCommand(AppliedOption appliedCommand)
{ {
var command = new AddProjectToSolutionCommand() if (appliedCommand == null)
{ {
Name = "add", throw new ArgumentNullException(nameof(appliedCommand));
FullName = LocalizableStrings.AddAppFullName, }
Description = LocalizableStrings.AddSubcommandHelpText, _appliedCommand = appliedCommand;
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.AddSubcommandHelpText,
};
command.HelpOption("-h|--help"); _fileOrDirectory = appliedCommand.Arguments.Single();
return command;
} }
public override int Run(string fileOrDirectory) public override int Execute()
{ {
SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(fileOrDirectory); SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(_fileOrDirectory);
if (RemainingArguments.Count == 0) if (_appliedCommand.Arguments.Count == 0)
{ {
throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneProjectToAdd); throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneProjectToAdd);
} }
PathUtility.EnsureAllPathsExist(RemainingArguments, CommonLocalizableStrings.ProjectDoesNotExist); PathUtility.EnsureAllPathsExist(_appliedCommand.Arguments, CommonLocalizableStrings.ProjectDoesNotExist);
var fullProjectPaths = RemainingArguments.Select((p) => Path.GetFullPath(p)).ToList();
var fullProjectPaths = _appliedCommand.Arguments
.Select(Path.GetFullPath)
.ToList();
var preAddProjectCount = slnFile.Projects.Count;
int preAddProjectCount = slnFile.Projects.Count;
foreach (var fullProjectPath in fullProjectPaths) foreach (var fullProjectPath in fullProjectPaths)
{ {
slnFile.AddProject(fullProjectPath); slnFile.AddProject(fullProjectPath);

View file

@ -1,33 +1,32 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Linq;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common; using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.Sln;
namespace Microsoft.DotNet.Tools.Sln.List namespace Microsoft.DotNet.Tools.Sln.List
{ {
internal class ListProjectsInSolutionCommand : DotNetSubCommandBase internal class ListProjectsInSolutionCommand : CommandBase
{ {
public static DotNetSubCommandBase Create() private readonly string _fileOrDirectory;
public ListProjectsInSolutionCommand(AppliedOption appliedCommand)
{ {
var command = new ListProjectsInSolutionCommand() if (appliedCommand == null)
{ {
Name = "list", throw new ArgumentNullException(nameof(appliedCommand));
FullName = LocalizableStrings.ListAppFullName, }
Description = LocalizableStrings.ListSubcommandHelpText, _fileOrDirectory = appliedCommand.Arguments.Single();
};
command.HelpOption("-h|--help");
return command;
} }
public override int Run(string fileOrDirectory) public override int Execute()
{ {
SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(fileOrDirectory); SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(_fileOrDirectory);
if (slnFile.Projects.Count == 0) if (slnFile.Projects.Count == 0)
{ {
Reporter.Output.WriteLine(CommonLocalizableStrings.NoProjectsFound); Reporter.Output.WriteLine(CommonLocalizableStrings.NoProjectsFound);

View file

@ -1,49 +1,47 @@
// Copyright (c) .NET Foundation and contributors. All rights reserved. // Copyright (c) .NET Foundation and contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information. // Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli; using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Sln.Internal; using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Cli.Utils; using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common; using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.Sln;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace Microsoft.DotNet.Tools.Sln.Remove namespace Microsoft.DotNet.Tools.Sln.Remove
{ {
internal class RemoveProjectFromSolutionCommand : DotNetSubCommandBase internal class RemoveProjectFromSolutionCommand : CommandBase
{ {
public static DotNetSubCommandBase Create() private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;
public RemoveProjectFromSolutionCommand(AppliedOption appliedCommand)
{ {
var command = new RemoveProjectFromSolutionCommand() if (appliedCommand == null)
{ {
Name = "remove", throw new ArgumentNullException(nameof(appliedCommand));
FullName = LocalizableStrings.RemoveAppFullName, }
Description = LocalizableStrings.RemoveSubcommandHelpText,
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.RemoveSubcommandHelpText,
};
command.HelpOption("-h|--help"); if (_appliedCommand.Arguments.Count == 0)
return command;
}
public override int Run(string fileOrDirectory)
{
SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(fileOrDirectory);
if (RemainingArguments.Count == 0)
{ {
throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneProjectToRemove); throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneProjectToRemove);
} }
var relativeProjectPaths = RemainingArguments.Select((p) => _appliedCommand = appliedCommand;
PathUtility.GetRelativePath( _fileOrDirectory = appliedCommand.Arguments.Single();
PathUtility.EnsureTrailingSlash(slnFile.BaseDirectory), }
Path.GetFullPath(p))).ToList();
public override int Execute()
{
SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(_fileOrDirectory);
var relativeProjectPaths = _appliedCommand.Arguments.Select(p =>
PathUtility.GetRelativePath(
PathUtility.EnsureTrailingSlash(slnFile.BaseDirectory),
Path.GetFullPath(p)))
.ToList();
bool slnChanged = false; bool slnChanged = false;
foreach (var path in relativeProjectPaths) foreach (var path in relativeProjectPaths)

View file

@ -16,7 +16,7 @@ namespace Microsoft.DotNet.Cli
Create.Option( Create.Option(
"-s|--settings", "-s|--settings",
LocalizableStrings.CmdSettingsDescription, LocalizableStrings.CmdSettingsDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdSettingsFile) .With(name: LocalizableStrings.CmdSettingsFile)
.ForwardAs(o => $"/p:VSTestSetting={o.Arguments.Single()}")), .ForwardAs(o => $"/p:VSTestSetting={o.Arguments.Single()}")),
Create.Option( Create.Option(
@ -27,19 +27,19 @@ namespace Microsoft.DotNet.Cli
Create.Option( Create.Option(
"--filter", "--filter",
LocalizableStrings.CmdTestCaseFilterDescription, LocalizableStrings.CmdTestCaseFilterDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdTestCaseFilterExpression) .With(name: LocalizableStrings.CmdTestCaseFilterExpression)
.ForwardAs(o => $"/p:VSTestTestCaseFilter={o.Arguments.Single()}")), .ForwardAs(o => $"/p:VSTestTestCaseFilter={o.Arguments.Single()}")),
Create.Option( Create.Option(
"-a|--test-adapter-path", "-a|--test-adapter-path",
LocalizableStrings.CmdTestAdapterPathDescription, LocalizableStrings.CmdTestAdapterPathDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdTestAdapterPath) .With(name: LocalizableStrings.CmdTestAdapterPath)
.ForwardAs(o => $"/p:VSTestTestAdapterPath={o.Arguments.Single()}")), .ForwardAs(o => $"/p:VSTestTestAdapterPath={o.Arguments.Single()}")),
Create.Option( Create.Option(
"-l|--logger", "-l|--logger",
LocalizableStrings.CmdLoggerDescription, LocalizableStrings.CmdLoggerDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdLoggerOption) .With(name: LocalizableStrings.CmdLoggerOption)
.ForwardAs(o => .ForwardAs(o =>
{ {
@ -52,13 +52,13 @@ namespace Microsoft.DotNet.Cli
Create.Option( Create.Option(
"-o|--output", "-o|--output",
LocalizableStrings.CmdOutputDescription, LocalizableStrings.CmdOutputDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdOutputDir) .With(name: LocalizableStrings.CmdOutputDir)
.ForwardAs(o => $"/p:OutputPath={o.Arguments.Single()}")), .ForwardAs(o => $"/p:OutputPath={o.Arguments.Single()}")),
Create.Option( Create.Option(
"-d|--diag", "-d|--diag",
LocalizableStrings.CmdPathTologFileDescription, LocalizableStrings.CmdPathTologFileDescription,
Accept.ExactlyOneArgument Accept.ExactlyOneArgument()
.With(name: LocalizableStrings.CmdPathToLogFile) .With(name: LocalizableStrings.CmdPathToLogFile)
.ForwardAs(o => $"/p:VSTestDiag={o.Arguments.Single()}")), .ForwardAs(o => $"/p:VSTestDiag={o.Arguments.Single()}")),
Create.Option( Create.Option(

View file

@ -40,7 +40,7 @@
<PackageReference Include="Microsoft.Win32.Registry" Version="4.3.0" /> <PackageReference Include="Microsoft.Win32.Registry" Version="4.3.0" />
<PackageReference Include="Microsoft.Build" Version="$(CLI_MSBuild_Version)" /> <PackageReference Include="Microsoft.Build" Version="$(CLI_MSBuild_Version)" />
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="$(PlatformAbstractionsVersion)" /> <PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="$(PlatformAbstractionsVersion)" />
<PackageReference Include="Microsoft.DotNet.Cli.CommandLine" Version="0.1.0-alpha-80" /> <PackageReference Include="Microsoft.DotNet.Cli.CommandLine" Version="0.1.0-alpha-84" />
<PackageReference Include="Microsoft.TemplateEngine.Abstractions" Version="$(TemplateEngineVersion)" /> <PackageReference Include="Microsoft.TemplateEngine.Abstractions" Version="$(TemplateEngineVersion)" />
<PackageReference Include="Microsoft.TemplateEngine.Cli" Version="$(TemplateEngineVersion)" /> <PackageReference Include="Microsoft.TemplateEngine.Cli" Version="$(TemplateEngineVersion)" />
<PackageReference Include="Microsoft.TemplateEngine.Orchestrator.RunnableProjects" Version="$(TemplateEngineVersion)" /> <PackageReference Include="Microsoft.TemplateEngine.Orchestrator.RunnableProjects" Version="$(TemplateEngineVersion)" />

View file

@ -18,10 +18,10 @@ namespace Microsoft.DotNet.Tests.ParserTests
{ {
var command = Command("the-command", "", var command = Command("the-command", "",
Option("-o|--one", "", Option("-o|--one", "",
ZeroOrOneArgument ZeroOrOneArgument()
.ForwardAs(o => $"/i:{o.Arguments.Single()}")), .ForwardAs(o => $"/i:{o.Arguments.Single()}")),
Option("-t|--two", "", Option("-t|--two", "",
NoArguments NoArguments()
.ForwardAs("/s:true"))); .ForwardAs("/s:true")));
var result = command.Parse("the-command -t -o 123"); var result = command.Parse("the-command -t -o 123");
@ -37,7 +37,7 @@ namespace Microsoft.DotNet.Tests.ParserTests
{ {
var command = Command("the-command", "", var command = Command("the-command", "",
Option("-x", "", Option("-x", "",
ZeroOrMoreArguments ZeroOrMoreArguments()
.ForwardAs(o => $"/x:{string.Join("&", o.Arguments)}"))); .ForwardAs(o => $"/x:{string.Join("&", o.Arguments)}")));
var result = command.Parse("the-command -x one -x two"); var result = command.Parse("the-command -x one -x two");
@ -53,7 +53,7 @@ namespace Microsoft.DotNet.Tests.ParserTests
{ {
var command = Command("the-command", "", var command = Command("the-command", "",
Option("-x", "", Option("-x", "",
ZeroOrMoreArguments ZeroOrMoreArguments()
.Forward())); .Forward()));
var result = command.Parse("the-command -x one"); var result = command.Parse("the-command -x one");

View file

@ -42,6 +42,6 @@
<PackageReference Include="xunit" Version="2.2.0-beta4-build3444" /> <PackageReference Include="xunit" Version="2.2.0-beta4-build3444" />
<PackageReference Include="xunit.netcore.extensions" Version="1.0.0-prerelease-00206" /> <PackageReference Include="xunit.netcore.extensions" Version="1.0.0-prerelease-00206" />
<PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="$(PlatformAbstractionsVersion)" /> <PackageReference Include="Microsoft.DotNet.PlatformAbstractions" Version="$(PlatformAbstractionsVersion)" />
<PackageReference Include="Microsoft.DotNet.Cli.CommandLine" Version="0.1.0-alpha-80" /> <PackageReference Include="Microsoft.DotNet.Cli.CommandLine" Version="0.1.0-alpha-84" />
</ItemGroup> </ItemGroup>
</Project> </Project>