good enough formatter

This commit is contained in:
koniifer 2024-09-30 12:57:01 +01:00
parent 9098604bf0
commit 4b5bb991f7

View file

@ -1,66 +1,62 @@
import * as vscode from 'vscode';
import { spawn } from 'child_process';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
// Register a document formatting edit provider for the language
context.subscriptions.push(
vscode.languages.registerDocumentFormattingEditProvider('hblang', {
async provideDocumentFormattingEdits(document: vscode.TextDocument): Promise<vscode.TextEdit[]> {
try {
const formattedText = await formatDocument(document.fileName);
const edit = new vscode.TextEdit(
new vscode.Range(0, 0, document.lineCount, 0),
formattedText
);
return [edit];
} catch (error: unknown) {
if (error instanceof Error) {
vscode.window.showErrorMessage(`Formatting failed: ${error.message}`);
} else {
vscode.window.showErrorMessage(`Formatting failed: ${String(error)}`);
}
return []; // Return an empty array if formatting fails
}
}
})
);
}
export function deactivate() { }
async function formatDocument(path: string): Promise<string> {
const filePath = document.uri.fsPath;
const tempFilePath = path.join(path.dirname(filePath), `temp_${path.basename(filePath)}`);
await fs.promises.writeFile(tempFilePath, document.getText());
return new Promise((resolve, reject) => {
const child = spawn('hbc', ['--fmt-stdout', path], { shell: true });
const hbcProcess = spawn('hbc', ['--fmt-stdout', tempFilePath]);
let formattedText = '';
let stdout = '';
let stderr = '';
// Capture the output
child.stdout.on('data', (data) => {
formattedText += data.toString();
hbcProcess.stdout.on('data', (data) => {
stdout += data.toString();
});
// Handle errors
child.stderr.on('data', (data) => {
reject(new Error(data.toString()));
hbcProcess.stderr.on('data', (data) => {
stderr += data.toString();
});
// Handle process exit
child.on('exit', (code) => {
hbcProcess.on('close', (code) => {
fs.unlink(tempFilePath, (err) => {
if (err) {
console.error('Error removing temp file:', err);
}
});
if (code === 0) {
resolve(formattedText);
const fullRange = new vscode.Range(
document.positionAt(0),
document.positionAt(document.getText().length)
);
const edit = vscode.TextEdit.replace(fullRange, stdout);
resolve([edit]);
} else {
reject(new Error(`Formatter exited with code ${code}`));
vscode.window.showErrorMessage(`hbc formatting failed: ${stderr}`);
reject(new Error(stderr));
}
});
hbcProcess.on('error', (err) => {
vscode.window.showErrorMessage(`Failed to start hbc: ${err.message}`);
reject(err);
});
});
} catch (error) {
if (error instanceof Error) {
vscode.window.showErrorMessage(`Error formatting document: ${error.message}`);
} else {
vscode.window.showErrorMessage('An unknown error occurred while formatting the document.');
}
return [];
}
}
});