diff --git a/src/fs/restore.js b/src/fs/restore.js index 96ae1ffb..3e6760b0 100644 --- a/src/fs/restore.js +++ b/src/fs/restore.js @@ -1,8 +1,37 @@ +import fs from "node:fs/promises"; +import path from "node:path"; + const restore = async () => { - // Write your code here - // Read snapshot.json - // Treat snapshot.rootPath as metadata only - // Recreate directory/file structure in workspace_restored + const restoredFolder = "workspace_restored"; + const snapshotFile = "snapshot.json"; + + try { + const data = await fs.readFile(snapshotFile, "utf-8").catch(() => { + throw new Error("Snapshot file not found"); + }); + + await fs.mkdir(restoredFolder).catch((err) => { + if (err.code === "EEXIST") { + throw new Error("Folder already exists"); + } + throw err; + }); + + const { entries } = JSON.parse(data); + + for (const entry of entries) { + const fullPath = path.join(restoredFolder, entry.path); + + if (entry.type === "directory") { + await fs.mkdir(fullPath, { recursive: true }); + } else { + await fs.mkdir(path.dirname(fullPath), { recursive: true }); + await fs.writeFile(fullPath, entry.content, "base64"); + } + } + } catch (err) { + console.error("FS operation failed:", err.message); + } }; -await restore(); +await restore(); \ No newline at end of file diff --git a/src/fs/snapshot.js b/src/fs/snapshot.js index 050103d3..c62b7469 100644 --- a/src/fs/snapshot.js +++ b/src/fs/snapshot.js @@ -1,9 +1,38 @@ +import fs from "node:fs/promises"; +import path from "node:path"; + const snapshot = async () => { - // Write your code here - // Recursively scan workspace directory - // Write snapshot.json with: - // - rootPath: absolute path to workspace - // - entries: flat array of relative paths and metadata + const root = process.cwd(); + const restoredFolder = "workspace_restored"; + + try { + const files = await fs.readdir(root, { recursive: true, withFileTypes: true }); + + const entries = await Promise.all(files + .filter(file => !file.name.includes(restoredFolder)) + .map(async (file) => { + const fullPath = path.join(file.parentPath, file.name); + const isFile = file.isFile(); + const relPath = path.relative(root, fullPath); + + let extra = {}; + if (isFile) { + const { size } = await fs.stat(fullPath); + const content = await fs.readFile(fullPath); + extra = { size, content: content.toString("base64") }; + } + + return { path: relPath, type: isFile ? "file" : "directory", ...extra }; + }) + ); + + await fs.writeFile( + "snapshot.json", + JSON.stringify({ rootPath: root, entries }, null, 2) + ); + } catch (err) { + console.error("snapshot failed:", err.message); + } }; -await snapshot(); +await snapshot(); \ No newline at end of file