Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 88 additions & 0 deletions src/Bicep.LangServer/Handlers/BicepSnapshotCommandHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

using Bicep.Core;
using Bicep.Core.Diagnostics;
using Bicep.Core.Emit;
using Bicep.Core.Extensions;
using Bicep.Core.Utils.Snapshots;
using Bicep.IO.Abstraction;
using Bicep.LanguageServer.CompilationManager;
using Bicep.LanguageServer.Utils;
using OmniSharp.Extensions.JsonRpc;
using OmniSharp.Extensions.LanguageServer.Protocol;
using OmniSharp.Extensions.LanguageServer.Protocol.Workspace;

namespace Bicep.LanguageServer.Handlers
{
// This handler is used to generate a snapshot (.snapshot.json) file for a given bicep parameters file.
// It returns snapshot generation succeeded/failed message, which can be displayed appropriately in IDE output window
public class BicepSnapshotCommandHandler : ExecuteTypedResponseCommandHandlerBase<DocumentUri, string>
{
private readonly ICompilationManager compilationManager;
private readonly IFileExplorer fileExplorer;
private readonly BicepCompiler bicepCompiler;

public BicepSnapshotCommandHandler(ICompilationManager compilationManager, IFileExplorer fileExplorer, BicepCompiler bicepCompiler, ISerializer serializer)
: base(LangServerConstants.SnapshotCommand, serializer)
{
this.compilationManager = compilationManager;
this.fileExplorer = fileExplorer;
this.bicepCompiler = bicepCompiler;
}

public override async Task<string> Handle(DocumentUri documentUri, CancellationToken cancellationToken)
{
string output = await GenerateSnapshotFileAndReturnOutputMessage(documentUri, cancellationToken);

return output;
}

private async Task<string> GenerateSnapshotFileAndReturnOutputMessage(DocumentUri documentUri, CancellationToken cancellationToken)
{
var bicepParamFileUri = documentUri.ToIOUri();
var snapshotFileUri = bicepParamFileUri.WithExtension(".snapshot.json");
var snapshotFile = this.fileExplorer.GetFile(snapshotFileUri);

var compilation = await new CompilationHelper(bicepCompiler, compilationManager).GetRefreshedCompilation(documentUri);
var paramsResult = compilation.Emitter.Parameters();

if (paramsResult.Success != true || paramsResult.Template?.Template is not { } templateContent || paramsResult.Parameters is not { } parametersContent)
{
var diagnosticsByFile = compilation.GetAllDiagnosticsByBicepFile();

return "Generating snapshot file failed. Please fix below errors:\n" + DiagnosticsHelper.GetDiagnosticsMessage(diagnosticsByFile);
}

try
{
var snapshot = await SnapshotHelper.GetSnapshot(
targetScope: compilation.GetEntrypointSemanticModel().TargetScope,
templateContent: templateContent,
parametersContent: parametersContent,
tenantId: null,
subscriptionId: null,
resourceGroup: null,
location: null,
deploymentName: null,
cancellationToken: cancellationToken,
externalInputs: []);
Comment on lines +63 to +69

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think realistically we'd need a way for someone to supply these inputs, but this would result in a complex UI experience, unless we're able to save the values somewhere.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can build a tree view for selecting scope later. It would be great if both deploy pane and the snapshot command can share the same UI.


if (snapshot.Diagnostics.Length > 0)
{
var diagnosticsMessage = string.Join("\n", snapshot.Diagnostics.Select(d => $" {d}"));
return $"Snapshot generation completed with warnings:\n{diagnosticsMessage}\n\nSnapshot file created at {snapshotFileUri}";
}

var contents = SnapshotHelper.Serialize(snapshot);
await snapshotFile.WriteAllTextAsync(contents, cancellationToken);

return $"Snapshot generation succeeded. Created file {snapshotFileUri}";
}
catch (Exception ex)
{
return $"Snapshot generation failed: {ex.Message}";
}
}
}
}
1 change: 1 addition & 0 deletions src/Bicep.LangServer/LangServerConstants.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ public static class LangServerConstants
public const string DecompileSaveCommand = "decompileSave";
public const string GenerateParamsCommand = "generateParams";
public const string BuildParamsCommand = "buildParams";
public const string SnapshotCommand = "snapshot";
public const string DeployCompleteMethod = "deploymentComplete";
public const string DeployStartCommand = "deploy/start";
public const string DeployWaitForCompletionCommand = "deploy/waitForCompletion";
Expand Down
1 change: 1 addition & 0 deletions src/Bicep.LangServer/Server.cs
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,7 @@ public Server(BicepLangServerOptions bicepLangServerOptions, Action<LanguageServ
.WithHandler<BicepBuildCommandHandler>()
.WithHandler<BicepGenerateParamsCommandHandler>()
.WithHandler<BicepBuildParamsCommandHandler>()
.WithHandler<BicepSnapshotCommandHandler>()
.WithHandler<BicepDeploymentStartCommandHandler>()
// Base handler (ExecuteTypedResponseCommandHandlerBase) is serial. This blocks other commands on the client side.
// To avoid the above issue, we'll change the RequestProcessType to parallel
Expand Down
25 changes: 25 additions & 0 deletions src/vscode-bicep/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -271,6 +271,12 @@
"category": "Bicep",
"icon": "$(output)"
},
{
"command": "bicep.snapshot",
"title": "Generate Snapshot",
Comment thread
shenglol marked this conversation as resolved.
"category": "Bicep",
"icon": "$(file-code)"
},
{
"command": "bicep.internal.showModuleSourceFile",
"title": "(Show a source file from a module)",
Expand Down Expand Up @@ -425,6 +431,11 @@
"when": "resourceLangId == bicep-params",
"group": "2_bicep_1_edit"
},
{
"command": "bicep.snapshot",
"when": "resourceLangId == bicep-params",
"group": "2_bicep_1_edit"
},
{
"command": "bicep.decompileParams",
"when": "resourceLangId == json || resourceLangId == jsonc",
Expand Down Expand Up @@ -487,6 +498,11 @@
"when": "resourceLangId == bicep-params",
"group": "2_bicep_1_edit"
},
{
"command": "bicep.snapshot",
"when": "resourceLangId == bicep-params",
"group": "2_bicep_1_edit"
},
{
"command": "bicep.decompileParams",
"when": "resourceLangId == json || resourceLangId == jsonc",
Expand Down Expand Up @@ -554,6 +570,11 @@
"when": "resourceLangId == bicep-params",
"group": "2_bicep_1_edit"
},
{
"command": "bicep.snapshot",
"when": "resourceLangId == bicep-params",
"group": "2_bicep_1_edit"
},
{
"command": "bicep.decompileParams",
"when": "resourceLangId == json || resourceLangId == jsonc",
Expand Down Expand Up @@ -620,6 +641,10 @@
"command": "bicep.buildParams",
"group": "0_bicep"
},
{
"command": "bicep.snapshot",
"group": "0_bicep"
},
{
"command": "bicep.internal.showModuleSourceFile",
"when": "never"
Expand Down
43 changes: 43 additions & 0 deletions src/vscode-bicep/src/commands/snapshot.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
import { IActionContext, parseError } from "@microsoft/vscode-azext-utils";
import vscode from "vscode";
import { LanguageClient } from "vscode-languageclient/node";
import { OutputChannelManager } from "../utils/OutputChannelManager";
import { findOrCreateActiveBicepParamFile } from "./findOrCreateActiveBicepFile";
import { Command } from "./types";

export class SnapshotCommand implements Command {
public readonly id = "bicep.snapshot";
public constructor(
private readonly client: LanguageClient,
private readonly outputChannelManager: OutputChannelManager,
) {}

public async execute(context: IActionContext, documentUri?: vscode.Uri | undefined): Promise<void> {
documentUri = await findOrCreateActiveBicepParamFile(
context,
documentUri,
"Choose which Bicep Parameters file to generate a snapshot from",
);

if (documentUri.scheme.toLowerCase() !== "file") {
this.client.error(
"Snapshot generation failed. The active file must be saved to your local filesystem.",
undefined,
true,
);
return;
}

try {
const snapshotOutput: string = await this.client.sendRequest("workspace/executeCommand", {
command: "snapshot",
arguments: [documentUri.toString()],
});
this.outputChannelManager.appendToOutputChannel(snapshotOutput);
} catch (err) {
this.client.error("Snapshot generation failed", parseError(err).message, true);
}
}
}
2 changes: 2 additions & 0 deletions src/vscode-bicep/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import * as lsp from "vscode-languageclient/node";
import { AzureUiManager } from "./azure/AzureUiManager";
import { BuildCommand } from "./commands/build";
import { BuildParamsCommand } from "./commands/buildParams";
import { SnapshotCommand } from "./commands/snapshot";
import { CommandManager } from "./commands/commandManager";
import { CreateBicepConfigurationFile } from "./commands/createConfigurationFile";
import { DecompileCommand } from "./commands/decompile";
Expand Down Expand Up @@ -147,6 +148,7 @@ export async function activate(extensionContext: ExtensionContext): Promise<void
new BuildCommand(languageClient, outputChannelManager),
new GenerateParamsCommand(languageClient, outputChannelManager),
new BuildParamsCommand(languageClient, outputChannelManager),
new SnapshotCommand(languageClient, outputChannelManager),
new CreateBicepConfigurationFile(languageClient),
new DeployCommand(languageClient, outputChannelManager, azurePickers),
new DecompileCommand(languageClient, outputChannelManager),
Expand Down
Loading