UNPKG

2.2 kBJavaScriptView Raw
1const path = require('path')
2const makeDir = require('make-dir')
3const fs = require('fs')
4const writeFileAtomic = require('write-file-atomic')
5const dotProp = require('dot-prop')
6
7const statePath = path.join('.netlify', 'state.json')
8const permissionError = "You don't have access to this file."
9
10class 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 // Don't create if it doesn't exist
21 if (err.code === 'ENOENT' || err.code === 'ENOTDIR') {
22 return {}
23 }
24
25 // Improve the message of permission errors
26 if (err.code === 'EACCES') {
27 err.message = `${err.message}\n${permissionError}\n`
28 }
29
30 // Empty the file if it encounters invalid JSON
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 // Make sure the folder exists as it could have been deleted in the meantime
43 makeDir.sync(path.dirname(this.path))
44 writeFileAtomic.sync(this.path, JSON.stringify(val, null, '\t'))
45 } catch (err) {
46 // Improve the message of permission errors
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 // TODO figure out cleaner way of grabbing ENV vars
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
96module.exports = StateConfig