/
update.js
103 lines (92 loc) · 2.29 KB
/
update.js
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
93
94
95
96
97
98
99
100
101
102
103
const fs = require(`fs-extra`)
const path = require(`path`)
const yargs = require(`yargs`)
const { getHistory, writeHistory } = require(`./history`)
const args = yargs
.option(`file`, {
demand: true,
type: `string`,
})
.option(`replacements`, {
default: [],
type: `array`,
})
.option(`exact`, {
default: false,
type: `boolean`,
})
.option(`delete`, {
default: false,
type: `boolean`,
})
.option(`fileContent`, {
default: JSON.stringify(
`
import * as React from 'react';
import Layout from '../components/layout';
export default function SomeComponent() {
return (
<Layout>
<h1 data-testid="message">Hello %REPLACEMENT%</h1>
</Layout>
)
}
`
).trim(),
type: `string`,
})
.option(`fileSource`, {
type: `string`,
})
.option(`restore`, {
default: false,
type: `boolean`,
}).argv
async function update() {
const history = await getHistory()
const { file: fileArg, replacements, restore } = args
const filePath = path.resolve(fileArg)
if (restore) {
const original = history.get(filePath)
if (original) {
await fs.writeFile(filePath, original, `utf-8`)
} else if (original === false) {
await fs.remove(filePath)
} else {
console.log(`Didn't make changes to "${fileArg}". Nothing to restore.`)
}
history.delete(filePath)
return
}
let exists = true
if (!fs.existsSync(filePath)) {
exists = false
let fileContent
if (args.fileSource) {
fileContent = await fs.readFile(args.fileSource, `utf8`)
} else if (args.fileContent) {
fileContent = JSON.parse(args.fileContent).replace(/\+n/g, `\n`)
}
await fs.writeFile(filePath, fileContent, `utf8`)
}
const file = await fs.readFile(filePath, `utf8`)
if (!history.has(filePath)) {
history.set(filePath, exists ? file : false)
}
if (args.delete) {
if (exists) {
await fs.remove(filePath)
}
} else {
const contents = replacements.reduce((replaced, pair) => {
const [key, value] = pair.split(`:`)
return replaced.replace(
args.exact ? key : new RegExp(`%${key}%`, `g`),
value
)
}, file)
await fs.writeFile(filePath, contents, `utf8`)
}
await writeHistory(history)
}
update()