repositories / dotfiles
dotfiles
bugabingas dorkfiles
owned by bugabinga
opencode/tools/rm.ts
Rawimport { tool } from "@opencode-ai/plugin";
import path from "node:path";
import {
cp,
lstat,
mkdir,
readdir,
readFile,
readlink,
rm,
symlink,
writeFile,
} from "node:fs/promises";
const TRASH_DIR = ".trash";
export function getTrashPath(filePath: string, directory: string): string {
const timestamp = Date.now();
const relativePath = path.relative(directory, filePath);
return path.join(directory, TRASH_DIR, `${relativePath}..${timestamp}`);
}
export function assertWithinDirectory(
targetPath: string,
directory: string,
operation: string,
): void {
const resolvedTarget = path.resolve(targetPath);
const resolvedDir = path.resolve(directory);
const dirWithSep = resolvedDir.endsWith(path.sep)
? resolvedDir
: resolvedDir + path.sep;
if (
resolvedTarget !== resolvedDir && !resolvedTarget.startsWith(dirWithSep)
) {
throw new Error(
`${operation}: path escapes working directory: ${targetPath}`,
);
}
}
export async function safeStat(
filePath: string,
): Promise<{ exists: boolean; isDirectory: boolean }> {
try {
const stats = await lstat(filePath);
return { exists: true, isDirectory: stats.isDirectory() };
} catch (e: unknown) {
if ((e as NodeJS.ErrnoException).code === "ENOENT") {
return { exists: false, isDirectory: false };
}
throw e;
}
}
export async function isSymlink(filePath: string): Promise<boolean> {
try {
const stats = await lstat(filePath);
return stats.isSymbolicLink();
} catch {
return false;
}
}
export async function moveToTrash(
fullPath: string,
directory: string,
isDirectory: boolean,
): Promise<string> {
assertWithinDirectory(fullPath, directory, "moveToTrash");
const trashPath = getTrashPath(fullPath, directory);
await mkdir(path.dirname(trashPath), { recursive: true });
let symlinkBackupPath: string | null = null;
if (isDirectory) {
await cp(fullPath, trashPath, {
recursive: true,
preserveTimestamps: true,
});
} else {
const isLink = await isSymlink(fullPath);
if (isLink) {
const linkTarget = await readlink(fullPath);
symlinkBackupPath = trashPath + ".symlink";
await writeFile(symlinkBackupPath, linkTarget);
} else {
await cp(fullPath, trashPath);
}
}
try {
await rm(fullPath, { recursive: isDirectory, force: true });
} catch (e) {
const backupToClean = symlinkBackupPath ?? trashPath;
await rm(backupToClean, { recursive: true, force: true });
throw new Error(`Failed to delete: ${(e as Error).message}`);
}
return symlinkBackupPath || trashPath;
}
export function extractTimestamp(
filename: string,
): { path: string; timestamp: number } | null {
const isSymlinkBackup = filename.endsWith(".symlink");
let baseName = isSymlinkBackup ? filename.slice(0, -7) : filename;
if (baseName.endsWith(".")) {
baseName = baseName.slice(0, -1);
}
const match = baseName.match(/\.\.([0-9]+)$/);
if (!match || !match[1]) return null;
const timestamp = parseInt(match[1], 10);
if (isNaN(timestamp)) return null;
const now = Date.now();
if (timestamp > now + 60000) return null;
const path = baseName.replace(/\.\.([0-9]+)$/, "");
if (!path) return null;
return { path, timestamp };
}
async function removeItem(
itemPath: string,
context: { directory: string },
isDirectory: boolean,
toolName: string,
): Promise<string> {
const trimmedPath = itemPath.trim();
if (!trimmedPath) {
throw new Error(`${toolName} path cannot be empty`);
}
const fullPath = path.resolve(context.directory, trimmedPath);
const resolvedDir = path.resolve(context.directory);
if (fullPath === resolvedDir) {
throw new Error(`${toolName}: cannot delete project directory`);
}
assertWithinDirectory(fullPath, context.directory, toolName);
const itemStat = await safeStat(fullPath);
if (!itemStat.exists) {
throw new Error(`${toolName} not found: ${itemPath}`);
}
if (itemStat.isDirectory !== isDirectory) {
const actual = itemStat.isDirectory ? "directory" : "file";
const expected = isDirectory ? "file" : "directory";
throw new Error(
`Path is a ${actual}, use '${expected}' tool instead: ${itemPath}`,
);
}
const trashPath = await moveToTrash(fullPath, context.directory, isDirectory);
return `Removed: ${itemPath}\nBackup: ${trashPath}`;
}
export const file = tool({
description: "Safely remove a file by backing it up to .trash/",
args: {
filePath: tool.schema.string().describe("Path to file to remove"),
},
async execute(args, context) {
return removeItem(args.filePath, context, false, "file");
},
});
export const directory = tool({
description: "Safely remove a directory by backing it up to .trash/",
args: {
directory: tool.schema.string().describe("Path to directory to remove"),
},
async execute(args, context) {
return removeItem(args.directory, context, true, "directory");
},
});
export const restore = tool({
description: "Restore a file or directory from .trash/",
args: {
trashPath: tool.schema.string().describe(
"Full path to the trash backup to restore",
),
},
async execute(args, context) {
const trashArg = args.trashPath?.trim();
if (!trashArg) {
throw new Error("Trash path cannot be empty");
}
const fullTrashPath = path.resolve(context.directory, trashArg);
assertWithinDirectory(fullTrashPath, context.directory, "restore");
const trashStat = await safeStat(fullTrashPath);
if (!trashStat.exists) {
throw new Error(`Trash item not found: ${trashArg}`);
}
const trashDir = path.join(context.directory, TRASH_DIR);
const parsed = extractTimestamp(path.relative(trashDir, fullTrashPath));
if (!parsed) {
throw new Error(
`Invalid trash path format: ${trashArg}. Expected format: .trash/path/to/file..123456789`,
);
}
const resolvedOriginalPath = path.join(context.directory, parsed.path);
assertWithinDirectory(resolvedOriginalPath, context.directory, "restore");
const isSymlinkBackup = fullTrashPath.endsWith(".symlink");
let symlinkTarget: string | null = null;
if (isSymlinkBackup) {
const content = await readFile(fullTrashPath, "utf-8");
symlinkTarget = content.trim();
}
const existingStat = await safeStat(resolvedOriginalPath);
if (existingStat.exists) {
throw new Error(
`Destination already exists: ${parsed.path}. Cannot overwrite existing files.`,
);
}
await mkdir(path.dirname(resolvedOriginalPath), { recursive: true });
if (isSymlinkBackup && symlinkTarget) {
await symlink(symlinkTarget, resolvedOriginalPath);
} else {
await cp(fullTrashPath, resolvedOriginalPath, { recursive: true });
}
const restoreSucceeded = await safeStat(resolvedOriginalPath);
if (!restoreSucceeded.exists) {
throw new Error("Restore failed: destination not created");
}
try {
await rm(fullTrashPath, { recursive: true, force: true });
} catch (e) {
console.warn(`Failed to clean up trash: ${(e as Error).message}`);
}
return `Restored: ${
path.relative(context.directory, resolvedOriginalPath)
}`;
},
});
interface TrashEntry {
relativePath: string;
parsed: { path: string; timestamp: number };
kind: "file" | "directory" | "symlink";
}
async function collectTrashEntries(
trashDir: string,
): Promise<TrashEntry[]> {
const entries: TrashEntry[] = [];
async function walk(dir: string): Promise<void> {
try {
const items = await readdir(dir, { withFileTypes: true });
for (const item of items) {
const fullPath = path.join(dir, item.name);
const relativePath = path.relative(trashDir, fullPath);
const parsed = extractTimestamp(relativePath);
if (parsed) {
const kind = relativePath.endsWith(".symlink")
? "symlink"
: item.isDirectory()
? "directory"
: "file";
entries.push({
relativePath,
parsed,
kind,
});
} else if (item.isDirectory()) {
await walk(fullPath);
}
}
} catch (e) {
// Directory might not exist or be empty
if ((e as NodeJS.ErrnoException).code !== "ENOENT") {
throw e;
}
}
}
await walk(trashDir);
// Filter out entries whose original path has an ancestor that is also a trash entry
const entryPaths = new Set(entries.map((e) => e.parsed.path));
const validEntries = entries.filter((entry) => {
const parts = entry.parsed.path.split(path.sep);
for (let i = 1; i < parts.length; i++) {
if (entryPaths.has(parts.slice(0, i).join(path.sep))) return false;
}
return true;
});
// Sort by timestamp (newest first)
validEntries.sort((a, b) => b.parsed.timestamp - a.parsed.timestamp);
return validEntries;
}
function formatTimestamp(ts: number): string {
const date = new Date(ts);
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, "0");
const day = String(date.getDate()).padStart(2, "0");
const hours = String(date.getHours()).padStart(2, "0");
const minutes = String(date.getMinutes()).padStart(2, "0");
const seconds = String(date.getSeconds()).padStart(2, "0");
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}
export const history = tool({
description: "List all items currently in .trash/",
args: {},
async execute(_args, context) {
const trashDir = path.join(context.directory, TRASH_DIR);
const entries = await collectTrashEntries(trashDir);
if (entries.length === 0) {
return "Trash is empty.";
}
const lines: string[] = [];
lines.push(`${entries.length} item(s) in trash:`);
lines.push("");
for (let i = 0; i < entries.length; i++) {
const entry = entries[i]!;
const index = i + 1;
const name = entry.parsed.path.split("/").pop() || entry.parsed.path;
const type = entry.kind;
lines.push(` [${index}] ${name} (${type})`);
lines.push(` deleted: ${formatTimestamp(entry.parsed.timestamp)}`);
lines.push(` restore: ${entry.relativePath}`);
lines.push("");
}
return lines.join("\n").trimEnd();
},
});