|
1 | 1 | const path = require('path'); |
2 | | -const {readJson, writeJson, pathExists} = require('fs-extra'); |
| 2 | +const parseJson = require('parse-json'); |
| 3 | +const detectIndent = require('detect-indent'); |
| 4 | +const detectNewline = require('detect-newline'); |
| 5 | +const {readFile, writeJson, pathExists} = require('fs-extra'); |
| 6 | + |
| 7 | +const DEFAULT_INDENT = 2; |
| 8 | +const DEFAULT_NEWLINE = '\n'; |
3 | 9 |
|
4 | 10 | module.exports = async (version, basePath, logger) => { |
5 | 11 | const packagePath = path.join(basePath, 'package.json'); |
6 | 12 | const shrinkwrapPath = path.join(basePath, 'npm-shrinkwrap.json'); |
7 | 13 | const packageLockPath = path.join(basePath, 'package-lock.json'); |
8 | | - const pkg = await readJson(packagePath); |
| 14 | + const pkg = await readFile(packagePath, 'utf8'); |
9 | 15 |
|
10 | | - await writeJson(packagePath, {...pkg, ...{version}}, {spaces: 2}); |
| 16 | + await writeJson(packagePath, {...parseJson(pkg), ...{version}}, getWriteOptions(pkg)); |
11 | 17 | logger.log('Wrote version %s to %s', version, packagePath); |
12 | 18 |
|
13 | 19 | if (await pathExists(shrinkwrapPath)) { |
14 | | - const shrinkwrap = await readJson(shrinkwrapPath); |
15 | | - await writeJson(shrinkwrapPath, {...shrinkwrap, ...{version}}, {spaces: 2}); |
| 20 | + const shrinkwrap = await readFile(shrinkwrapPath, 'utf8'); |
| 21 | + await writeJson(shrinkwrapPath, {...parseJson(shrinkwrap), ...{version}}, getWriteOptions(shrinkwrap)); |
16 | 22 | logger.log('Wrote version %s to %s', version, shrinkwrapPath); |
17 | 23 | } |
18 | 24 |
|
19 | 25 | if (await pathExists(packageLockPath)) { |
20 | | - const packageLock = await readJson(packageLockPath); |
21 | | - await writeJson(packageLockPath, {...packageLock, ...{version}}, {spaces: 2}); |
| 26 | + const packageLock = await readFile(packageLockPath, 'utf8'); |
| 27 | + await writeJson(packageLockPath, {...parseJson(packageLock), ...{version}}, getWriteOptions(packageLock)); |
22 | 28 | logger.log('Wrote version %s to %s', version, packageLockPath); |
23 | 29 | } |
24 | 30 | }; |
| 31 | + |
| 32 | +function getWriteOptions(content) { |
| 33 | + return {spaces: detectIndent(content).indent || DEFAULT_INDENT, EOL: detectNewline(content) || DEFAULT_NEWLINE}; |
| 34 | +} |
0 commit comments