forked from microsoft/devicescript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnippets.ts
More file actions
80 lines (69 loc) · 2.51 KB
/
Copy pathsnippets.ts
File metadata and controls
80 lines (69 loc) · 2.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import glob from "fast-glob"
import { ensureDir } from "fs-extra"
import { readFile, rm, writeFile } from "fs/promises"
import { resolve, dirname } from "path"
import { compileFile } from "./build"
import { log } from "./command"
export interface SnippetsOptions {
include: string
exclude?: string
}
const snipFolder = "devs/snippets"
export async function snippets(options: SnippetsOptions) {
const files = await glob(options.include, {
ignore: options.exclude ? [options.exclude] : [],
})
await rm(snipFolder, { recursive: true, force: true })
const pref = 'import * as ds from "@devicescript/core"'
const allImports: string[] = []
let imports = ""
let numsnip = 0
for (const fn of files) {
const md = await readFile(fn, "utf-8")
const snips: { line: number; snip: string }[] = []
md.replace(
/```(.*)\n([^]*?)```/g,
(full: string, optline: string, snip: string) => {
const line =
md.slice(0, md.indexOf(full)).replace(/[^\n]/g, "").length +
2
const opts = optline.split(/\s+/).filter(Boolean)
if (
!opts.includes("skip") &&
opts[0] == "ts" &&
!optline.includes("/sim/")
) {
if (!snip.includes(pref)) snip = pref + "\n" + snip
snip = `// ${fn}(${line})\n` + snip
snips.push({ line, snip })
}
return ""
}
)
for (const { line, snip } of snips) {
const bn = fn.replace(/\.\w+$/, "")
const mod = bn.replace(/\\/g, "/") + "_" + line
const fullname = resolve(snipFolder, mod + ".ts")
await ensureDir(dirname(fullname))
await writeFile(fullname, snip)
imports += `import "./${mod}"\n`
numsnip++
if (numsnip % 150 == 0) {
allImports.push(imports)
imports = ""
}
}
}
if (imports) allImports.push(imports)
for (let i = 0; i < allImports.length; ++i) {
const idx = resolve(snipFolder, `index${i}.ts`)
log(`compile ${idx}`)
await writeFile(idx, allImports[i])
const res = await compileFile(idx, {
ignoreMissingConfig: true,
flag: { allFunctions: true, allPrototypes: true },
})
if (!res.success) process.exit(1)
}
log(`${numsnip} snippets OK!`)
}