1 import {
2 constants,
3 type Dirent,
4 type MakeDirectoryOptions,
5 promises,
6 type RmOptions,
7 type StatOptions,
8 type WriteFileOptions,
9 } from "fs"
10 import { dirname, join } from "path"
11 import { readDirRecursive } from "./read-dir-recursive"
12
13 const { rm, stat, mkdir, access, readFile, writeFile } = promises
14
15 export type JSONFileOptions = WriteFileOptions & {
16 spaces?: number | string
17 replacer?: (this: any, key: string, value: any) => any
18 }
19
20 /**
21 * File system abstraction to create and cleanup files during
22 * tests
23 */
24 export class FileSystem {
25 constructor(public basePath: string) {}
26
27 private makePath(filePath: string) {
28 return join(this.basePath, filePath)
29 }
30
31 /**
32 * Cleanup directory
33 */
34 async cleanup(options?: RmOptions) {
35 return await rm(this.basePath, {
36 recursive: true,
37 maxRetries: 10,
38 force: true,
39 ...options,
40 })
41 }
42
43 /**
44 * Creates a directory inside the root of the filesystem
45 * path. You may use this method to create nested
46 * directories as well.
47 */
48 mkdir(dirPath: string, options?: MakeDirectoryOptions) {
49 return mkdir(this.makePath(dirPath), { recursive: true, ...options })
50 }
51
52 /**
53 * Create a new file
54 */
55 async create(filePath: string, contents: string, options?: WriteFileOptions) {
56 const absolutePath = this.makePath(filePath)
57 await mkdir(dirname(absolutePath), { recursive: true })
58 return writeFile(this.makePath(filePath), contents, options)
59 }
60
61 /**
62 * Remove a file
63 */
64 async remove(filePath: string, options?: RmOptions) {
65 return await rm(this.makePath(filePath), {
66 recursive: true,
67 force: true,
68 maxRetries: 2,
69 ...options,
70 })
71 }
72
73 /**
74 * Check if the root of the filesystem exists
75 */
76 async rootExists() {
77 try {
78 await access(this.basePath, constants.F_OK)
79 return true
80 } catch (error) {
81 if (error.code === "ENOENT") {
82 return false
83 }
84 throw error
85 }
86 }
87
88 /**
89 * Check if a file exists
90 */
91 async exists(filePath: string) {
92 try {
93 await access(this.makePath(filePath), constants.F_OK)
94 return true
95 } catch (error) {
96 if (error.code === "ENOENT") {
97 return false
98 }
99 throw error
100 }
101 }
102
103 /**
104 * Returns file contents
105 */
106 async contents(filePath: string) {
107 return await readFile(this.makePath(filePath), "utf-8")
108 }
109
110 /**
111 * Dumps file contents to the stdout
112 */
113 async dump(filePath: string) {
114 console.log("------------------------------------------------------------")
115 console.log(`file path => "${filePath}"`)
116 console.log(`contents => "${await this.contents(filePath)}"`)
117 }
118
119 /**
120 * Returns stats for a file
121 */
122 async stats(filePath: string, options?: StatOptions) {
123 return stat(this.makePath(filePath), options)
124 }
125
126 /**
127 * Recursively reads files from a given directory
128 */
129 readDir(dirPath?: string): Promise<Dirent[]> {
130 const location = dirPath ? this.makePath(dirPath) : this.basePath
131 return readDirRecursive(location)
132 }
133
134 /**
135 * Create a json file
136 */
137 async createJson(filePath: string, contents: any, options?: JSONFileOptions) {
138 if (options && typeof options === "object") {
139 const { replacer, spaces, ...rest } = options
140 return await this.create(
141 filePath,
142 JSON.stringify(contents, replacer, spaces),
143 rest
144 )
145 }
146
147 return await this.create(filePath, JSON.stringify(contents), options)
148 }
149
150 /**
151 * Read and parse a json file
152 */
153 async contentsJson(filePath: string) {
154 const contents = await readFile(this.makePath(filePath), "utf-8")
155 return JSON.parse(contents)
156 }
157 }