Changes
2 changed files (+121/-0)
-
-
@@ -0,0 +1,57 @@// SPDX-FileCopyrightText: 2024 Shota FUJI <pockawoooh@gmail.com> // // SPDX-License-Identifier: Apache-2.0 import { assertEquals, assertExists, assertRejects, } from "../deps/deno.land/std/assert/mod.ts"; import { MemoryFsWriter } from "./memory_fs.ts"; import { validateTree } from "./validate_tree.ts"; Deno.test("Should prevents from writing file when there is a directory at the path", async () => { const writer = validateTree(new MemoryFsWriter()); const enc = new TextEncoder(); await writer.write(["foo", "bar.txt"], enc.encode("Foo\n")); await assertRejects(async () => await writer.write(["foo"], enc.encode("Bar\n")) ); }); Deno.test("Should prevents from writing directory when there is a file at the path", async () => { const writer = validateTree(new MemoryFsWriter()); const enc = new TextEncoder(); await writer.write(["foo"], enc.encode("Foo\n")); await assertRejects(async () => await writer.write(["foo", "bar.txt"], enc.encode("Bar\n")) ); }); Deno.test("Should not reject if there is no conflict", async () => { const memoryWriter = new MemoryFsWriter(); const writer = validateTree(memoryWriter); const enc = new TextEncoder(); await writer.write(["foo.txt"], enc.encode("Foo\n")); await writer.write(["foo", "bar.txt"], enc.encode("Bar\n")); const dec = new TextDecoder(); const foo = memoryWriter.get(["foo.txt"]); assertExists(foo); const bar = memoryWriter.get(["foo", "bar.txt"]); assertExists(bar); assertEquals(dec.decode(foo), "Foo\n"); assertEquals(dec.decode(bar), "Bar\n"); });
-
-
-
@@ -0,0 +1,64 @@// SPDX-FileCopyrightText: 2024 Shota FUJI <pockawoooh@gmail.com> // // SPDX-License-Identifier: Apache-2.0 import type { FileSystemWriter } from "./interface.ts"; const enum NodeType { File, Directory, } function nodeTypeToString(nodeType: NodeType): string { switch (nodeType) { case NodeType.File: return "file"; case NodeType.Directory: return "directory"; } } const SEP = "/"; /** * Wraps the given FileSystem Writer and returns a new FileSystem Writer * that checks tree structure so there won't be a directory and a file * having same name. */ export function validateTree(childWriter: FileSystemWriter): FileSystemWriter { const nodes = new Map<string, NodeType>(); return { write(path, content, opts) { setNodeTypeRecur(path, NodeType.File, nodes); return childWriter.write(path, content, opts); }, }; } function setNodeTypeRecur( path: readonly string[], nodeType: NodeType, map: Map<string, NodeType>, ): void { if (path.length === 0) { return; } const key = path.join(SEP); const found = map.get(key); if (typeof found !== "undefined" && found !== nodeType) { const ns = nodeTypeToString(nodeType); const fs = nodeTypeToString(found); throw new Error( `Attempt to write a ${ns} at "${key}", but there already is a ${fs}.`, ); } map.set(key, nodeType); return setNodeTypeRecur(path.slice(0, -1), NodeType.Directory, map); }
-