-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfile-generator.ts
More file actions
58 lines (54 loc) · 1.51 KB
/
file-generator.ts
File metadata and controls
58 lines (54 loc) · 1.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import * as fs from 'fs'
import * as path from 'path'
/**
* Creates dirs and files on disk at the given
* subroot based on the given file map.
*
* Paths are absolute, and made relative to `outDir`.
*
* * `opts?.parent` defaults to cwd
* * `opts?.dry` defaults to false
* * `opts?.dir` defaults to `"docs"`
*
* ```typescript
* import { generateFiles } from 'immaculata'
*
* generateFiles(new Map([
* ['/index.html', 'hello world'],
* ['/about.html', 'about my site'],
* ['/css/main.css', 'body{...}'],
* ]))
*
* // writefile: docs/index.html
* // writefile: docs/about.html
* // mkdir: docs/css
* // writefile: docs/css/main.css
* ```
*/
export function generateFiles(out: Map<string, { content: Buffer | string }>, opts?: {
parent?: string,
dry?: boolean,
dir?: string,
}) {
const dry = opts?.dry ?? false
const outDir = opts?.dir ?? 'docs'
const parent = opts?.parent ?? ''
const madeDirs = new Set<string>()
const mkdirIfNeeded = (dir: string) => {
if (madeDirs.has(dir)) return
madeDirs.add(dir)
console.log('mkdir ', dir)
if (!dry) fs.mkdirSync(dir)
}
for (const [filepath, { content }] of out) {
const relfile = path.join(outDir, filepath)
const parts = relfile.split(path.sep)
for (let i = 1; i < parts.length; i++) {
const dir = path.join(parent, ...parts.slice(0, i))
mkdirIfNeeded(dir)
}
const absfile = path.join(parent, relfile)
console.log('writefile', absfile)
if (!dry) fs.writeFileSync(absfile, content)
}
}