1 | const path = require('path')
|
2 | const makeDir = require('make-dir')
|
3 | const fs = require('fs')
|
4 | const writeFileAtomic = require('write-file-atomic')
|
5 | const dotProp = require('dot-prop')
|
6 |
|
7 | const statePath = path.join('.netlify', 'state.json')
|
8 | const permissionError = "You don't have access to this file."
|
9 |
|
10 | class StateConfig {
|
11 | constructor(projectRoot) {
|
12 | this.root = projectRoot
|
13 | this.path = path.join(projectRoot, statePath)
|
14 | }
|
15 |
|
16 | get all() {
|
17 | try {
|
18 | return JSON.parse(fs.readFileSync(this.path, 'utf8'))
|
19 | } catch (err) {
|
20 |
|
21 | if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
|
22 | return {}
|
23 | }
|
24 |
|
25 |
|
26 | if (err.code === 'EACCES') {
|
27 | err.message = `${err.message}\n${permissionError}\n`
|
28 | }
|
29 |
|
30 |
|
31 | if (err.name === 'SyntaxError') {
|
32 | writeFileAtomic.sync(this.path, '')
|
33 | return {}
|
34 | }
|
35 |
|
36 | throw err
|
37 | }
|
38 | }
|
39 |
|
40 | set all(val) {
|
41 | try {
|
42 |
|
43 | makeDir.sync(path.dirname(this.path))
|
44 | writeFileAtomic.sync(this.path, JSON.stringify(val, null, '\t'))
|
45 | } catch (err) {
|
46 |
|
47 | if (err.code === 'EACCES') {
|
48 | err.message = `${err.message}\n${permissionError}\n`
|
49 | }
|
50 |
|
51 | throw err
|
52 | }
|
53 | }
|
54 |
|
55 | get size() {
|
56 | return Object.keys(this.all || {}).length
|
57 | }
|
58 |
|
59 | get(key) {
|
60 | if (key === 'siteId' && process.env.NETLIFY_SITE_ID) {
|
61 |
|
62 | return process.env.NETLIFY_SITE_ID
|
63 | }
|
64 | return dotProp.get(this.all, key)
|
65 | }
|
66 |
|
67 | set(key, val) {
|
68 | const config = this.all
|
69 |
|
70 | if (arguments.length === 1) {
|
71 | for (const k of Object.keys(key)) {
|
72 | dotProp.set(config, k, key[k])
|
73 | }
|
74 | } else {
|
75 | dotProp.set(config, key, val)
|
76 | }
|
77 |
|
78 | this.all = config
|
79 | }
|
80 |
|
81 | has(key) {
|
82 | return dotProp.has(this.all, key)
|
83 | }
|
84 |
|
85 | delete(key) {
|
86 | const config = this.all
|
87 | dotProp.delete(config, key)
|
88 | this.all = config
|
89 | }
|
90 |
|
91 | clear() {
|
92 | this.all = {}
|
93 | }
|
94 | }
|
95 |
|
96 | module.exports = StateConfig
|