( root: string, fs: FileSystemAdapter = DEFAULT_FS, )
| 18 | |
| 19 | // eslint-disable-next-line max-lines-per-function |
| 20 | export function createTree( |
| 21 | root: string, |
| 22 | fs: FileSystemAdapter = DEFAULT_FS, |
| 23 | ): Tree { |
| 24 | const pending = new Map<string, PendingEntry>(); |
| 25 | const resolve = (filePath: string): string => path.resolve(root, filePath); |
| 26 | |
| 27 | return { |
| 28 | root, |
| 29 | |
| 30 | exists: async (filePath: string): Promise<boolean> => |
| 31 | pending.has(filePath) || fs.exists(resolve(filePath)), |
| 32 | |
| 33 | read: async (filePath: string): Promise<string | null> => { |
| 34 | const entry = pending.get(filePath); |
| 35 | if (entry) { |
| 36 | return entry.content; |
| 37 | } |
| 38 | const absolute = resolve(filePath); |
| 39 | if (!(await fs.exists(absolute))) { |
| 40 | return null; |
| 41 | } |
| 42 | return fs.readFile(absolute, 'utf8'); |
| 43 | }, |
| 44 | |
| 45 | write: async (filePath: string, content: string): Promise<void> => { |
| 46 | const entry = pending.get(filePath); |
| 47 | if (entry) { |
| 48 | if (entry.content !== content) { |
| 49 | pending.set(filePath, { ...entry, content }); |
| 50 | } |
| 51 | return; |
| 52 | } |
| 53 | const absolute = resolve(filePath); |
| 54 | const existing = await fs.readFile(absolute, 'utf8').catch(() => null); |
| 55 | if (existing === content) { |
| 56 | return; |
| 57 | } |
| 58 | pending.set(filePath, { |
| 59 | content, |
| 60 | type: existing == null ? 'CREATE' : 'UPDATE', |
| 61 | original: existing, |
| 62 | }); |
| 63 | }, |
| 64 | |
| 65 | listChanges: (): FileChange[] => |
| 66 | [...pending.entries()].map(([filePath, { content, type }]) => ({ |
| 67 | path: filePath, |
| 68 | type, |
| 69 | content, |
| 70 | })), |
| 71 | |
| 72 | async flush(): Promise<void> { |
| 73 | const written = new Set<string>(); |
| 74 | try { |
| 75 | await [...pending.entries()].reduce<Promise<null>>( |
| 76 | async (acc, [filePath, { content }]) => { |
| 77 | await acc; |
no test coverage detected