๐Ÿ“ฆ hediet / bulk-file-editor

๐Ÿ“„ extension.ts ยท 319 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319import * as vscode from 'vscode';
import * as path from 'path';
import * as os from 'os';
import { splitContent, mergeFiles, IFileSystem, IPath, LineFormatter, IWriter, HashMismatchError, getMerchFileExtension, parseMerchDoc, analyzeMerchDoc } from '../lib';

class VSCodeFileSystem implements IFileSystem {
    readonly path: IPath = path;

    async readFile(filePath: string): Promise<string> {
        const uri = vscode.Uri.file(filePath);
        const bytes = await vscode.workspace.fs.readFile(uri);
        return new TextDecoder().decode(bytes);
    }

    async writeFile(filePath: string, content: string): Promise<void> {
        const uri = vscode.Uri.file(filePath);
        const bytes = new TextEncoder().encode(content);
        await vscode.workspace.fs.writeFile(uri, bytes);
    }

    async exists(filePath: string): Promise<boolean> {
        try {
            await vscode.workspace.fs.stat(vscode.Uri.file(filePath));
            return true;
        } catch {
            return false;
        }
    }

    async isFile(filePath: string): Promise<boolean> {
        try {
            const stat = await vscode.workspace.fs.stat(vscode.Uri.file(filePath));
            return stat.type === vscode.FileType.File;
        } catch {
            return false;
        }
    }

    async delete(filePath: string): Promise<void> {
        await vscode.workspace.fs.delete(vscode.Uri.file(filePath), { recursive: false });
    }

    async rename(oldPath: string, newPath: string): Promise<void> {
        await vscode.workspace.fs.rename(vscode.Uri.file(oldPath), vscode.Uri.file(newPath));
    }

    async mkdir(dirPath: string): Promise<void> {
        await vscode.workspace.fs.createDirectory(vscode.Uri.file(dirPath));
    }
}

class StringWriter implements IWriter {
    public content = '';
    write(chunk: string): void {
        this.content += chunk;
    }
}

export function activate(context: vscode.ExtensionContext) {
    const fs = new VSCodeFileSystem();

    const decorationType = vscode.window.createTextEditorDecorationType({
        backgroundColor: 'rgba(255, 255, 0, 0.1)', // More transparent
        isWholeLine: true,
    });

    const infoDecorationType = vscode.window.createTextEditorDecorationType({
        after: {
            color: new vscode.ThemeColor('descriptionForeground'),
            margin: '0 0 0 2em',
            fontStyle: 'italic'
        }
    });

    const warningDecorationType = vscode.window.createTextEditorDecorationType({
        after: {
            color: new vscode.ThemeColor('editorWarning.foreground'),
            margin: '0 0 0 2em',
            fontStyle: 'italic'
        }
    });

    const errorDecorationType = vscode.window.createTextEditorDecorationType({
        textDecoration: 'wavy underline',
        after: {
            color: new vscode.ThemeColor('editorError.foreground'),
            margin: '0 0 0 2em',
            fontStyle: 'italic'
        }
    });

    const successDecorationType = vscode.window.createTextEditorDecorationType({
        after: {
            color: 'green', // Or a theme color if available
            margin: '0 0 0 2em',
            fontStyle: 'italic'
        }
    });

    const updateDecorations = async (editor: vscode.TextEditor) => {
        if (!editor.document.fileName.includes('.merch.')) {
            return;
        }

        const text = editor.document.getText();
        const ranges: vscode.Range[] = [];
        const infoRanges: vscode.DecorationOptions[] = [];
        const warningRanges: vscode.DecorationOptions[] = [];
        const errorRanges: vscode.DecorationOptions[] = [];
        const successRanges: vscode.DecorationOptions[] = [];

        try {
            const doc = parseMerchDoc(text);
            const statuses = await analyzeMerchDoc(text, doc);

            // Add background for all headers
            if (doc.setupHeaderRange) {
                const startPos = editor.document.positionAt(doc.setupHeaderRange.start);
                const endPos = editor.document.positionAt(doc.setupHeaderRange.endExclusive);
                ranges.push(new vscode.Range(startPos, endPos));
            }

            for (const file of doc.existingFiles) {
                const startPos = editor.document.positionAt(file.headerOffsetRange.start);
                const endPos = editor.document.positionAt(file.headerOffsetRange.endExclusive);
                ranges.push(new vscode.Range(startPos, endPos));
            }

            for (const file of doc.updatedFiles.values()) {
                const startPos = editor.document.positionAt(file.headerOffsetRange.start);
                const endPos = editor.document.positionAt(file.headerOffsetRange.endExclusive);
                ranges.push(new vscode.Range(startPos, endPos));
            }

            for (const diag of doc.diagnostics) {
                const startPos = editor.document.positionAt(diag.range.start);
                const endPos = editor.document.positionAt(diag.range.endExclusive);
                ranges.push(new vscode.Range(startPos, endPos));
            }

            for (const status of statuses) {
                const startPos = editor.document.positionAt(status.range.start);
                const endPos = editor.document.positionAt(status.range.endExclusive);
                const range = new vscode.Range(startPos, endPos);
                const decoration: vscode.DecorationOptions = {
                    range,
                    renderOptions: {
                        after: {
                            contentText: status.message
                        }
                    }
                };

                switch (status.type) {
                    case 'info':
                        infoRanges.push(decoration);
                        break;
                    case 'warning':
                        warningRanges.push(decoration);
                        break;
                    case 'error':
                        errorRanges.push(decoration);
                        break;
                    case 'success':
                        successRanges.push(decoration);
                        break;
                }
            }

        } catch (e) {
            console.error('Error updating decorations:', e);
        }

        editor.setDecorations(decorationType, ranges);
        editor.setDecorations(infoDecorationType, infoRanges);
        editor.setDecorations(warningDecorationType, warningRanges);
        editor.setDecorations(errorDecorationType, errorRanges);
        editor.setDecorations(successDecorationType, successRanges);
    };

    vscode.window.onDidChangeActiveTextEditor(editor => {
        if (editor) {
            updateDecorations(editor);
        }
    }, null, context.subscriptions);

    vscode.workspace.onDidChangeTextDocument(event => {
        const editor = vscode.window.activeTextEditor;
        if (editor && event.document === editor.document) {
            updateDecorations(editor);
        }
    }, null, context.subscriptions);

    if (vscode.window.activeTextEditor) {
        updateDecorations(vscode.window.activeTextEditor);
    }

    context.subscriptions.push(vscode.commands.registerCommand('merch.split', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('No active editor');
            return;
        }

        const doc = editor.document;
        if (doc.isDirty) {
            await doc.save();
        }

        const filePath = doc.fileName;
        try {
            await splitContent(doc.getText(), false, fs);
            vscode.window.showInformationMessage('Merch file split successfully');
        } catch (e: any) {
            vscode.window.showErrorMessage(`Error splitting merch file: ${e.message}`);
        }
    }));

    context.subscriptions.push(vscode.commands.registerCommand('merch.editFolder', async (uri: vscode.Uri) => {
        if (!uri) {
            vscode.window.showErrorMessage('No folder selected');
            return;
        }

        const folderPath = uri.fsPath;
        const folderName = path.basename(folderPath);
        const randomId = Math.random().toString(36).substring(7);

        try {
            // List files recursively
            const files = await listFilesRecursively(uri);
            const filePaths = files.map(f => f.fsPath);

            const ext = getMerchFileExtension(filePaths);
            const tempFileName = `${folderName}-${randomId}.merch${ext}`;
            const tempFilePath = path.join(os.tmpdir(), tempFileName);

            const writer = new StringWriter();
            const formatter = new LineFormatter('// ', '');
            
            await mergeFiles(filePaths, writer, formatter, folderPath, false, fs);
            
            await fs.writeFile(tempFilePath, writer.content);
            
            const doc = await vscode.workspace.openTextDocument(tempFilePath);
            await vscode.window.showTextDocument(doc);
        } catch (e: any) {
            vscode.window.showErrorMessage(`Error creating merch file: ${e.message}`);
        }
    }));

    context.subscriptions.push(vscode.commands.registerCommand('merch.apply', async () => {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            vscode.window.showErrorMessage('No active editor');
            return;
        }

        const doc = editor.document;
        // We don't necessarily need to save, we can use the content in the editor
        const content = doc.getText();

        const apply = async (checkHash: boolean) => {
            try {
                const actions = await splitContent(content, false, fs, console.log, checkHash);
                
                if (actions.length === 0) {
                    vscode.window.showInformationMessage('No changes applied');
                } else {
                    const updates = actions.filter(a => a.type === 'write').length;
                    const renames = actions.filter(a => a.type === 'rename').length;
                    const deletes = actions.filter(a => a.type === 'delete').length;
                    
                    const parts: string[] = [];
                    if (updates > 0) parts.push(`${updates} Content Update${updates > 1 ? 's' : ''}`);
                    if (renames > 0) parts.push(`${renames} Rename${renames > 1 ? 's' : ''}`);
                    if (deletes > 0) parts.push(`${deletes} Delete${deletes > 1 ? 's' : ''}`);
                    
                    vscode.window.showInformationMessage(`${parts.join(', ')} applied successfully`);
                }

                // Close the editor
                await vscode.commands.executeCommand('workbench.action.closeActiveEditor');
            } catch (e: any) {
                if (e instanceof HashMismatchError) {
                    const selection = await vscode.window.showErrorMessage(
                        `Error applying changes: ${e.message}. The file on disk has changed since the merch file was created.`,
                        'Overwrite changed files'
                    );
                    if (selection === 'Overwrite changed files') {
                        await apply(false);
                    }
                } else {
                    vscode.window.showErrorMessage(`Error applying changes: ${e.message}`);
                }
            }
        };

        await apply(true);
    }));
}

async function listFilesRecursively(folderUri: vscode.Uri): Promise<vscode.Uri[]> {
    const result: vscode.Uri[] = [];
    const entries = await vscode.workspace.fs.readDirectory(folderUri);
    
    for (const [name, type] of entries) {
        const uri = vscode.Uri.joinPath(folderUri, name);
        if (type === vscode.FileType.File) {
            result.push(uri);
        } else if (type === vscode.FileType.Directory) {
            result.push(...await listFilesRecursively(uri));
        }
    }
    return result;
}

export function deactivate() {}