1
1
const { existsSync, lstatSync, readFileSync } = require ( "fs" ) ;
2
2
3
3
/**
4
- * Get the parsed contents of a package.json manifest file .
4
+ * Read the content of target package.json if exists .
5
5
*
6
- * @param {string } path The path to the package.json manifest file.
7
- * @returns {object } The manifest file's contents.
6
+ * @param {string } path file path
7
+ * @returns {string } file content
8
8
*
9
9
* @internal
10
10
*/
11
- function getManifest ( path ) {
11
+ function readManifest ( path ) {
12
12
// Check it exists.
13
13
if ( ! existsSync ( path ) ) throw new ReferenceError ( `package.json file not found: "${ path } "` ) ;
14
14
@@ -25,13 +25,41 @@ function getManifest(path) {
25
25
if ( ! stat . isFile ( ) ) throw new ReferenceError ( `package.json is not a file: "${ path } "` ) ;
26
26
27
27
// Read the file.
28
- let contents ;
29
28
try {
30
- contents = readFileSync ( path , "utf8" ) ;
29
+ return readFileSync ( path , "utf8" ) ;
31
30
} catch ( _ ) {
32
31
// istanbul ignore next (hard to test — happens if no read access etc).
33
32
throw new ReferenceError ( `package.json cannot be read: "${ path } "` ) ;
34
33
}
34
+ }
35
+
36
+ /**
37
+ * Extract the current indent sequence from file.
38
+ *
39
+ * @param {string } path The path to the package.json manifest file.
40
+ * @returns {string } indent symbols
41
+ *
42
+ * @internal
43
+ */
44
+ function getIndent ( path ) {
45
+ // Read the file.
46
+ const contents = readManifest ( path ) ;
47
+ const match = / \n ( [ ^ " ] + ) / . exec ( contents ) ;
48
+
49
+ return match ? match [ 1 ] : 2 ;
50
+ }
51
+
52
+ /**
53
+ * Get the parsed contents of a package.json manifest file.
54
+ *
55
+ * @param {string } path The path to the package.json manifest file.
56
+ * @returns {object } The manifest file's contents.
57
+ *
58
+ * @internal
59
+ */
60
+ function getManifest ( path ) {
61
+ // Read the file.
62
+ const contents = readManifest ( path ) ;
35
63
36
64
// Parse the file.
37
65
let manifest ;
@@ -65,4 +93,4 @@ function getManifest(path) {
65
93
}
66
94
67
95
// Exports.
68
- module . exports = getManifest ;
96
+ module . exports = { getManifest, getIndent } ;
0 commit comments