dotnet-installer/src/dotnet/DotNetTopLevelCommandBase.cs

85 lines
2.8 KiB
C#
Raw Normal View History

// 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;
2016-12-16 01:04:09 -08:00
using System.IO;
using System.Linq;
using Microsoft.DotNet.Cli.CommandLine;
using Microsoft.DotNet.Cli.Utils;
using Microsoft.DotNet.Tools;
2016-12-16 01:04:09 -08:00
using Microsoft.DotNet.Tools.Common;
namespace Microsoft.DotNet.Cli
{
public abstract class DotNetTopLevelCommandBase
{
protected abstract string CommandName { get; }
protected abstract string FullCommandNameLocalized { get; }
2016-12-16 01:04:09 -08:00
internal abstract List<Func<DotNetSubCommandBase>> SubCommands { get; }
public int RunCommand(string[] args)
{
DebugHelper.HandleDebugSwitch(ref args);
2016-12-16 01:04:09 -08:00
CommandLineApplication command = new CommandLineApplication(throwOnUnexpectedArg: true)
{
Name = $"dotnet {CommandName}",
FullName = FullCommandNameLocalized,
};
2016-12-16 01:04:09 -08:00
command.HelpOption("-h|--help");
2016-12-16 01:04:09 -08:00
command.Argument(
Constants.ProjectOrSolutionArgumentName,
CommonLocalizableStrings.ArgumentsProjectOrSolutionDescription);
foreach (var subCommandCreator in SubCommands)
{
2016-12-16 01:04:09 -08:00
var subCommand = subCommandCreator();
2016-12-16 13:27:41 -08:00
command.AddCommand(subCommand);
2016-12-16 01:04:09 -08:00
subCommand.OnExecute(() => {
try
{
if (!command.Arguments.Any())
{
throw new GracefulException(CommonLocalizableStrings.RequiredArgumentNotPassed, Constants.ProjectOrSolutionArgumentName);
}
var projectOrDirectory = command.Arguments.First().Value;
if (string.IsNullOrEmpty(projectOrDirectory))
{
projectOrDirectory = PathUtility.EnsureTrailingSlash(Directory.GetCurrentDirectory());
}
return subCommand.Run(projectOrDirectory);
}
catch (GracefulException e)
{
Reporter.Error.WriteLine(e.Message.Red());
subCommand.ShowHelp();
return 1;
}
});
}
try
{
2016-12-16 01:04:09 -08:00
return command.Execute(args);
}
catch (GracefulException e)
{
Reporter.Error.WriteLine(e.Message.Red());
2016-12-16 01:04:09 -08:00
command.ShowHelp();
return 1;
}
catch (CommandParsingException e)
{
Reporter.Error.WriteLine(e.Message.Red());
return 1;
}
}
}
}