forked from Azure/bicep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBicepGenerateParamsCommandHandler.cs
115 lines (97 loc) · 5.11 KB
/
BicepGenerateParamsCommandHandler.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Bicep.Core;
using Bicep.Core.Diagnostics;
using Bicep.Core.Emit;
using Bicep.Core.Emit.Options;
using Bicep.Core.FileSystem;
using Bicep.LanguageServer.CompilationManager;
using Bicep.LanguageServer.Utils;
using Microsoft.WindowsAzure.ResourceStack.Common.Extensions;
using Microsoft.WindowsAzure.ResourceStack.Common.Json;
using Newtonsoft.Json.Linq;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Workspace;
namespace Bicep.LanguageServer.Handlers
{
public record BicepGenerateParamsCommandParams(
string BicepFilePath,
OutputFormatOption OutputFormat,
IncludeParamsOption IncludeParams
);
// This handler is used to generate compiled parameters.json file for given a bicep file path.
// It returns generate-params succeeded/failed message, which can be displayed approriately in IDE output window
public class BicepGenerateParamsCommandHandler : ExecuteTypedResponseCommandHandlerBase<BicepGenerateParamsCommandParams, string>
{
private readonly ICompilationManager compilationManager;
private readonly BicepCompiler bicepCompiler;
public BicepGenerateParamsCommandHandler(ICompilationManager compilationManager, BicepCompiler bicepCompiler, ISerializer serializer)
: base(LangServerConstants.GenerateParamsCommand, serializer)
{
this.compilationManager = compilationManager;
this.bicepCompiler = bicepCompiler;
}
public override async Task<string> Handle(BicepGenerateParamsCommandParams parameters, CancellationToken cancellationToken)
{
if (string.IsNullOrWhiteSpace(parameters.BicepFilePath))
{
throw new ArgumentException("Invalid input file path");
}
DocumentUri documentUri = DocumentUri.FromFileSystemPath(parameters.BicepFilePath);
string output = await GenerateCompiledParametersFileAndReturnOutputMessage(parameters.BicepFilePath, parameters.OutputFormat, parameters.IncludeParams, documentUri);
return output;
}
private async Task<string> GenerateCompiledParametersFileAndReturnOutputMessage(string bicepFilePath, OutputFormatOption outputFormat, IncludeParamsOption includeParams, DocumentUri documentUri)
{
string compiledFilePath = PathHelper.ResolveParametersFileOutputPath(bicepFilePath, outputFormat);
string compiledFile = Path.GetFileName(compiledFilePath);
// If the template exists and contains bicep generator metadata, we can go ahead and replace the file.
// If not, we'll fail the generate params.
if (File.Exists(compiledFilePath) && !TemplateIsParametersFile(File.ReadAllText(compiledFilePath)))
{
return "Generating parameters file failed. The file \"" + compiledFile + "\" already exists but does not contain the schema for a parameters file. If overwriting the file is intended, delete it manually and retry the Generate Parameters command.";
}
var compilation = await new CompilationHelper(bicepCompiler, compilationManager).GetRefreshedCompilation(documentUri);
var fileUri = documentUri.ToUri();
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile()
.FirstOrDefault(x => x.Key.FileUri == fileUri);
if (diagnosticsByFile.Value.Any(x => x.Level == DiagnosticLevel.Error))
{
return "Generating parameters file failed. Please fix below errors:\n" + DiagnosticsHelper.GetDiagnosticsMessage(diagnosticsByFile);
}
var existingContent = File.Exists(compiledFilePath) ? File.ReadAllText(compiledFilePath) : string.Empty;
var model = compilation.GetEntrypointSemanticModel();
var emitter = new TemplateEmitter(model);
using var fileStream = new FileStream(compiledFilePath, FileMode.Create, FileAccess.Write);
var result = emitter.EmitTemplateGeneratedParameterFile(fileStream, existingContent, outputFormat, includeParams);
return "Generating parameters file succeeded. Processed file " + compiledFile;
}
// Returns true if the template contains the parameters file schema, false otherwise
public bool TemplateIsParametersFile(string template)
{
try
{
if (!string.IsNullOrEmpty(template))
{
JToken jtoken = template.FromJson<JToken>();
var schema = jtoken.SelectToken("$schema")?.ToString();
if (schema != null && schema.ContainsInsensitively("deploymentParameters.json"))
{
return true;
}
}
}
catch (Exception)
{
return false;
}
return false;
}
}
}