maksit-openfolderrecurs/src/extension.ts

155 lines
5.6 KiB
TypeScript

import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
// Command: Open files in batches, wait for lint, and close if no errors
let lintAndCloseCommand = vscode.commands.registerCommand('maksit-openfolderrecurs.openAllFilesAndKeepWithErrors', async () => {
const folderUri = await vscode.window.showOpenDialog({
canSelectFolders: true,
canSelectFiles: false,
canSelectMany: false
});
if (!folderUri || folderUri.length === 0) {
return; // No folder selected
}
const folderPath = folderUri[0].fsPath;
const files = getAllFiles(folderPath);
const batchSize = 20;
for (let i = 0; i < files.length; i += batchSize) {
const batch = files.slice(i, i + batchSize);
await Promise.all(
batch.map(async (file) => {
try {
const document = await vscode.workspace.openTextDocument(file);
const editor = await vscode.window.showTextDocument(document, { preview: false });
// Wait for lint results
await waitForLinting(file);
} catch (error) {
console.warn(`Could not process file: ${file}. Skipping.`, error);
}
})
);
// Close documents in the current batch without lint errors
await closeDocumentsWithoutErrors(batch);
}
});
// Command: Close open documents without lint errors
let closeWithoutErrorsCommand = vscode.commands.registerCommand('maksit-openfolderrecurs.closeWithoutErrors', async () => {
await closeDocumentsWithoutErrors();
});
// Command: Open all files in a folder recursively
let openAllFilesCommand = vscode.commands.registerCommand('maksit-openfolderrecurs.openAllFiles', async () => {
const folderUri = await vscode.window.showOpenDialog({
canSelectFolders: true,
canSelectFiles: false,
canSelectMany: false
});
if (!folderUri || folderUri.length === 0) {
return; // No folder selected
}
const folderPath = folderUri[0].fsPath;
const files = getAllFiles(folderPath);
for (const file of files) {
try {
const document = await vscode.workspace.openTextDocument(file);
await vscode.window.showTextDocument(document, { preview: false });
} catch (error) {
console.warn(`Could not open file: ${file}. Skipping.`, error);
}
}
});
context.subscriptions.push(lintAndCloseCommand, closeWithoutErrorsCommand);
}
// Function to close open documents without lint errors
async function closeDocumentsWithoutErrors(filesToCheck?: string[]) {
const tabGroups = vscode.window.tabGroups.all;
for (const group of tabGroups) {
for (const tab of group.tabs) {
if (tab.input instanceof vscode.TabInputText) {
try {
const documentUri = tab.input.uri;
// If filesToCheck is provided, ensure the file is in the list
if (filesToCheck && !filesToCheck.includes(documentUri.fsPath)) {
continue;
}
const document = await vscode.workspace.openTextDocument(documentUri);
// Wait for lint results
await waitForLinting(document.fileName, 500);
// Check if there are no errors
const problems = vscode.languages.getDiagnostics(document.uri);
const hasErrors = problems.some(problem => problem.severity === vscode.DiagnosticSeverity.Error);
if (!hasErrors) {
// Set the document as active
await vscode.window.showTextDocument(document, { preview: false });
// Close the active editor
await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
// Add a delay to ensure the editor is closed before moving to the next one
await new Promise(resolve => setTimeout(resolve, 100));
}
} catch (error) {
console.error(`Failed to process document: ${error}`);
}
}
}
}
}
// Function to get all files recursively
function getAllFiles(dir: string, fileList: string[] = []): string[] {
const entries = fs.readdirSync(dir, { withFileTypes: true });
for (const entry of entries) {
const fullPath = path.join(dir, entry.name);
if (entry.isDirectory()) {
getAllFiles(fullPath, fileList);
} else if (entry.isFile()) {
fileList.push(fullPath);
}
}
return fileList;
}
// Function to wait for linting results to update
function waitForLinting(filePath: string, maxWaitTime: number = 5000): Promise<void> {
return new Promise((resolve) => {
const checkInterval = 500; // Check every 500ms
let elapsed = 0;
const interval = setInterval(() => {
const diagnostics = vscode.languages.getDiagnostics(vscode.Uri.file(filePath));
if (diagnostics.length > 0 || elapsed >= maxWaitTime) {
clearInterval(interval);
resolve();
} else {
elapsed += checkInterval;
}
}, checkInterval);
});
}
export function deactivate() {}