|
| 1 | +import * as vscode from 'vscode' |
| 2 | +import dayjs from 'dayjs' |
| 3 | +import { CHECKPOINTS_STATE_KEY } from '../../../constants/state-keys' |
| 4 | +import type { Checkpoint } from '../types' |
| 5 | +import { get_checkpoint_path } from '../utils' |
| 6 | + |
| 7 | +export const delete_checkpoint = async (params: { |
| 8 | + context: vscode.ExtensionContext |
| 9 | + checkpoint_to_delete: Checkpoint |
| 10 | + options?: { skip_undo_prompt?: boolean } |
| 11 | +}) => { |
| 12 | + // First, remove checkpoint from state. This makes the deletion immediate from user's perspective. |
| 13 | + const checkpoints = |
| 14 | + params.context.workspaceState.get<Checkpoint[]>( |
| 15 | + CHECKPOINTS_STATE_KEY, |
| 16 | + [] |
| 17 | + ) ?? [] |
| 18 | + const updated_checkpoints = checkpoints.filter( |
| 19 | + (c) => c.timestamp != params.checkpoint_to_delete.timestamp |
| 20 | + ) |
| 21 | + await params.context.workspaceState.update( |
| 22 | + CHECKPOINTS_STATE_KEY, |
| 23 | + updated_checkpoints |
| 24 | + ) |
| 25 | + |
| 26 | + const actually_delete_files = async () => { |
| 27 | + try { |
| 28 | + const checkpoint_path = get_checkpoint_path( |
| 29 | + params.checkpoint_to_delete.timestamp |
| 30 | + ) |
| 31 | + await vscode.workspace.fs.delete(vscode.Uri.file(checkpoint_path), { |
| 32 | + recursive: true |
| 33 | + }) |
| 34 | + } catch (error) { |
| 35 | + console.warn(`Could not delete checkpoint file: ${error}`) |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + if (!params.options?.skip_undo_prompt) { |
| 40 | + vscode.window |
| 41 | + .showInformationMessage( |
| 42 | + `Checkpoint from ${dayjs( |
| 43 | + params.checkpoint_to_delete.timestamp |
| 44 | + ).fromNow()} deleted successfully.`, |
| 45 | + 'Revert' |
| 46 | + ) |
| 47 | + .then(async (action) => { |
| 48 | + if (action == 'Revert') { |
| 49 | + // User chose to revert. Add the checkpoint back to the state. |
| 50 | + const current_checkpoints = |
| 51 | + params.context.workspaceState.get<Checkpoint[]>( |
| 52 | + CHECKPOINTS_STATE_KEY, |
| 53 | + [] |
| 54 | + ) ?? [] |
| 55 | + current_checkpoints.push(params.checkpoint_to_delete) |
| 56 | + await params.context.workspaceState.update( |
| 57 | + CHECKPOINTS_STATE_KEY, |
| 58 | + current_checkpoints |
| 59 | + ) |
| 60 | + vscode.window.showInformationMessage('Checkpoint deletion reverted.') |
| 61 | + } else { |
| 62 | + // User dismissed the notification or it timed out. |
| 63 | + // Proceed with deleting the checkpoint files. |
| 64 | + await actually_delete_files() |
| 65 | + } |
| 66 | + }) |
| 67 | + } else { |
| 68 | + // This is a silent deletion (e.g. temporary checkpoint cleanup), no need |
| 69 | + // to ask for revert. |
| 70 | + await actually_delete_files() |
| 71 | + } |
| 72 | +} |
0 commit comments