|
| 1 | +import * as vscode from 'vscode'; |
| 2 | +import * as fs from 'fs'; |
| 3 | +import { DefaultValue } from 'vscode-trace-common/lib/types/customization'; |
| 4 | + |
| 5 | +/** |
| 6 | + * Service for handling file operations related to JSON configurations |
| 7 | + */ |
| 8 | +export class FileService { |
| 9 | + private fileWatchers: Map<string, vscode.Disposable>; |
| 10 | + private autoSaveListeners: Map<string, vscode.Disposable>; |
| 11 | + |
| 12 | + constructor() { |
| 13 | + this.fileWatchers = new Map(); |
| 14 | + this.autoSaveListeners = new Map(); |
| 15 | + } |
| 16 | + |
| 17 | + /** |
| 18 | + * Creates a configuration file from the provided config object. |
| 19 | + * If there is a file open, it modifies the content instead. |
| 20 | + * |
| 21 | + * This is the physical file that is displayed in the editor |
| 22 | + * @param fileUri The file path to write over or create the temp config file |
| 23 | + * @param json The json object to add to the file |
| 24 | + * @param meta Optional metadata for the file header |
| 25 | + */ |
| 26 | + public async loadJSONConfigFile(fileUri: vscode.Uri, json: DefaultValue): Promise<void> { |
| 27 | + const fileContent = [ |
| 28 | + '/**', |
| 29 | + '* A toolbar is located in the top-right', |
| 30 | + '* • Submit the current config', |
| 31 | + '* • Save this config for future use', |
| 32 | + '* • Load an existing config file', |
| 33 | + '*', |
| 34 | + '* You can also submit by simply closing the file', |
| 35 | + '*/', |
| 36 | + JSON.stringify(json, undefined, 2) |
| 37 | + ].join('\n'); |
| 38 | + |
| 39 | + // First, find the editor that's showing this document |
| 40 | + const openConfigEditor = vscode.window.visibleTextEditors.find( |
| 41 | + editor => editor.document.uri.toString() === fileUri.toString() |
| 42 | + ); |
| 43 | + |
| 44 | + if (openConfigEditor) { |
| 45 | + // If the editor is open, update its content using edit |
| 46 | + await openConfigEditor.edit(editBuilder => { |
| 47 | + // Replace the entire content |
| 48 | + const fullRange = new vscode.Range( |
| 49 | + 0, |
| 50 | + 0, |
| 51 | + openConfigEditor.document.lineCount - 1, |
| 52 | + openConfigEditor.document.lineAt(openConfigEditor.document.lineCount - 1).text.length |
| 53 | + ); |
| 54 | + editBuilder.replace(fullRange, fileContent); |
| 55 | + }); |
| 56 | + } else { |
| 57 | + // If no editor is open for this file, just write to the file |
| 58 | + await vscode.workspace.fs.writeFile(fileUri, Buffer.from(fileContent, 'utf-8')); |
| 59 | + } |
| 60 | + |
| 61 | + const document = await vscode.workspace.openTextDocument(fileUri); |
| 62 | + await document.save(); |
| 63 | + |
| 64 | + // Setup watcher for this file |
| 65 | + this.watchConfigFile(fileUri); |
| 66 | + } |
| 67 | + |
| 68 | + /** |
| 69 | + * Set up a watcher for the config file to enable settings-like behavior |
| 70 | + */ |
| 71 | + private watchConfigFile(fileUri: vscode.Uri): void { |
| 72 | + const key = fileUri.toString(); |
| 73 | + |
| 74 | + if (this.fileWatchers.has(key)) { |
| 75 | + this.fileWatchers.get(key)?.dispose(); |
| 76 | + } |
| 77 | + |
| 78 | + const watcher = vscode.workspace.createFileSystemWatcher( |
| 79 | + new vscode.RelativePattern( |
| 80 | + vscode.workspace.getWorkspaceFolder(fileUri)?.uri || fileUri, |
| 81 | + vscode.workspace.asRelativePath(fileUri) |
| 82 | + ) |
| 83 | + ); |
| 84 | + |
| 85 | + this.fileWatchers.set(key, watcher); |
| 86 | + this.setupAutoSaveForFile(fileUri); |
| 87 | + } |
| 88 | + |
| 89 | + /** |
| 90 | + * Sets up auto-save functionality for a specific file |
| 91 | + * @param fileUri The URI of the file to auto-save |
| 92 | + * @param delayMs Optional delay in milliseconds before saving (default: 500ms) |
| 93 | + * @private Internal method used by file watchers |
| 94 | + */ |
| 95 | + private async setupAutoSaveForFile(fileUri: vscode.Uri, delayMs: number = 250): Promise<void> { |
| 96 | + const key = fileUri.toString(); |
| 97 | + |
| 98 | + if (this.autoSaveListeners.has(key)) { |
| 99 | + this.autoSaveListeners.get(key)?.dispose(); |
| 100 | + this.autoSaveListeners.delete(key); |
| 101 | + } |
| 102 | + |
| 103 | + let saveTimeout: ReturnType<typeof setTimeout>; |
| 104 | + |
| 105 | + try { |
| 106 | + const document = await vscode.workspace.openTextDocument(fileUri); |
| 107 | + |
| 108 | + const changeListener = vscode.workspace.onDidChangeTextDocument(event => { |
| 109 | + if (event.document.uri.toString() === document.uri.toString()) { |
| 110 | + if (saveTimeout) { |
| 111 | + clearTimeout(saveTimeout); |
| 112 | + } |
| 113 | + |
| 114 | + saveTimeout = setTimeout(async () => { |
| 115 | + try { |
| 116 | + await document.save(); |
| 117 | + } catch (error) { |
| 118 | + console.error('Failed to auto-save document:', error); |
| 119 | + } |
| 120 | + }, delayMs); |
| 121 | + } |
| 122 | + }); |
| 123 | + |
| 124 | + // Store the listener |
| 125 | + this.autoSaveListeners.set(key, changeListener); |
| 126 | + } catch (error) { |
| 127 | + console.error(`Failed to set up auto-save for ${fileUri.toString()}:`, error); |
| 128 | + } |
| 129 | + } |
| 130 | + |
| 131 | + /** |
| 132 | + * Cleans up the temporary file and any watchers |
| 133 | + * @param filePath Path to the temporary file |
| 134 | + */ |
| 135 | + public cleanupTempFile(filePath: string): void { |
| 136 | + const fileUri = vscode.Uri.file(filePath); |
| 137 | + const key = fileUri.toString(); |
| 138 | + |
| 139 | + if (this.fileWatchers.has(key)) { |
| 140 | + this.fileWatchers.get(key)?.dispose(); |
| 141 | + this.fileWatchers.delete(key); |
| 142 | + } |
| 143 | + |
| 144 | + if (this.autoSaveListeners.has(key)) { |
| 145 | + this.autoSaveListeners.get(key)?.dispose(); |
| 146 | + this.autoSaveListeners.delete(key); |
| 147 | + } |
| 148 | + |
| 149 | + if (fs.existsSync(filePath)) { |
| 150 | + try { |
| 151 | + fs.unlinkSync(filePath); |
| 152 | + } catch (error) { |
| 153 | + console.error('Failed to delete temporary file:', error); |
| 154 | + } |
| 155 | + } |
| 156 | + } |
| 157 | + |
| 158 | + /** |
| 159 | + * Dispose all resources |
| 160 | + */ |
| 161 | + public dispose(): void { |
| 162 | + for (const watcher of this.fileWatchers.values()) { |
| 163 | + watcher.dispose(); |
| 164 | + } |
| 165 | + this.fileWatchers.clear(); |
| 166 | + |
| 167 | + for (const listener of this.autoSaveListeners.values()) { |
| 168 | + listener.dispose(); |
| 169 | + } |
| 170 | + this.autoSaveListeners.clear(); |
| 171 | + } |
| 172 | +} |
0 commit comments