-
-
Notifications
You must be signed in to change notification settings - Fork 70
/
Copy pathutil.ts
92 lines (85 loc) · 2.33 KB
/
util.ts
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
81
82
83
84
85
86
87
88
89
90
91
92
import type Ajv from "ajv"
import * as glob from "glob"
import * as path from "path"
import * as fs from "fs"
import * as yaml from "js-yaml"
import * as JSON5 from "json5"
import {AnyValidateFunction} from "ajv/dist/core"
export function getFiles(args: string | string[]): string[] {
let files: string[] = []
if (Array.isArray(args)) args.forEach(_getFiles)
else _getFiles(args)
return files
function _getFiles(fileOrPattern: string): void {
if (glob.hasMagic(fileOrPattern)) {
const dataFiles = glob.sync(fileOrPattern, {cwd: process.cwd()})
files = files.concat(dataFiles)
} else {
files.push(fileOrPattern)
}
}
}
function getFormatFromFileName(filename: string): string {
return path.extname(filename).substr(1).toLowerCase()
}
function decodeFile(contents: string, format: string): any {
switch (format) {
case "json":
return JSON.parse(contents)
case "jsonc":
case "json5":
return JSON5.parse(contents)
case "yml":
case "yaml":
return yaml.safeLoad(contents, {schema: yaml.CORE_SCHEMA})
default:
throw new Error(`unsupported file format ${format}`)
}
}
export function openFile(filename: string, suffix: string): any {
let json = null
const file = path.resolve(process.cwd(), filename)
try {
try {
const format = getFormatFromFileName(filename)
json = decodeFile(fs.readFileSync(file).toString(), format)
} catch (e) {
json = require(file)
}
} catch (err) {
if (err instanceof Error) {
const msg: string = err.message
console.error(`error: ${msg.replace(" module", " " + suffix)}`)
}
process.exit(2)
}
return json
}
export function logJSON(mode: string, data: any, ajv?: Ajv): string {
switch (mode) {
case "json":
data = JSON.stringify(data, null, " ")
break
case "line":
data = JSON.stringify(data)
break
case "no":
data = ""
break
case "text":
if (ajv) data = ajv.errorsText(data)
}
return data
}
export function compile(ajv: Ajv, schemaFile: string): AnyValidateFunction {
const schema = openFile(schemaFile, "schema")
try {
return ajv.compile(schema)
} catch (err) {
if (err instanceof Error) {
console.error(`schema ${schemaFile} is invalid`)
console.error(`error: ${err.message}`)
}
process.exit(1)
}
}