Skip to content

Commit

Permalink
CR
Browse files Browse the repository at this point in the history
  • Loading branch information
netalondon committed Oct 1, 2024
1 parent e7d6dc0 commit f5c0766
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 37 deletions.
37 changes: 37 additions & 0 deletions components/src/file_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,3 +42,40 @@ export function sortFiles(files: Stats[]) {
}
});
}

export async function cloneTree(
sourceFs: FileSystem,
targetFs: FileSystem,
dir = "/",
pathTransform: (path: string) => string,
overwrite = false,
) {
const sourceDir = dir == "/" ? "" : dir;
const targetDir = pathTransform(sourceDir);

const sourceItems = await sourceFs.scandir(dir);

targetFs.mkdir(targetDir);
const targetItems = new Set(
(await targetFs.scandir(targetDir)).map((stat) => stat.name),
);

for (const item of sourceItems) {
if (item.isFile()) {
if (overwrite || !targetItems.has(item.name)) {
await targetFs.writeFile(
`${targetDir}/${item.name}`,
await sourceFs.readFile(`${sourceDir}/${item.name}`),
);
}
} else {
await cloneTree(
sourceFs,
targetFs,
`${sourceDir}/${item.name}`,
pathTransform,
overwrite,
);
}
}
}
38 changes: 1 addition & 37 deletions components/src/stores/base.context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import {
useState,
} from "react";
import { useDialog } from "../dialog.js";
import { cloneTree } from "../file_utils.js";
import {
FileSystemAccessFileSystemAdapter,
openNand2TetrisDirectory,
Expand All @@ -21,43 +22,6 @@ import {
removeLocalAdapterFromIndexedDB,
} from "./base/indexDb.js";

async function cloneTree(
sourceFs: FileSystem,
targetFs: FileSystem,
dir = "/",
pathTransform: (path: string) => string,
overwrite = false,
) {
const sourceDir = dir == "/" ? "" : dir;
const targetDir = pathTransform(sourceDir);

const sourceItems = await sourceFs.scandir(dir);

targetFs.mkdir(targetDir);
const targetItems = new Set(
(await targetFs.scandir(targetDir)).map((stat) => stat.name),
);

for (const item of sourceItems) {
if (item.isFile()) {
if (overwrite || !targetItems.has(item.name)) {
await targetFs.writeFile(
`${targetDir}/${item.name}`,
await sourceFs.readFile(`${sourceDir}/${item.name}`),
);
}
} else {
await cloneTree(
sourceFs,
targetFs,
`${sourceDir}/${item.name}`,
pathTransform,
overwrite,
);
}
}
}

export interface BaseContext {
fs: FileSystem;
localFsRoot?: string;
Expand Down

0 comments on commit f5c0766

Please sign in to comment.