/
Sample Code - Plugin
Sample Code - Plugin
import * as vscode from 'vscode';
import { DelveDebugAdapterDescriptorFactory } from './delveDebugAdapterFactory';
export function activate(context: vscode.ExtensionContext) {
console.log('Hyperledger Chaincode Debugger is active.');
// Register the debug adapter factory
context.subscriptions.push(
vscode.debug.registerDebugAdapterDescriptorFactory('delve', new DelveDebugAdapterDescriptorFactory())
);
// Listen for debugging session events
vscode.debug.onDidStartDebugSession((session) => {
console.log(`Debugging started: ${session.name}`);
vscode.window.showInformationMessage(`Debugging started: ${session.name}`);
});
vscode.debug.onDidTerminateDebugSession((session) => {
console.log(`Debugging terminated: ${session.name}`);
vscode.window.showInformationMessage(`Debugging terminated: ${session.name}`);
});
}
export function deactivate() {
console.log('Hyperledger Chaincode Debugger is deactivated.');
}
import * as vscode from 'vscode';
import { spawn, ChildProcess } from 'child_process';
import * as path from 'path';
import { DelveDebugAdapter } from './delveDebugAdapter';
export class DelveDebugAdapterDescriptorFactory implements vscode.DebugAdapterDescriptorFactory {
private delveProcess: ChildProcess | undefined;
createDebugAdapterDescriptor(
session: vscode.DebugSession
): vscode.ProviderResult<vscode.DebugAdapterDescriptor> {
const config = session.configuration;
const program = config.program;
const port = config.port || 2345;
if (!program) {
vscode.window.showErrorMessage('No program specified to debug.');
return;
}
// Start Delve as a headless server
this.delveProcess = spawn('dlv', [
'debug',
'--headless',
`--listen=127.0.0.1:${port}`,
'--log',
'--api-version=2',
program
], {
cwd: path.dirname(program),
env: process.env
});
this.delveProcess.stdout.on('data', (data) => {
console.log(`Delve: ${data}`);
});
this.delveProcess.stderr.on('data', (data) => {
console.error(`Delve Error: ${data}`);
});
this.delveProcess.on('exit', (code) => {
console.log(`Delve exited with code ${code}`);
});
// Return a custom debug adapter to handle requests
return new DelveDebugAdapter(port, '127.0.0.1');
}
dispose() {
if (this.delveProcess) {
this.delveProcess.kill();
this.delveProcess = undefined;
}
}
}
import { DebugSession, InitializedEvent, StoppedEvent, TerminatedEvent } from '@vscode/debugadapter';
import { DebugProtocol } from '@vscode/debugprotocol';
import { Socket } from 'net';
export class DelveDebugAdapter extends DebugSession {
private socket: Socket;
constructor(port: number, host: string) {
super();
// Connect to the Delve server
this.socket = new Socket();
this.socket.connect(port, host, () => {
console.log('Connected to Delve server');
});
this.socket.on('data', (data) => {
console.log(`Received data from Delve: ${data}`);
});
this.socket.on('error', (err) => {
console.error(`Socket error: ${err.message}`);
});
this.socket.on('close', () => {
console.log('Connection to Delve server closed');
});
}
protected async dispatchRequest(request: DebugProtocol.Request): Promise<void> {
console.log(`Received request: ${request.command}`);
switch (request.command) {
case 'initialize':
console.log('Debugging session initialized');
break;
case 'next':
console.log('User clicked Step Over');
break;
case 'stepIn':
console.log('User clicked Step In');
break;
case 'stepOut':
console.log('User clicked Step Out');
break;
case 'continue':
console.log('User clicked Continue');
break;
case 'pause':
console.log('User clicked Pause');
break;
default:
console.log(`Unhandled command: ${request.command}`);
}
// Forward the request to Delve
this.socket.write(JSON.stringify(request));
await super.dispatchRequest(request);
}
dispose() {
this.socket.destroy();
}
}
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug Hyperledger Chaincode (Delve Server)",
"type": "delve",
"request": "launch",
"program": "${workspaceFolder}/path/to/chaincode",
"port": 2345
}
]
}
require("fabric-protos");
const protobuf = require("protobufjs");
// Assuming you have a .proto file defining your message
protobuf.load("common.proto", (err, root) => {
if (err) throw err;
// Get the message type
const Block = root.lookupType("fabric-protos.common.Block");
// The buffer containing the serialized message
const buffer = // response from the fabric peer;
// Deserialize the message
try {
const message = Block.decode(buffer);
console.log(message);
} catch (e) {
console.error("Error decoding message:", e);
}
});
// Alternative
import(fabric-common);
Block block = BlockDecoder.decodeBlock(response);
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
// Generate launch.json dynamically
generateLaunchConfig();
}
// this can also be written just when the debug session is activated
async function generateLaunchConfig() {
if (!vscode.workspace.workspaceFolders) {
vscode.window.showErrorMessage("No workspace folder open.");
return;
}
const workspacePath = vscode.workspace.workspaceFolders[0].uri.fsPath;
const launchJsonPath = path.join(workspacePath, ".vscode", "launch.json");
let launchConfig: any = {
version: "0.2.0",
configurations: [
{
type: "custom-debug",
request: "launch",
name: "Launch Custom Debugger",
program: "${workspaceFolder}/main.js",
args: ["--verbose"],
stopOnEntry: true,
cwd: "${workspaceFolder}",
console: "integratedTerminal",
trace: "verbose"
}
]
};
try {
// Ensure .vscode folder exists
const vscodeFolder = path.join(workspacePath, ".vscode");
if (!fs.existsSync(vscodeFolder)) {
fs.mkdirSync(vscodeFolder);
}
// Check if launch.json exists and merge configurations if necessary
if (fs.existsSync(launchJsonPath)) {
const existingContent = fs.readFileSync(launchJsonPath, "utf8");
const existingJson = JSON.parse(existingContent);
// Merge configurations to avoid overwriting user settings
existingJson.configurations = [
...existingJson.configurations,
...launchConfig.configurations
];
launchConfig = existingJson;
}
// Write to launch.json
fs.writeFileSync(launchJsonPath, JSON.stringify(launchConfig, null, 4));
vscode.window.showInformationMessage("launch.json updated successfully!");
} catch (error) {
vscode.window.showErrorMessage("Failed to update launch.json: " + error.message);
}
}
export function deactivate() {}
, multiple selections available,
Related content
VS Code Debugger Plugin for Hyperledger Fabric Chaincode
VS Code Debugger Plugin for Hyperledger Fabric Chaincode
More like this
VS Code Plugin - Project Plan
VS Code Plugin - Project Plan
More like this
July 14 2024
July 14 2024
More like this
July 21 2024
July 21 2024
More like this
Project Plan
Project Plan
More like this
July 07 2024
July 07 2024
More like this