-
Notifications
You must be signed in to change notification settings - Fork 13
/
index.js
73 lines (61 loc) · 1.4 KB
/
index.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
/**
* @module packageEditor
* @exports {Function} read
* @exports {Function} write
* @exports {Function} reset
*
*/
const assign = require('@recursive/assign');
const {
writeFile,
readFile,
jsonCopy,
packageData,
} = require('./utils');
let _original;
let _suffix;
const original = async () => _original = _original || jsonCopy(await packageData()); // eslint-disable-line require-atomic-updates
const suffix = async () => {
if (typeof _suffix !== 'string') {
const contents = await readFile('package.json');
_suffix = contents.toString().endsWith('\n') ? '\n' : ''; // eslint-disable-line require-atomic-updates
}
return _suffix;
};
/**
* Read package
* @return {Object}
*
* @example
* await packageEditor.read()
*/
module.exports.read = async () => await packageData();
/**
* Edit the package file
* @param {Object} data
* @return {Object}
*
* @example
* await packageEditor.write({name: 'NOT_THE_PACKAGE_NAME'});
*/
module.exports.write = async data => {
await original(); // make sure original is stored
const json = assign(
{},
await module.exports.read(),
data,
);
await writeFile(
'package.json',
JSON.stringify(json, null, 2) + await suffix(),
);
return json;
};
/**
* Reset to the original package.json
* @return {Objecy}
*/
module.exports.reset = async () => await writeFile(
'package.json',
JSON.stringify(await original(), null, 2) + await suffix(),
);