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 * as vscode from 'vscode';
import { spawn } from 'child_process'; import { spawn } from 'child_process';
import * as fs from 'fs'; import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path'; import * as path from 'path';
export function activate(context: vscode.ExtensionContext) { vscode.languages.registerDocumentFormattingEditProvider('hblang', {
// Register a document formatting edit provider for the language
context.subscriptions.push(
vscode.languages.registerDocumentFormattingEditProvider('hblang', {
async provideDocumentFormattingEdits(document: vscode.TextDocument): Promise<vscode.TextEdit[]> { async provideDocumentFormattingEdits(document: vscode.TextDocument): Promise<vscode.TextEdit[]> {
try { try {
const formattedText = await formatDocument(document.fileName); const filePath = document.uri.fsPath;
const tempFilePath = path.join(path.dirname(filePath), `temp_${path.basename(filePath)}`);
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> {
await fs.promises.writeFile(tempFilePath, document.getText());
return new Promise((resolve, reject) => { 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 hbcProcess.stdout.on('data', (data) => {
child.stdout.on('data', (data) => { stdout += data.toString();
formattedText += data.toString();
}); });
// Handle errors hbcProcess.stderr.on('data', (data) => {
child.stderr.on('data', (data) => { stderr += data.toString();
reject(new Error(data.toString()));
}); });
// Handle process exit hbcProcess.on('close', (code) => {
child.on('exit', (code) => { fs.unlink(tempFilePath, (err) => {
if (err) {
if (code === 0) { console.error('Error removing temp file:', err);
resolve(formattedText);
} else {
reject(new Error(`Formatter exited with code ${code}`));
} }
}); });
if (code === 0) {
const fullRange = new vscode.Range(
document.positionAt(0),
document.positionAt(document.getText().length)
);
const edit = vscode.TextEdit.replace(fullRange, stdout);
resolve([edit]);
} else {
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 [];
}
}
});