private static void ListTemplates(CommandArgument template, CommandOption source) { IEnumerable <ITemplate> results = TemplateCreator.List(template.Value, source); TableFormatter.Print(results, "(No Items)", " ", '-', new Dictionary <string, Func <ITemplate, string> > { { "Templates", x => x.Name }, { "Short Names", x => $"[{x.ShortName}]" }, { "Alias", x => AliasRegistry.GetAliasForTemplate(x) ?? "" } }); }
public static int Main(string[] args) { CommandLineApplication app = new CommandLineApplication(false) { Name = "dotnet new3", FullName = "Template Instantiation Commands for .NET Core CLI." }; CommandArgument template = app.Argument("template", "The template to instantiate."); CommandOption listOnly = app.Option("-l|--list", "Lists templates with containing the specified name.", CommandOptionType.NoValue); CommandOption name = app.Option("-n|--name", "The name for the output. If no name is specified, the name of the current directory is used.", CommandOptionType.SingleValue); CommandOption dir = app.Option("-d|--dir", "Indicates whether to display create a directory for the generated content.", CommandOptionType.NoValue); CommandOption alias = app.Option("-a|--alias", "Creates an alias for the specified template", CommandOptionType.SingleValue); CommandOption parametersFiles = app.Option("-x|--extra-args", "Adds a parameters file.", CommandOptionType.MultipleValue); CommandOption install = app.Option("-i|--install", "Installs a source or a template pack.", CommandOptionType.MultipleValue); CommandOption help = app.Option("-h|--help", "Indicates whether to display the help for the template's parameters instead of creating it.", CommandOptionType.NoValue); CommandOption quiet = app.Option("--quiet", "Doesn't output any status information.", CommandOptionType.NoValue); CommandOption skipUpdateCheck = app.Option("--skip-update-check", "Don't check for updates.", CommandOptionType.NoValue); CommandOption update = app.Option("--update", "Update matching templates.", CommandOptionType.NoValue); app.OnExecute(async() => { bool reinitFlag = app.RemainingArguments.Any(x => x == "--debug:reinit"); if (reinitFlag) { Paths.User.FirstRunCookie.Delete(); } if (reinitFlag || app.RemainingArguments.Any(x => x == "--debug:reset-config")) { Paths.User.AliasesFile.Delete(); Paths.User.SettingsFile.Delete(); Paths.User.TemplateCacheFile.Delete(); return(0); } if (!Paths.User.BaseDir.Exists() || !Paths.User.FirstRunCookie.Exists()) { if (!quiet.HasValue()) { Reporter.Output.WriteLine("Getting things ready for first use..."); } ConfigureEnvironment(); Paths.User.FirstRunCookie.WriteAllText(""); } if (app.RemainingArguments.Any(x => x == "--debug:showconfig")) { ShowConfig(); return(0); } if (install.HasValue()) { InstallPackage(install.Values, quiet.HasValue()); return(0); } if (update.HasValue()) { //return PerformUpdateAsync(template.Value, quiet.HasValue(), source); } if (listOnly.HasValue()) { ListTemplates(template); return(0); } IReadOnlyDictionary <string, string> parameters; try { parameters = app.ParseExtraArgs(parametersFiles); } catch (Exception ex) { Reporter.Error.WriteLine(ex.Message.Red().Bold()); app.ShowHelp(); return(-1); } if (string.IsNullOrWhiteSpace(template.Value) && help.HasValue()) { app.ShowHelp(); return(0); } string aliasName = alias.HasValue() ? alias.Value() : null; ITemplateEngineHost host = new DotNetNew3TemplateEngineHost(); string fallbackName = new DirectoryInfo(Directory.GetCurrentDirectory()).Name; if (await TemplateCreator.Instantiate(host, template.Value ?? "", name.Value(), fallbackName, dir.HasValue(), aliasName, parameters, skipUpdateCheck.HasValue()) == -1) { ListTemplates(template); return(-1); } return(0); }); int result; try { using (Timing.Over("Execute")) { result = app.Execute(args); } } catch (Exception ex) { AggregateException ax = ex as AggregateException; while (ax != null && ax.InnerExceptions.Count == 1) { ex = ax.InnerException; ax = ex as AggregateException; } Reporter.Error.WriteLine(ex.Message.Bold().Red()); while (ex.InnerException != null) { ex = ex.InnerException; ax = ex as AggregateException; while (ax != null && ax.InnerExceptions.Count == 1) { ex = ax.InnerException; ax = ex as AggregateException; } Reporter.Error.WriteLine(ex.Message.Bold().Red()); } Reporter.Error.WriteLine(ex.StackTrace.Bold().Red()); result = 1; } return(result); }
private static int DisplayHelp(CommandArgument template) { IReadOnlyCollection <ITemplateInfo> templates = TemplateCreator.List(template.Value); if (templates.Count > 1) { ListTemplates(template); return(-1); } ITemplateInfo tmplt = templates.First(); Reporter.Output.WriteLine(tmplt.Name); if (!string.IsNullOrWhiteSpace(tmplt.Author)) { Reporter.Output.WriteLine($"Author: {tmplt.Author}"); } if (!string.IsNullOrWhiteSpace(tmplt.Description)) { Reporter.Output.WriteLine($"Description: {tmplt.Description}"); } ITemplate realTmplt = SettingsLoader.LoadTemplate(tmplt); IParameterSet allParams = realTmplt.Generator.GetParametersForTemplate(realTmplt); Reporter.Output.WriteLine($"Parameters: {tmplt.Description}"); bool anyParams = false; foreach (ITemplateParameter parameter in allParams.ParameterDefinitions.OrderBy(x => x.Priority)) { if (parameter.Priority == TemplateParameterPriority.Implicit) { continue; } anyParams = true; Reporter.Output.WriteLine($" --{parameter.Name} ({parameter.DataType ?? "string"} - {parameter.Priority})"); Reporter.Output.WriteLine($" {parameter.Documentation}"); if (string.Equals(parameter.DataType, "choice", StringComparison.OrdinalIgnoreCase)) { Reporter.Output.WriteLine($" Allowed values:"); foreach (string choice in parameter.Choices) { Reporter.Output.WriteLine($" {choice}"); } } if (!string.IsNullOrEmpty(parameter.DefaultValue)) { Reporter.Output.WriteLine($" Default: {parameter.DefaultValue}"); } Reporter.Output.WriteLine(" "); } if (!anyParams) { Reporter.Output.WriteLine(" (No Parameters)"); } return(0); }
private static async Task <int> PerformUpdateAsync(string name, bool quiet, CommandOption source) { HashSet <IConfiguredTemplateSource> allSources = new HashSet <IConfiguredTemplateSource>(); HashSet <string> toInstall = new HashSet <string>(StringComparer.OrdinalIgnoreCase); foreach (ITemplate template in TemplateCreator.List(name, source)) { allSources.Add(template.Source); } foreach (IConfiguredTemplateSource src in allSources) { if (!quiet) { Reporter.Output.WriteLine($"Checking for updates for {src.Alias}..."); } bool updatesReady; if (src.ParentSource != null) { updatesReady = await src.Source.CheckForUpdatesAsync(src.ParentSource, src.Location); } else { updatesReady = await src.Source.CheckForUpdatesAsync(src.Location); } if (updatesReady) { if (!quiet) { Reporter.Output.WriteLine($"An update for {src.Alias} is available..."); } string packageId = src.ParentSource != null ? src.Source.GetInstallPackageId(src.ParentSource, src.Location) : src.Source.GetInstallPackageId(src.Location); toInstall.Add(packageId); } } if (toInstall.Count == 0) { if (!quiet) { Reporter.Output.WriteLine("No updates were found."); } return(0); } if (!quiet) { Reporter.Output.WriteLine("Installing updates..."); } List <string> installCommands = new List <string>(); List <string> uninstallCommands = new List <string>(); foreach (string packageId in toInstall) { installCommands.Add("-i"); installCommands.Add(packageId); uninstallCommands.Add("-i"); uninstallCommands.Add(packageId); } installCommands.Add("--quiet"); uninstallCommands.Add("--quiet"); Command.CreateDotNet("new3", uninstallCommands).ForwardStdOut().ForwardStdErr().Execute(); Command.CreateDotNet("new3", installCommands).ForwardStdOut().ForwardStdErr().Execute(); Broker.ComponentRegistry.ForceReinitialize(); if (!quiet) { Reporter.Output.WriteLine("Done."); } return(0); }
public static int Main(string[] args) { //Console.ReadLine(); Broker = new Broker(); CommandLineApplication app = new CommandLineApplication(false) { Name = "dotnet new3", FullName = "Template Instantiation Commands for .NET Core CLI." }; CommandArgument template = app.Argument("template", "The template to instantiate."); CommandOption listOnly = app.Option("-l|--list", "Lists templates with containing the specified name.", CommandOptionType.NoValue); CommandOption name = app.Option("-n|--name", "The name for the output. If no name is specified, the name of the current directory is used.", CommandOptionType.SingleValue); CommandOption dir = app.Option("-d|--dir", "Indicates whether to display create a directory for the generated content.", CommandOptionType.NoValue); CommandOption alias = app.Option("-a|--alias", "Creates an alias for the specified template", CommandOptionType.SingleValue); CommandOption parametersFiles = app.Option("-x|--extra-args", "Adds a parameters file.", CommandOptionType.MultipleValue); CommandOption install = app.Option("-i|--install", "Installs a source or a template pack.", CommandOptionType.MultipleValue); CommandOption uninstall = app.Option("-u|--uninstall", "Uninstalls a source", CommandOptionType.MultipleValue); CommandOption source = app.Option("-s|--source", "The specific template source to get the template from.", CommandOptionType.SingleValue); CommandOption currentConfig = app.Option("-c|--current-config", "Lists the currently installed components and sources.", CommandOptionType.NoValue); CommandOption help = app.Option("-h|--help", "Indicates whether to display the help for the template's parameters instead of creating it.", CommandOptionType.NoValue); CommandOption installComponent = app.Option("--install-component", "Installs a component.", CommandOptionType.MultipleValue); CommandOption resetConfig = app.Option("--reset", "Resets the component cache and installed template sources.", CommandOptionType.NoValue); CommandOption rescan = app.Option("--rescan", "Rebuilds the component cache.", CommandOptionType.NoValue); CommandOption global = app.Option("--global", "Performs the --install or --install-component operation for all users.", CommandOptionType.NoValue); CommandOption reinit = app.Option("--reinitialize", "Sets dotnet new3 back to its pre-first run state.", CommandOptionType.NoValue); CommandOption quiet = app.Option("--quiet", "Doesn't output any status information.", CommandOptionType.NoValue); CommandOption skipUpdateCheck = app.Option("--skip-update-check", "Don't check for updates.", CommandOptionType.NoValue); CommandOption update = app.Option("--update", "Update matching templates.", CommandOptionType.NoValue); app.OnExecute(() => { if (reinit.HasValue()) { Paths.FirstRunCookie.Delete(); return(Task.FromResult(0)); } if (!Paths.UserDir.Exists() || !Paths.FirstRunCookie.Exists()) { if (!quiet.HasValue()) { Reporter.Output.WriteLine("Getting things ready for first use..."); } if (!Paths.FirstRunCookie.Exists()) { PerformReset(true, true); Paths.FirstRunCookie.WriteAllText(""); } ConfigureEnvironment(); PerformReset(false, true); } if (rescan.HasValue()) { Broker.ComponentRegistry.ForceReinitialize(); ShowConfig(); return(Task.FromResult(0)); } if (resetConfig.HasValue()) { PerformReset(global.HasValue()); return(Task.FromResult(0)); } if (currentConfig.HasValue()) { ShowConfig(); return(Task.FromResult(0)); } if (install.HasValue()) { InstallPackage(install.Values, true, global.HasValue(), quiet.HasValue()); return(Task.FromResult(0)); } if (installComponent.HasValue()) { InstallPackage(installComponent.Values, false, global.HasValue(), quiet.HasValue()); return(Task.FromResult(0)); } if (update.HasValue()) { return(PerformUpdateAsync(template.Value, quiet.HasValue(), source)); } if (uninstall.HasValue()) { foreach (string value in uninstall.Values) { if (value == "*") { Paths.TemplateSourcesFile.Delete(); Paths.AliasesFile.Delete(); if (global.HasValue()) { Paths.GlobalTemplateCacheDir.Delete(); } else { Paths.TemplateCacheDir.Delete(); } return(Task.FromResult(0)); } if (!TryRemoveSource(value)) { string cacheDir = global.HasValue() ? Paths.GlobalTemplateCacheDir : Paths.TemplateCacheDir; bool anyRemoved = false; if (!value.Exists()) { foreach (string file in cacheDir.EnumerateFiles($"{value}.*.nupkg")) { int verStart = file.IndexOf(value, StringComparison.OrdinalIgnoreCase) + value.Length + 1; string ver = file.Substring(verStart); ver = ver.Substring(0, ver.Length - ".nupkg".Length); Version version; if (Version.TryParse(ver, out version)) { if (!quiet.HasValue()) { Reporter.Output.WriteLine($"Removing {value} version {version}..."); } anyRemoved = true; file.Delete(); } } } if (!anyRemoved && !quiet.HasValue()) { Reporter.Error.WriteLine($"Couldn't remove {value} as a template source.".Red().Bold()); } } } return(Task.FromResult(0)); } if (listOnly.HasValue()) { ListTemplates(template, source); return(Task.FromResult(0)); } IReadOnlyDictionary <string, string> parameters; try { parameters = app.ParseExtraArgs(parametersFiles); } catch (Exception ex) { Reporter.Error.WriteLine(ex.Message.Red().Bold()); app.ShowHelp(); return(Task.FromResult(-1)); } return(TemplateCreator.Instantiate(app, template.Value ?? "", name, dir, source, help, alias, parameters, quiet.HasValue(), skipUpdateCheck.HasValue())); }); int result; try { result = app.Execute(args); } catch (Exception ex) { AggregateException ax = ex as AggregateException; while (ax != null && ax.InnerExceptions.Count == 1) { ex = ax.InnerException; ax = ex as AggregateException; } Reporter.Error.WriteLine(ex.Message.Bold().Red()); while (ex.InnerException != null) { ex = ex.InnerException; ax = ex as AggregateException; while (ax != null && ax.InnerExceptions.Count == 1) { ex = ax.InnerException; ax = ex as AggregateException; } Reporter.Error.WriteLine(ex.Message.Bold().Red()); } Reporter.Error.WriteLine(ex.StackTrace.Bold().Red()); result = 1; } return(result); }