-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathextension.js
More file actions
491 lines (396 loc) · 18.9 KB
/
Copy pathextension.js
File metadata and controls
491 lines (396 loc) · 18.9 KB
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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
const vscode = require('vscode');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const SELECTION_HISTORY_KEY = 'copyFilesToClipboard.selectionHistory';
const MAX_AUTO_SAVED_ITEMS = 20;
// --- Tree Data Provider for the Custom View ---
class HistoryDataProvider {
constructor(context) {
this.context = context;
this._onDidChangeTreeData = new vscode.EventEmitter();
this.onDidChangeTreeData = this._onDidChangeTreeData.event;
this.activeSelectionId = null;
this.activeEditorFilePath = null;
}
viewSelection(selectionId) {
this.activeSelectionId = selectionId;
vscode.commands.executeCommand('setContext', 'copy-files-to-clipboard-llm.viewVisible', true);
this.refresh();
}
closeView() {
this.activeSelectionId = null;
vscode.commands.executeCommand('setContext', 'copy-files-to-clipboard-llm.viewVisible', false);
this.refresh();
}
refresh() {
this._onDidChangeTreeData.fire(undefined);
}
getTreeItem(element) {
return element;
}
getChildren(element) {
if (!this.activeSelectionId) {
return Promise.resolve([]);
}
const history = this.context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const activeSelection = history.find(s => s.id === this.activeSelectionId);
if (!activeSelection) {
return Promise.resolve([]);
}
if (element) { // Child nodes (files)
const workspaceFolder = vscode.workspace.getWorkspaceFolder(vscode.Uri.file(activeSelection.files[0] || ''));
const selectionFiles = new Set(activeSelection.files);
const displayPathsSet = new Set(activeSelection.files);
if (this.activeEditorFilePath) {
displayPathsSet.add(this.activeEditorFilePath);
}
const displayPaths = Array.from(displayPathsSet);
const fileItems = displayPaths.map(filePath => ({
filePath,
relativePath: workspaceFolder ?
path.relative(workspaceFolder.uri.fsPath, filePath) :
path.basename(filePath)
}));
fileItems.sort((a, b) => a.relativePath.localeCompare(b.relativePath));
return Promise.resolve(fileItems.map(({ filePath, relativePath }) => {
const isInSelection = selectionFiles.has(filePath);
const isSelectedInExplorer = filePath === this.activeEditorFilePath;
const item = new vscode.TreeItem(relativePath, vscode.TreeItemCollapsibleState.None);
item.resourceUri = vscode.Uri.file(filePath);
if (isInSelection) {
item.contextValue = 'file';
if (isSelectedInExplorer) {
item.label = { label: relativePath, highlights: [[0, relativePath.length]] };
}
} else {
item.contextValue = 'file-to-add';
item.iconPath = new vscode.ThemeIcon('add');
item.description = "(Not in selection)";
}
item.command = {
command: 'historyView.revealFile',
title: "Reveal File",
arguments: [item.resourceUri]
};
return item;
}));
} else { // Root node
const rootItem = new vscode.TreeItem(activeSelection.name, vscode.TreeItemCollapsibleState.Expanded);
rootItem.contextValue = 'history';
rootItem.description = `(${activeSelection.files.length} files)`;
rootItem.selectionId = activeSelection.id;
return Promise.resolve([rootItem]);
}
}
}
/**
* @param {vscode.ExtensionContext} context
*/
function activate(context) {
// --- Setup Tree View ---
const historyDataProvider = new HistoryDataProvider(context);
vscode.window.registerTreeDataProvider('historyView', historyDataProvider);
const updateActiveFile = () => {
const editor = vscode.window.activeTextEditor;
historyDataProvider.activeEditorFilePath = editor ? editor.document.uri.fsPath : null;
if (historyDataProvider.activeSelectionId) {
historyDataProvider.refresh();
}
};
context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(updateActiveFile));
// --- Command Registrations ---
context.subscriptions.push(vscode.commands.registerCommand('extension.copyFilesToClipboard', async (fileUri, selectedUris) => {
let files = getSelectedFiles(fileUri, selectedUris);
if (!files) return;
await copyFiles(files, context);
const filePaths = files.map(uri => uri.fsPath);
updateSelectionHistory(filePaths, context, `Selection from ${new Date().toLocaleTimeString()}`);
}));
context.subscriptions.push(vscode.commands.registerCommand('extension.copyFromHistory', async () => {
const loadItems = () => {
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
return history.map(selection => ({
label: selection.name,
description: `(${selection.files.length} files) - ${formatTimeAgo(selection.timestamp)}`,
detail: selection.files.map(f => path.basename(f)).join(', '),
selectionId: selection.id,
// Add two buttons: Edit and Trash
buttons: [
{
iconPath: new vscode.ThemeIcon('edit'),
tooltip: 'Edit Selection in Sidebar',
type: 'edit'
},
{
iconPath: new vscode.ThemeIcon('trash'),
tooltip: 'Delete Selection',
type: 'delete'
}
]
}));
};
const quickPickItems = loadItems();
if (quickPickItems.length === 0) {
vscode.window.showInformationMessage('No selection history found.');
return;
}
const quickPick = vscode.window.createQuickPick();
quickPick.items = quickPickItems;
quickPick.placeholder = 'Select a previous file selection to copy or edit';
quickPick.onDidAccept(async () => {
const selectedItem = quickPick.selectedItems[0];
if (selectedItem) {
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const selection = history.find(s => s.id === selectedItem.selectionId);
if (selection) {
await copyFiles(selection.files.map(f => vscode.Uri.file(f)), context);
updateAndReorderHistory(context, selection.id);
}
}
quickPick.hide();
});
quickPick.onDidTriggerItemButton(async (e) => {
const buttonType = e.button.type;
const selectionId = e.item.selectionId;
if (buttonType === 'edit') {
await vscode.commands.executeCommand('historyView.openInView', selectionId);
quickPick.hide();
} else if (buttonType === 'delete') {
// Handle manual deletion
let history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
history = history.filter(s => s.id !== selectionId);
await context.workspaceState.update(SELECTION_HISTORY_KEY, history);
vscode.commands.executeCommand('setContext', 'copy-files-to-clipboard-llm.historySize', history.length);
// If the deleted item was currently open in the view, close the view
if (historyDataProvider.activeSelectionId === selectionId) {
historyDataProvider.closeView();
}
// Refresh the Quick Pick items immediately
quickPick.items = loadItems();
}
});
quickPick.onDidHide(() => quickPick.dispose());
quickPick.show();
}));
// --- View-Related Commands ---
context.subscriptions.push(vscode.commands.registerCommand('historyView.openInView', (selectionId) => {
historyDataProvider.viewSelection(selectionId);
updateActiveFile();
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.closeView', () => {
historyDataProvider.closeView();
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.revealFile', (fileUri) => {
vscode.commands.executeCommand('revealInExplorer', fileUri);
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.copySelection', async () => {
if (!historyDataProvider.activeSelectionId) return;
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const selection = history.find(s => s.id === historyDataProvider.activeSelectionId);
if (selection) {
await copyFiles(selection.files.map(f => vscode.Uri.file(f)), context);
updateAndReorderHistory(context, selection.id);
historyDataProvider.closeView();
}
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.duplicateSelection', async () => {
// 1. Ensure we have an active selection open in the view
if (!historyDataProvider.activeSelectionId) return;
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const currentSelection = history.find(s => s.id === historyDataProvider.activeSelectionId);
if (!currentSelection) return;
// 2. Prompt user for a name for the duplicate
const newName = await vscode.window.showInputBox({
prompt: "Enter a name for the duplicated selection",
value: `${currentSelection.name} (Copy)`
});
if (!newName) return; // User cancelled
// 3. Create the new selection object
const newEntry = {
id: uuidv4(), // Generate a new ID
timestamp: new Date().toISOString(),
name: newName,
files: [...currentSelection.files], // Copy the file list
isRenamed: true // Mark as renamed so it doesn't get auto-deleted
};
// 4. Add to history
history.unshift(newEntry);
// 5. Run cleanup to ensure we respect the 20-item limit for non-renamed items
// (Though this is a renamed item, we still run the sort/clean logic for consistency)
const cleanedHistory = cleanupHistory(history);
await context.workspaceState.update(SELECTION_HISTORY_KEY, cleanedHistory);
vscode.commands.executeCommand('setContext', 'copy-files-to-clipboard-llm.historySize', cleanedHistory.length);
// 6. Switch the view to the newly created duplicate
historyDataProvider.viewSelection(newEntry.id);
vscode.window.showInformationMessage(`Selection duplicated as "${newName}"`);
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.renameSelection', async (historyItem) => {
const currentName = typeof historyItem.label === 'string'
? historyItem.label
: historyItem.label.label;
const newName = await vscode.window.showInputBox({
prompt: "Enter a new name for this selection",
value: currentName
});
if (newName) {
// When renamed, mark isRenamed as true so it persists
updateAndReorderHistory(context, historyItem.selectionId, { name: newName, isRenamed: true });
historyDataProvider.refresh();
}
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.addFileFromView', async (fileItem) => {
if (!historyDataProvider.activeSelectionId) return;
const filePath = fileItem.resourceUri.fsPath;
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const selection = history.find(s => s.id === historyDataProvider.activeSelectionId);
if (selection && !selection.files.includes(filePath)) {
const updatedFiles = [...selection.files, filePath];
updateAndReorderHistory(context, selection.id, { files: updatedFiles });
historyDataProvider.refresh();
}
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.addSelectedFiles', async (fileUri, selectedUris) => {
if (!historyDataProvider.activeSelectionId) {
vscode.window.showWarningMessage('There is no active LLM selection to add files to. Please use the "Copy From History..." command to open a selection for editing.');
return;
}
const files = getSelectedFiles(fileUri, selectedUris);
if (!files) return;
const filePathsToAdd = files.map(uri => uri.fsPath);
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const selection = history.find(s => s.id === historyDataProvider.activeSelectionId);
if (selection) {
const updatedFiles = Array.from(new Set([...selection.files, ...filePathsToAdd]));
updateAndReorderHistory(context, selection.id, { files: updatedFiles });
historyDataProvider.refresh();
}
}));
context.subscriptions.push(vscode.commands.registerCommand('historyView.removeFile', async (fileItem) => {
if (!historyDataProvider.activeSelectionId) return;
const filePathToRemove = fileItem.resourceUri.fsPath;
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const selection = history.find(s => s.id === historyDataProvider.activeSelectionId);
if (selection) {
const updatedFiles = selection.files.filter(f => f !== filePathToRemove);
updateAndReorderHistory(context, selection.id, { files: updatedFiles });
historyDataProvider.refresh();
}
}));
// Initialize context
const history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
vscode.commands.executeCommand('setContext', 'copy-files-to-clipboard-llm.historySize', history.length);
vscode.commands.executeCommand('setContext', 'copy-files-to-clipboard-llm.viewVisible', false);
updateActiveFile();
}
// --- Helper Functions ---
function formatTimeAgo(isoString) {
const date = new Date(isoString);
const now = new Date();
const seconds = Math.round((now - date) / 1000);
if (seconds < 60) return 'Just now';
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `${minutes} minute${minutes > 1 ? 's' : ''} ago`;
const hours = Math.round(minutes / 60);
if (hours < 24) return `${hours} hour${hours > 1 ? 's' : ''} ago`;
const days = Math.round(hours / 24);
if (days < 7) return `${days} day${days > 1 ? 's' : ''} ago`;
return date.toLocaleDateString();
}
function getSelectedFiles(fileUri, selectedUris) {
if (Array.isArray(selectedUris) && selectedUris.length > 0) {
return selectedUris;
}
if (fileUri) {
return [fileUri];
}
vscode.window.showWarningMessage('No file selected!');
return null;
}
/**
* Enforces the history limit logic:
* 1. Keeps ALL items marked as isRenamed: true.
* 2. Keeps only the top 20 items that are NOT renamed.
* 3. Returns the combined sorted list.
*/
function cleanupHistory(history) {
// Sort by timestamp desc to ensure we keep the most recent ones
history.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
const renamedItems = history.filter(item => item.isRenamed);
const autoItems = history.filter(item => !item.isRenamed);
// Only keep the most recent 20 auto-generated items
const keptAutoItems = autoItems.slice(0, MAX_AUTO_SAVED_ITEMS);
// Combine and re-sort
const combined = [...renamedItems, ...keptAutoItems];
return combined.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp));
}
function updateSelectionHistory(filePaths, context, name) {
let history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const newEntry = {
id: uuidv4(),
timestamp: new Date().toISOString(),
name: name,
files: filePaths,
isRenamed: false // Default to false for new automatic selections
};
history.unshift(newEntry);
// Apply the cleanup logic (keep renamed + 20 auto)
history = cleanupHistory(history);
context.workspaceState.update(SELECTION_HISTORY_KEY, history);
vscode.commands.executeCommand('setContext', 'copy-files-to-clipboard-llm.historySize', history.length);
}
function updateAndReorderHistory(context, selectionId, updates = {}) {
let history = context.workspaceState.get(SELECTION_HISTORY_KEY, []);
const index = history.findIndex(s => s.id === selectionId);
if (index !== -1) {
const itemToMove = history.splice(index, 1)[0];
const updatedItem = {
...itemToMove,
...updates,
timestamp: new Date().toISOString()
};
history.unshift(updatedItem);
// Apply cleanup logic again (in case a renamed item became un-renamed, or just to be safe)
history = cleanupHistory(history);
context.workspaceState.update(SELECTION_HISTORY_KEY, history);
}
}
async function copyFiles(files, context) {
if (!files || files.length === 0) {
vscode.window.showWarningMessage('No files to copy.');
return;
}
const workspaceFolder = vscode.workspace.getWorkspaceFolder(files[0]);
if (!workspaceFolder) {
vscode.window.showErrorMessage('Could not find a workspace for the selected files. Please open the containing folder in VS Code.');
return;
}
const workspaceFolderPath = workspaceFolder.uri.fsPath;
let finalString = '';
let errorCount = 0;
for (const fileUri of files) {
try {
const fileContentBytes = await vscode.workspace.fs.readFile(fileUri);
const fileContent = Buffer.from(fileContentBytes).toString('utf8');
const relativePath = path.relative(workspaceFolderPath, fileUri.fsPath);
finalString += `\`\`\`${relativePath}\n${fileContent}\n\`\`\`\n\n`;
} catch (err) {
errorCount++;
vscode.window.showErrorMessage(`Error reading file ${fileUri.fsPath}: ${err.message}`);
}
}
if (errorCount > 0 && finalString.length === 0) {
vscode.window.showErrorMessage(`Failed to read all ${errorCount} selected file(s).`);
return;
}
if (finalString.length > 0) {
await vscode.env.clipboard.writeText(finalString);
vscode.window.showInformationMessage(`${files.length - errorCount} file(s) copied to clipboard!`);
} else if (errorCount === 0) {
vscode.window.showWarningMessage('No files were copied.');
}
}
function deactivate() {}
module.exports = {
activate,
deactivate
};