Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 34 additions & 5 deletions src/fs/restore.js
Original file line number Diff line number Diff line change
@@ -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();
41 changes: 35 additions & 6 deletions src/fs/snapshot.js
Original file line number Diff line number Diff line change
@@ -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();