|
| 1 | +// Licensed to the .NET Foundation under one or more agreements. |
| 2 | +// The .NET Foundation licenses this file to you under the MIT license. |
| 3 | + |
| 4 | +using Aspire.Cli.Configuration; |
| 5 | +using Aspire.Cli.Interaction; |
| 6 | +using Aspire.Cli.Projects; |
| 7 | +using Aspire.Cli.Resources; |
| 8 | +using Microsoft.Extensions.Logging; |
| 9 | +using Spectre.Console; |
| 10 | + |
| 11 | +namespace Aspire.Cli.Templating; |
| 12 | + |
| 13 | +internal sealed partial class CliTemplateFactory |
| 14 | +{ |
| 15 | + private async Task<TemplateResult> ApplyPythonStarterTemplateAsync(CallbackTemplate _, TemplateInputs inputs, System.CommandLine.ParseResult parseResult, CancellationToken cancellationToken) |
| 16 | + { |
| 17 | + var projectName = inputs.Name; |
| 18 | + if (string.IsNullOrWhiteSpace(projectName)) |
| 19 | + { |
| 20 | + var defaultName = _executionContext.WorkingDirectory.Name; |
| 21 | + projectName = await _prompter.PromptForProjectNameAsync(defaultName, cancellationToken); |
| 22 | + } |
| 23 | + |
| 24 | + if (string.IsNullOrWhiteSpace(inputs.Version)) |
| 25 | + { |
| 26 | + _interactionService.DisplayError("Unable to determine Aspire version for the Python starter template."); |
| 27 | + return new TemplateResult(ExitCodeConstants.InvalidCommand); |
| 28 | + } |
| 29 | + |
| 30 | + var aspireVersion = inputs.Version; |
| 31 | + var outputPath = inputs.Output; |
| 32 | + if (string.IsNullOrWhiteSpace(outputPath)) |
| 33 | + { |
| 34 | + var defaultOutputPath = $"./{projectName}"; |
| 35 | + outputPath = await _prompter.PromptForOutputPath(defaultOutputPath, cancellationToken); |
| 36 | + } |
| 37 | + outputPath = Path.GetFullPath(outputPath, _executionContext.WorkingDirectory.FullName); |
| 38 | + |
| 39 | + _logger.LogDebug("Applying Python starter template. ProjectName: {ProjectName}, OutputPath: {OutputPath}, AspireVersion: {AspireVersion}.", projectName, outputPath, aspireVersion); |
| 40 | + |
| 41 | + var useLocalhostTld = await ResolveUseLocalhostTldAsync(parseResult, cancellationToken); |
| 42 | + var useRedisCache = await ResolveUseRedisCacheAsync(parseResult, cancellationToken); |
| 43 | + |
| 44 | + TemplateResult templateResult; |
| 45 | + try |
| 46 | + { |
| 47 | + if (!Directory.Exists(outputPath)) |
| 48 | + { |
| 49 | + Directory.CreateDirectory(outputPath); |
| 50 | + } |
| 51 | + |
| 52 | + templateResult = await _interactionService.ShowStatusAsync( |
| 53 | + TemplatingStrings.CreatingNewProject, |
| 54 | + async () => |
| 55 | + { |
| 56 | + var projectNameLower = projectName.ToLowerInvariant(); |
| 57 | + |
| 58 | + var ports = GenerateRandomPorts(); |
| 59 | + var hostName = useLocalhostTld ? $"{projectNameLower}.dev.localhost" : "localhost"; |
| 60 | + var conditions = new Dictionary<string, bool> |
| 61 | + { |
| 62 | + ["redis"] = useRedisCache, |
| 63 | + ["no-redis"] = !useRedisCache, |
| 64 | + }; |
| 65 | + string ApplyAllTokens(string content) => ConditionalBlockProcessor.Process( |
| 66 | + ApplyTokens(content, projectName, projectNameLower, aspireVersion, ports, hostName), |
| 67 | + conditions); |
| 68 | + _logger.LogDebug("Copying embedded Python starter template files to '{OutputPath}'.", outputPath); |
| 69 | + await CopyTemplateTreeToDiskAsync("py-starter", outputPath, ApplyAllTokens, cancellationToken); |
| 70 | + |
| 71 | + if (useRedisCache) |
| 72 | + { |
| 73 | + AddRedisPackageToConfig(outputPath, aspireVersion); |
| 74 | + } |
| 75 | + |
| 76 | + // Write channel to settings.json before restore so package resolution uses the selected channel. |
| 77 | + if (!string.IsNullOrEmpty(inputs.Channel)) |
| 78 | + { |
| 79 | + var config = AspireJsonConfiguration.Load(outputPath); |
| 80 | + if (config is not null) |
| 81 | + { |
| 82 | + config.Channel = inputs.Channel; |
| 83 | + config.Save(outputPath); |
| 84 | + } |
| 85 | + } |
| 86 | + |
| 87 | + var appHostProject = _projectFactory.TryGetProject(new FileInfo(Path.Combine(outputPath, "apphost.ts"))); |
| 88 | + if (appHostProject is not IGuestAppHostSdkGenerator guestProject) |
| 89 | + { |
| 90 | + _interactionService.DisplayError("Automatic 'aspire restore' is unavailable for the new Python starter project because no TypeScript AppHost SDK generator was found."); |
| 91 | + return new TemplateResult(ExitCodeConstants.FailedToBuildArtifacts, outputPath); |
| 92 | + } |
| 93 | + |
| 94 | + _logger.LogDebug("Generating SDK code for Python starter in '{OutputPath}'.", outputPath); |
| 95 | + var restoreSucceeded = await guestProject.BuildAndGenerateSdkAsync(new DirectoryInfo(outputPath), cancellationToken); |
| 96 | + if (!restoreSucceeded) |
| 97 | + { |
| 98 | + _interactionService.DisplayError("Automatic 'aspire restore' failed for the new Python starter project. Run 'aspire restore' in the project directory for more details."); |
| 99 | + return new TemplateResult(ExitCodeConstants.FailedToBuildArtifacts, outputPath); |
| 100 | + } |
| 101 | + |
| 102 | + return new TemplateResult(ExitCodeConstants.Success, outputPath); |
| 103 | + }, emoji: KnownEmojis.Rocket); |
| 104 | + |
| 105 | + if (templateResult.ExitCode != ExitCodeConstants.Success) |
| 106 | + { |
| 107 | + return templateResult; |
| 108 | + } |
| 109 | + } |
| 110 | + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) |
| 111 | + { |
| 112 | + _interactionService.DisplayError($"Failed to create project files: {ex.Message}"); |
| 113 | + return new TemplateResult(ExitCodeConstants.FailedToCreateNewProject); |
| 114 | + } |
| 115 | + |
| 116 | + _interactionService.DisplaySuccess($"Created Python starter project at {outputPath.EscapeMarkup()}"); |
| 117 | + DisplayPostCreationInstructions(outputPath); |
| 118 | + |
| 119 | + return templateResult; |
| 120 | + } |
| 121 | + |
| 122 | + private async Task<bool> ResolveUseRedisCacheAsync(System.CommandLine.ParseResult parseResult, CancellationToken cancellationToken) |
| 123 | + { |
| 124 | + var redisCacheOptionSpecified = parseResult.Tokens.Any(token => |
| 125 | + string.Equals(token.Value, "--use-redis-cache", StringComparisons.CliInputOrOutput)); |
| 126 | + var useRedisCache = parseResult.GetValue(_useRedisCacheOption); |
| 127 | + if (!redisCacheOptionSpecified) |
| 128 | + { |
| 129 | + if (!_hostEnvironment.SupportsInteractiveInput) |
| 130 | + { |
| 131 | + return false; |
| 132 | + } |
| 133 | + |
| 134 | + useRedisCache = await _interactionService.PromptForSelectionAsync( |
| 135 | + TemplatingStrings.UseRedisCache_Prompt, |
| 136 | + [TemplatingStrings.Yes, TemplatingStrings.No], |
| 137 | + choice => choice, |
| 138 | + cancellationToken) switch |
| 139 | + { |
| 140 | + var choice when string.Equals(choice, TemplatingStrings.Yes, StringComparisons.CliInputOrOutput) => true, |
| 141 | + var choice when string.Equals(choice, TemplatingStrings.No, StringComparisons.CliInputOrOutput) => false, |
| 142 | + _ => throw new InvalidOperationException(TemplatingStrings.UseRedisCache_UnexpectedChoice) |
| 143 | + }; |
| 144 | + } |
| 145 | + |
| 146 | + if (useRedisCache ?? false) |
| 147 | + { |
| 148 | + _interactionService.DisplayMessage(KnownEmojis.CheckMark, TemplatingStrings.UseRedisCache_UsingRedisCache); |
| 149 | + } |
| 150 | + |
| 151 | + return useRedisCache ?? false; |
| 152 | + } |
| 153 | + |
| 154 | + private static void AddRedisPackageToConfig(string outputPath, string aspireVersion) |
| 155 | + { |
| 156 | + var config = AspireConfigFile.LoadOrCreate(outputPath); |
| 157 | + config.AddOrUpdatePackage("Aspire.Hosting.Redis", aspireVersion); |
| 158 | + config.Save(outputPath); |
| 159 | + } |
| 160 | +} |
0 commit comments