|
| 1 | +// |
| 2 | +// Copyright (c) Microsoft. All rights reserved. |
| 3 | +// Licensed under the MIT license. See LICENSE file in the project root for full license information. |
| 4 | +// |
| 5 | + |
| 6 | +using Microsoft.Extensions.Logging; |
| 7 | +using Microsoft.PowerShell.EditorServices.Utility; |
| 8 | +using PowerShellEditorServices.Engine.Services.Handlers; |
| 9 | +using System; |
| 10 | +using System.Linq; |
| 11 | +using System.Management.Automation; |
| 12 | +using System.Threading.Tasks; |
| 13 | + |
| 14 | +namespace Microsoft.PowerShell.EditorServices.Templates |
| 15 | +{ |
| 16 | + /// <summary> |
| 17 | + /// Provides a service for listing PowerShell project templates and creating |
| 18 | + /// new projects from those templates. This service leverages the Plaster |
| 19 | + /// module for creating projects from templates. |
| 20 | + /// </summary> |
| 21 | + public class TemplateService |
| 22 | + { |
| 23 | + #region Private Fields |
| 24 | + |
| 25 | + private readonly ILogger logger; |
| 26 | + private bool isPlasterLoaded; |
| 27 | + private bool? isPlasterInstalled; |
| 28 | + private readonly PowerShellContextService powerShellContext; |
| 29 | + |
| 30 | + #endregion |
| 31 | + |
| 32 | + #region Constructors |
| 33 | + |
| 34 | + /// <summary> |
| 35 | + /// Creates a new instance of the TemplateService class. |
| 36 | + /// </summary> |
| 37 | + /// <param name="powerShellContext">The PowerShellContext to use for this service.</param> |
| 38 | + /// <param name="factory">An ILoggerFactory implementation used for writing log messages.</param> |
| 39 | + public TemplateService(PowerShellContextService powerShellContext, ILoggerFactory factory) |
| 40 | + { |
| 41 | + Validate.IsNotNull(nameof(powerShellContext), powerShellContext); |
| 42 | + |
| 43 | + this.logger = factory.CreateLogger<TemplateService>(); |
| 44 | + this.powerShellContext = powerShellContext; |
| 45 | + } |
| 46 | + |
| 47 | + #endregion |
| 48 | + |
| 49 | + #region Public Methods |
| 50 | + |
| 51 | + /// <summary> |
| 52 | + /// Checks if Plaster is installed on the user's machine. |
| 53 | + /// </summary> |
| 54 | + /// <returns>A Task that can be awaited until the check is complete. The result will be true if Plaster is installed.</returns> |
| 55 | + public async Task<bool> ImportPlasterIfInstalledAsync() |
| 56 | + { |
| 57 | + if (!this.isPlasterInstalled.HasValue) |
| 58 | + { |
| 59 | + PSCommand psCommand = new PSCommand(); |
| 60 | + |
| 61 | + psCommand |
| 62 | + .AddCommand("Get-Module") |
| 63 | + .AddParameter("ListAvailable") |
| 64 | + .AddParameter("Name", "Plaster"); |
| 65 | + |
| 66 | + psCommand |
| 67 | + .AddCommand("Sort-Object") |
| 68 | + .AddParameter("Descending") |
| 69 | + .AddParameter("Property", "Version"); |
| 70 | + |
| 71 | + psCommand |
| 72 | + .AddCommand("Select-Object") |
| 73 | + .AddParameter("First", 1); |
| 74 | + |
| 75 | + this.logger.LogTrace("Checking if Plaster is installed..."); |
| 76 | + |
| 77 | + var getResult = |
| 78 | + await this.powerShellContext.ExecuteCommandAsync<PSObject>( |
| 79 | + psCommand, false, false); |
| 80 | + |
| 81 | + PSObject moduleObject = getResult.First(); |
| 82 | + this.isPlasterInstalled = moduleObject != null; |
| 83 | + string installedQualifier = |
| 84 | + this.isPlasterInstalled.Value |
| 85 | + ? string.Empty : "not "; |
| 86 | + |
| 87 | + this.logger.LogTrace($"Plaster is {installedQualifier}installed!"); |
| 88 | + |
| 89 | + // Attempt to load plaster |
| 90 | + if (this.isPlasterInstalled.Value && this.isPlasterLoaded == false) |
| 91 | + { |
| 92 | + this.logger.LogTrace("Loading Plaster..."); |
| 93 | + |
| 94 | + psCommand = new PSCommand(); |
| 95 | + psCommand |
| 96 | + .AddCommand("Import-Module") |
| 97 | + .AddParameter("ModuleInfo", (PSModuleInfo)moduleObject.ImmediateBaseObject) |
| 98 | + .AddParameter("PassThru"); |
| 99 | + |
| 100 | + var importResult = |
| 101 | + await this.powerShellContext.ExecuteCommandAsync<object>( |
| 102 | + psCommand, false, false); |
| 103 | + |
| 104 | + this.isPlasterLoaded = importResult.Any(); |
| 105 | + string loadedQualifier = |
| 106 | + this.isPlasterInstalled.Value |
| 107 | + ? "was" : "could not be"; |
| 108 | + |
| 109 | + this.logger.LogTrace($"Plaster {loadedQualifier} loaded successfully!"); |
| 110 | + } |
| 111 | + } |
| 112 | + |
| 113 | + return this.isPlasterInstalled.Value; |
| 114 | + } |
| 115 | + |
| 116 | + /// <summary> |
| 117 | + /// Gets the available file or project templates on the user's |
| 118 | + /// machine. |
| 119 | + /// </summary> |
| 120 | + /// <param name="includeInstalledModules"> |
| 121 | + /// If true, searches the user's installed PowerShell modules for |
| 122 | + /// included templates. |
| 123 | + /// </param> |
| 124 | + /// <returns>A Task which can be awaited for the TemplateDetails list to be returned.</returns> |
| 125 | + public async Task<TemplateDetails[]> GetAvailableTemplatesAsync( |
| 126 | + bool includeInstalledModules) |
| 127 | + { |
| 128 | + if (!this.isPlasterLoaded) |
| 129 | + { |
| 130 | + throw new InvalidOperationException("Plaster is not loaded, templates cannot be accessed."); |
| 131 | + } |
| 132 | + |
| 133 | + PSCommand psCommand = new PSCommand(); |
| 134 | + psCommand.AddCommand("Get-PlasterTemplate"); |
| 135 | + |
| 136 | + if (includeInstalledModules) |
| 137 | + { |
| 138 | + psCommand.AddParameter("IncludeModules"); |
| 139 | + } |
| 140 | + |
| 141 | + var templateObjects = |
| 142 | + await this.powerShellContext.ExecuteCommandAsync<PSObject>( |
| 143 | + psCommand, false, false); |
| 144 | + |
| 145 | + this.logger.LogTrace($"Found {templateObjects.Count()} Plaster templates"); |
| 146 | + |
| 147 | + return |
| 148 | + templateObjects |
| 149 | + .Select(CreateTemplateDetails) |
| 150 | + .ToArray(); |
| 151 | + } |
| 152 | + |
| 153 | + /// <summary> |
| 154 | + /// Creates a new file or project from a specified template and |
| 155 | + /// places it in the destination path. This ultimately calls |
| 156 | + /// Invoke-Plaster in PowerShell. |
| 157 | + /// </summary> |
| 158 | + /// <param name="templatePath">The folder path containing the template.</param> |
| 159 | + /// <param name="destinationPath">The folder path where the files will be created.</param> |
| 160 | + /// <returns>A boolean-returning Task which communicates success or failure.</returns> |
| 161 | + public async Task<bool> CreateFromTemplateAsync( |
| 162 | + string templatePath, |
| 163 | + string destinationPath) |
| 164 | + { |
| 165 | + this.logger.LogTrace( |
| 166 | + $"Invoking Plaster...\n\n TemplatePath: {templatePath}\n DestinationPath: {destinationPath}"); |
| 167 | + |
| 168 | + PSCommand command = new PSCommand(); |
| 169 | + command.AddCommand("Invoke-Plaster"); |
| 170 | + command.AddParameter("TemplatePath", templatePath); |
| 171 | + command.AddParameter("DestinationPath", destinationPath); |
| 172 | + |
| 173 | + var errorString = new System.Text.StringBuilder(); |
| 174 | + await this.powerShellContext.ExecuteCommandAsync<PSObject>( |
| 175 | + command, |
| 176 | + errorString, |
| 177 | + new ExecutionOptions |
| 178 | + { |
| 179 | + WriteOutputToHost = false, |
| 180 | + WriteErrorsToHost = true, |
| 181 | + InterruptCommandPrompt = true |
| 182 | + }); |
| 183 | + |
| 184 | + // If any errors were written out, creation was not successful |
| 185 | + return errorString.Length == 0; |
| 186 | + } |
| 187 | + |
| 188 | + #endregion |
| 189 | + |
| 190 | + #region Private Methods |
| 191 | + |
| 192 | + private static TemplateDetails CreateTemplateDetails(PSObject psObject) |
| 193 | + { |
| 194 | + return new TemplateDetails |
| 195 | + { |
| 196 | + Title = psObject.Members["Title"].Value as string, |
| 197 | + Author = psObject.Members["Author"].Value as string, |
| 198 | + Version = psObject.Members["Version"].Value.ToString(), |
| 199 | + Description = psObject.Members["Description"].Value as string, |
| 200 | + TemplatePath = psObject.Members["TemplatePath"].Value as string, |
| 201 | + Tags = |
| 202 | + psObject.Members["Tags"].Value is object[] tags |
| 203 | + ? string.Join(", ", tags) |
| 204 | + : string.Empty |
| 205 | + }; |
| 206 | + } |
| 207 | + |
| 208 | + #endregion |
| 209 | + } |
| 210 | +} |
0 commit comments