|
| 1 | +import * as fs from "fs"; |
| 2 | +import path from "path"; |
| 3 | +import { treeStringToJson } from "./tree"; |
| 4 | +import isNondot from "@structure-codes/is-nondot"; |
| 5 | + |
| 6 | +const pathExists = (filepath: string) => { |
| 7 | + try { |
| 8 | + fs.accessSync(filepath); |
| 9 | + return true; |
| 10 | + } catch { |
| 11 | + return false; |
| 12 | + } |
| 13 | +}; |
| 14 | + |
| 15 | +const getPaths = (tree: any) => { |
| 16 | + type Path = { |
| 17 | + filepath: string; |
| 18 | + type: "file" | "dir"; |
| 19 | + }; |
| 20 | + const paths: Array<Path> = []; |
| 21 | + const searchTree = (tree: any, filepath: Array<string>) => { |
| 22 | + const branches = Object.keys(tree); |
| 23 | + if (branches.length === 0) { |
| 24 | + const leafName = filepath[filepath.length - 1]; |
| 25 | + const type = leafName.includes(".") || isNondot(leafName) |
| 26 | + ? "file" |
| 27 | + : "dir"; |
| 28 | + const currentPath = filepath.join("/"); |
| 29 | + |
| 30 | + return paths.push({ filepath: currentPath, type }); |
| 31 | + } |
| 32 | + branches.forEach((branch) => { |
| 33 | + const newPath = [...filepath]; |
| 34 | + newPath.push(branch); |
| 35 | + searchTree(tree[branch], newPath); |
| 36 | + }); |
| 37 | + }; |
| 38 | + searchTree(tree, []); |
| 39 | + return paths; |
| 40 | +}; |
| 41 | + |
| 42 | +export const buildStructure = (file, outputDir) => { |
| 43 | + try { |
| 44 | + const data = fs.readFileSync(file); |
| 45 | + const tree = treeStringToJson(data.toString()); |
| 46 | + const paths = getPaths(tree); |
| 47 | + const outputDirExists = pathExists(outputDir); |
| 48 | + if (!outputDirExists) { |
| 49 | + console.log("Creating target directory:", outputDir); |
| 50 | + fs.mkdirSync(outputDir, { recursive: true }); |
| 51 | + } |
| 52 | + paths.forEach(({ filepath, type }: any) => { |
| 53 | + const fullPath = outputDir + "/" + filepath.replace(/\/+/g, "/"); |
| 54 | + if (pathExists(fullPath)) { |
| 55 | + console.warn("Path already exists:", fullPath); |
| 56 | + return; |
| 57 | + } |
| 58 | + if (type === "dir") { |
| 59 | + console.log("Creating directory:", fullPath); |
| 60 | + fs.mkdirSync(fullPath, { recursive: true }); |
| 61 | + } else { |
| 62 | + const dirname = path.dirname(fullPath); |
| 63 | + const exist = pathExists(dirname); |
| 64 | + if (!exist) { |
| 65 | + console.log("Creating directory:", dirname); |
| 66 | + fs.mkdirSync(dirname, { recursive: true }); |
| 67 | + } |
| 68 | + console.log("Creating file:", fullPath); |
| 69 | + fs.writeFileSync(fullPath, "", { flag: "wx" }); |
| 70 | + } |
| 71 | + }); |
| 72 | + } catch (e: any) { |
| 73 | + console.error(e.message); |
| 74 | + } |
| 75 | +}; |
0 commit comments