move subcommands to new parser

This commit is contained in:
Jon Sequeira 2017-03-10 16:43:44 -08:00
parent d3319adb59
commit a3f536c248
20 changed files with 307 additions and 395 deletions

View file

@ -313,9 +313,12 @@ namespace Microsoft.DotNet.Tools.Common
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>();
foreach (var p in paths)
{
if (!File.Exists(p))
@ -329,7 +332,7 @@ namespace Microsoft.DotNet.Tools.Common
throw new GracefulException(
string.Join(
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

@ -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.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools;
using Microsoft.DotNet.Tools.Common;
namespace Microsoft.DotNet.Cli
{
@ -18,60 +15,34 @@ namespace Microsoft.DotNet.Cli
protected abstract string FullCommandNameLocalized { get; }
protected abstract string ArgumentName { 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)
{
DebugHelper.HandleDebugSwitch(ref args);
CommandLineApplication command = new CommandLineApplication(throwOnUnexpectedArg: true)
{
Name = $"dotnet {CommandName}",
FullName = FullCommandNameLocalized,
};
var parser = Parser.Instance;
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)
{
var subCommand = subCommandCreator();
command.AddCommand(subCommand);
result.ShowHelpIfRequested();
var subcommandName = result.Command().Name;
var create = SubCommands[subcommandName];
var command = create(result["dotnet"][CommandName]);
subCommand.OnExecute(() => {
try
{
if (!command.Arguments.Any())
{
throw new GracefulException(CommonLocalizableStrings.RequiredArgumentNotPassed, ArgumentDescriptionLocalized);
}
var projectOrDirectory = command.Arguments.First().Value;
if (string.IsNullOrEmpty(projectOrDirectory))
{
projectOrDirectory = PathUtility.EnsureTrailingSlash(Directory.GetCurrentDirectory());
}
return subCommand.Run(projectOrDirectory);
return command.Execute();
}
catch (GracefulException e)
{
Reporter.Error.WriteLine(e.Message.Red());
subCommand.ShowHelp();
return 1;
}
});
}
try
{
return command.Execute(args);
}
catch (GracefulException e)
{
Reporter.Error.WriteLine(e.Message.Red());
command.ShowHelp();
result.ShowHelp();
return 1;
}
catch (CommandParsingException e)

View file

@ -14,11 +14,9 @@ namespace Microsoft.DotNet.Cli
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.
throw new HelpException(parseResult.Command().HelpView());
}
}

View file

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

View file

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

View file

@ -3,7 +3,9 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Add.PackageReference;
using Microsoft.DotNet.Tools.Add.ProjectToProjectReference;
@ -16,11 +18,22 @@ namespace Microsoft.DotNet.Tools.Add
protected override string FullCommandNameLocalized => LocalizableStrings.NetAddCommand;
protected override string ArgumentName => Constants.ProjectArgumentName;
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)

View file

@ -1,105 +1,65 @@
// 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.Build.Evaluation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.MSBuild;
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
{
internal class AddPackageReferenceCommand : DotNetSubCommandBase
internal class AddPackageReferenceCommand : CommandBase
{
private CommandOption _versionOption;
private CommandOption _frameworkOption;
private CommandOption _noRestoreOption;
private CommandOption _sourceOption;
private CommandOption _packageDirectoryOption;
private CommandArgument _packageNameArgument;
private readonly AppliedOption _appliedCommand;
public static DotNetSubCommandBase Create()
private readonly string _packageId;
private readonly string _fileOrDirectory;
public AddPackageReferenceCommand(AppliedOption appliedCommand, string fileOrDirectory)
{
var command = new AddPackageReferenceCommand
{
Name = "package",
FullName = LocalizableStrings.AppFullName,
Description = LocalizableStrings.AppDescription,
HandleRemainingArguments = false
};
_appliedCommand = appliedCommand;
_fileOrDirectory = fileOrDirectory;
_packageId = appliedCommand.Value<string>();
command.HelpOption("-h|--help");
command._packageNameArgument = command.Argument(
$"<{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)
if ( string.IsNullOrWhiteSpace(_packageId) || _appliedCommand.Arguments.Count > 1)
{
throw new GracefulException(LocalizableStrings.SpecifyExactlyOnePackageReference);
}
}
public override int Execute()
{
var projectFilePath = string.Empty;
if (!File.Exists(fileOrDirectory))
if (!File.Exists(_fileOrDirectory))
{
projectFilePath = MsbuildProject.GetProjectFileFromDirectory(fileOrDirectory).FullName;
projectFilePath = MsbuildProject.GetProjectFileFromDirectory(_fileOrDirectory).FullName;
}
else
{
projectFilePath = fileOrDirectory;
projectFilePath = _fileOrDirectory;
}
var tempDgFilePath = string.Empty;
if (!_noRestoreOption.HasValue())
if (!_appliedCommand.HasOption("no-restore"))
{
// Create a Dependency Graph file for the project
tempDgFilePath = Path.GetTempFileName();
GetProjectDependencyGraph(projectFilePath, tempDgFilePath);
}
var result = NuGetCommand.Run(TransformArgs(_packageNameArgument.Value, tempDgFilePath, projectFilePath));
var result = NuGetCommand.Run(
TransformArgs(
_packageId,
tempDgFilePath,
projectFilePath));
DisposeTemporaryFile(tempDgFilePath);
return result;
@ -136,7 +96,8 @@ namespace Microsoft.DotNet.Tools.Add.PackageReference
private string[] TransformArgs(string packageId, string tempDgFilePath, string projectFilePath)
{
var args = new List<string>(){
var args = new List<string>
{
"package",
"add",
"--package",
@ -145,27 +106,11 @@ namespace Microsoft.DotNet.Tools.Add.PackageReference
projectFilePath
};
if (_versionOption.HasValue())
{
args.Add("--version");
args.Add(_versionOption.Value());
}
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.AddRange(_appliedCommand
.OptionValuesToBeForwarded()
.SelectMany(a => a.Split(' ')));
if (_appliedCommand.HasOption("no-restore"))
{
args.Add("--no-restore");
}

View file

@ -1,57 +1,44 @@
// 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 System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using NuGet.Frameworks;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
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",
FullName = LocalizableStrings.AppFullName,
Description = LocalizableStrings.AppDescription,
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.AppHelpText,
};
command.HelpOption("-h|--help");
command._frameworkOption = command.Option(
$"-f|--framework <{CommonLocalizableStrings.CmdFramework}>",
LocalizableStrings.CmdFrameworkDescription,
CommandOptionType.SingleValue);
return command;
throw new ArgumentNullException(nameof(appliedCommand));
}
_appliedCommand = appliedCommand;
_fileOrDirectory = fileOrDirectory;
}
public override int Run(string fileOrDirectory)
public override int Execute()
{
var projects = new ProjectCollection();
MsbuildProject msbuildProj = MsbuildProject.FromFileOrDirectory(projects, fileOrDirectory);
MsbuildProject msbuildProj = MsbuildProject.FromFileOrDirectory(projects, _fileOrDirectory);
if (RemainingArguments.Count == 0)
{
throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneReferenceToAdd);
}
var frameworkString = _appliedCommand["framework"].Value<string>();
string frameworkString = _frameworkOption.Value();
PathUtility.EnsureAllPathsExist(RemainingArguments, CommonLocalizableStrings.ReferenceDoesNotExist);
List<MsbuildProject> refs = RemainingArguments
PathUtility.EnsureAllPathsExist(_appliedCommand.Arguments, CommonLocalizableStrings.ReferenceDoesNotExist);
List<MsbuildProject> refs = _appliedCommand.Arguments
.Select((r) => MsbuildProject.FromFile(projects, r))
.ToList();
@ -95,11 +82,12 @@ namespace Microsoft.DotNet.Tools.Add.ProjectToProjectReference
}
}
var relativePathReferences = RemainingArguments.Select((r) =>
PathUtility.GetRelativePath(msbuildProj.ProjectDirectory, Path.GetFullPath(r))).ToList();
var relativePathReferences = _appliedCommand.Arguments.Select((r) =>
PathUtility.GetRelativePath(msbuildProj.ProjectDirectory, Path.GetFullPath(r)))
.ToList();
int numberOfAddedReferences = msbuildProj.AddProjectToProjectReferences(
_frameworkOption.Value(),
frameworkString,
relativePathReferences);
if (numberOfAddedReferences != 0)

View file

@ -15,6 +15,7 @@ namespace Microsoft.DotNet.Cli
.With(name: "path"),
Create.Option("--position", "",
Accept.ExactlyOneArgument
.With(name: "command")));
.With(name: "command")
.MaterializeAs(o => int.Parse(o.Arguments.Single()))));
}
}

View file

@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.List.ProjectToProjectReferences;
@ -15,10 +16,11 @@ namespace Microsoft.DotNet.Tools.List
protected override string FullCommandNameLocalized => LocalizableStrings.NetListCommand;
protected override string ArgumentName => Constants.ProjectArgumentName;
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)

View file

@ -1,32 +1,32 @@
// 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 System;
using System.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using System.Linq;
namespace Microsoft.DotNet.Tools.List.ProjectToProjectReferences
{
internal class ListProjectToProjectReferencesCommand : DotNetSubCommandBase
internal class ListProjectToProjectReferencesCommand : CommandBase
{
public static DotNetSubCommandBase Create()
{
var command = new ListProjectToProjectReferencesCommand()
{
Name = "reference",
FullName = LocalizableStrings.AppFullName,
Description = LocalizableStrings.AppDescription,
};
private readonly string _fileOrDirectory;
command.HelpOption("-h|--help");
return command;
public ListProjectToProjectReferencesCommand(AppliedOption appliedCommand)
{
if (appliedCommand == null)
{
throw new ArgumentNullException(nameof(appliedCommand));
}
public override int Run(string fileOrDirectory)
_fileOrDirectory = appliedCommand.Arguments.Single();
}
public override int Execute()
{
var msbuildProj = MsbuildProject.FromFileOrDirectory(new ProjectCollection(), fileOrDirectory);
var msbuildProj = MsbuildProject.FromFileOrDirectory(new ProjectCollection(), _fileOrDirectory);
var p2ps = msbuildProj.GetProjectToProjectReferences();
if (!p2ps.Any())
@ -34,7 +34,7 @@ namespace Microsoft.DotNet.Tools.List.ProjectToProjectReferences
Reporter.Output.WriteLine(string.Format(
CommonLocalizableStrings.NoReferencesFound,
CommonLocalizableStrings.P2P,
fileOrDirectory));
_fileOrDirectory));
return 0;
}

View file

@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Remove.PackageReference;
using Microsoft.DotNet.Tools.Remove.ProjectToProjectReference;
@ -16,11 +17,12 @@ namespace Microsoft.DotNet.Tools.Remove
protected override string FullCommandNameLocalized => LocalizableStrings.NetRemoveCommand;
protected override string ArgumentName => Constants.ProjectArgumentName;
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,
RemovePackageReferenceCommand.Create
{ "reference", o => new RemoveProjectToProjectReferenceCommand(o) },
{ "package", o => new RemovePackageReferenceCommand(o) }
};
public static int Run(string[] args)

View file

@ -1,61 +1,50 @@
// 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.Build.Evaluation;
using System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.MSBuild;
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
{
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",
FullName = LocalizableStrings.AppFullName,
Description = LocalizableStrings.AppDescription,
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.AppHelpText,
};
command.HelpOption("-h|--help");
return command;
throw new ArgumentNullException(nameof(appliedCommand));
}
public override int Run(string fileOrDirectory)
{
if (RemainingArguments.Count != 1)
if (_appliedCommand.Arguments.Count != 1)
{
throw new GracefulException(LocalizableStrings.SpecifyExactlyOnePackageReference);
}
_appliedCommand = appliedCommand;
_fileOrDirectory = appliedCommand.Arguments.Single();
}
public override int Execute()
{
var projectFilePath = string.Empty;
if (!File.Exists(fileOrDirectory))
if (!File.Exists(_fileOrDirectory))
{
projectFilePath = MsbuildProject.GetProjectFileFromDirectory(fileOrDirectory).FullName;
projectFilePath = MsbuildProject.GetProjectFileFromDirectory(_fileOrDirectory).FullName;
}
else
{
projectFilePath = fileOrDirectory;
projectFilePath = _fileOrDirectory;
}
var packageToRemove = RemainingArguments.First();
var packageToRemove = _appliedCommand.Arguments.Single();
var result = NuGetCommand.Run(TransformArgs(packageToRemove, projectFilePath));
return result;
@ -63,7 +52,8 @@ namespace Microsoft.DotNet.Tools.Remove.PackageReference
private string[] TransformArgs(string packageId, string projectFilePath)
{
return new string[]{
return new string[]
{
"package",
"remove",
"--package",

View file

@ -1,6 +1,8 @@
// 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 System;
using System.Linq;
using Microsoft.Build.Evaluation;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
@ -8,42 +10,34 @@ using Microsoft.DotNet.Cli.Utils;
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",
FullName = LocalizableStrings.AppFullName,
Description = LocalizableStrings.AppDescription,
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.AppHelpText,
};
command.HelpOption("-h|--help");
command._frameworkOption = command.Option(
$"-f|--framework <{CommonLocalizableStrings.CmdFramework}>",
LocalizableStrings.CmdFrameworkDescription,
CommandOptionType.SingleValue);
return command;
throw new ArgumentNullException(nameof(appliedCommand));
}
public override int Run(string fileOrDirectory)
{
var msbuildProj = MsbuildProject.FromFileOrDirectory(new ProjectCollection(), fileOrDirectory);
if (RemainingArguments.Count == 0)
if (_appliedCommand.Arguments.Count == 0)
{
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(
_frameworkOption.Value(),
RemainingArguments);
_appliedCommand["framework"].Value<string>(),
_appliedCommand.Arguments);
if (numberOfRemovedReferences != 0)
{

View file

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

View file

@ -1,49 +1,50 @@
// 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 System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Cli.Utils;
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
{
internal class AddProjectToSolutionCommand : DotNetSubCommandBase
internal class AddProjectToSolutionCommand : CommandBase
{
public static DotNetSubCommandBase Create()
{
var command = new AddProjectToSolutionCommand()
{
Name = "add",
FullName = LocalizableStrings.AddAppFullName,
Description = LocalizableStrings.AddSubcommandHelpText,
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.AddSubcommandHelpText,
};
private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;
command.HelpOption("-h|--help");
public AddProjectToSolutionCommand(AppliedOption appliedCommand)
{
if (appliedCommand == null)
{
throw new ArgumentNullException(nameof(appliedCommand));
}
_appliedCommand = appliedCommand;
return command;
_fileOrDirectory = appliedCommand.Arguments.Single();
}
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);
}
PathUtility.EnsureAllPathsExist(RemainingArguments, CommonLocalizableStrings.ProjectDoesNotExist);
var fullProjectPaths = RemainingArguments.Select((p) => Path.GetFullPath(p)).ToList();
PathUtility.EnsureAllPathsExist(_appliedCommand.Arguments, CommonLocalizableStrings.ProjectDoesNotExist);
var fullProjectPaths = _appliedCommand.Arguments
.Select(Path.GetFullPath)
.ToList();
var preAddProjectCount = slnFile.Projects.Count;
int preAddProjectCount = slnFile.Projects.Count;
foreach (var fullProjectPath in fullProjectPaths)
{
slnFile.AddProject(fullProjectPath);

View file

@ -1,33 +1,32 @@
// 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 System;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools.Common;
using Microsoft.DotNet.Tools.Sln;
namespace Microsoft.DotNet.Tools.Sln.List
{
internal class ListProjectsInSolutionCommand : DotNetSubCommandBase
internal class ListProjectsInSolutionCommand : CommandBase
{
public static DotNetSubCommandBase Create()
{
var command = new ListProjectsInSolutionCommand()
{
Name = "list",
FullName = LocalizableStrings.ListAppFullName,
Description = LocalizableStrings.ListSubcommandHelpText,
};
private readonly string _fileOrDirectory;
command.HelpOption("-h|--help");
return command;
public ListProjectsInSolutionCommand(AppliedOption appliedCommand)
{
if (appliedCommand == null)
{
throw new ArgumentNullException(nameof(appliedCommand));
}
_fileOrDirectory = appliedCommand.Arguments.Single();
}
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)
{
Reporter.Output.WriteLine(CommonLocalizableStrings.NoProjectsFound);

View file

@ -1,49 +1,47 @@
// 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 System;
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Sln.Internal;
using Microsoft.DotNet.Cli.Utils;
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
{
internal class RemoveProjectFromSolutionCommand : DotNetSubCommandBase
internal class RemoveProjectFromSolutionCommand : CommandBase
{
public static DotNetSubCommandBase Create()
{
var command = new RemoveProjectFromSolutionCommand()
{
Name = "remove",
FullName = LocalizableStrings.RemoveAppFullName,
Description = LocalizableStrings.RemoveSubcommandHelpText,
HandleRemainingArguments = true,
ArgumentSeparatorHelpText = LocalizableStrings.RemoveSubcommandHelpText,
};
private readonly AppliedOption _appliedCommand;
private readonly string _fileOrDirectory;
command.HelpOption("-h|--help");
return command;
public RemoveProjectFromSolutionCommand(AppliedOption appliedCommand)
{
if (appliedCommand == null)
{
throw new ArgumentNullException(nameof(appliedCommand));
}
public override int Run(string fileOrDirectory)
{
SlnFile slnFile = SlnFileFactory.CreateFromFileOrDirectory(fileOrDirectory);
if (RemainingArguments.Count == 0)
if (_appliedCommand.Arguments.Count == 0)
{
throw new GracefulException(CommonLocalizableStrings.SpecifyAtLeastOneProjectToRemove);
}
var relativeProjectPaths = RemainingArguments.Select((p) =>
_appliedCommand = appliedCommand;
_fileOrDirectory = appliedCommand.Arguments.Single();
}
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();
Path.GetFullPath(p)))
.ToList();
bool slnChanged = false;
foreach (var path in relativeProjectPaths)