UNPKG

3.34 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3const tslib_1 = require("tslib");
4const path = tslib_1.__importStar(require("path"));
5const deps_1 = tslib_1.__importDefault(require("./deps"));
6class UserConfig {
7 constructor(config) {
8 this.config = config;
9 this.needsSave = false;
10 }
11 get install() {
12 return this.body.install || this.genInstall();
13 }
14 set install(install) {
15 this.body.install = install;
16 this.needsSave = true;
17 }
18 get skipAnalytics() {
19 if (this.config.scopedEnvVar('SKIP_ANALYTICS') === '1')
20 return true;
21 if (typeof this.body.skipAnalytics !== 'boolean') {
22 this.body.skipAnalytics = false;
23 this.needsSave = true;
24 }
25 return this.body.skipAnalytics;
26 }
27 async init() {
28 await this.saving;
29 if (this._init)
30 return this._init;
31 return (this._init = (async () => {
32 this.debug('init');
33 this.body = (await this.read()) || { schema: 1 };
34 if (!this.body.schema) {
35 this.body.schema = 1;
36 this.needsSave = true;
37 }
38 else if (this.body.schema !== 1)
39 this.body = { schema: 1 };
40 // tslint:disable-next-line
41 this.install;
42 // tslint:disable-next-line
43 this.skipAnalytics;
44 if (this.needsSave)
45 await this.save();
46 })());
47 }
48 get debug() {
49 return require('debug')('heroku:user_config');
50 }
51 get file() {
52 return path.join(this.config.dataDir, 'config.json');
53 }
54 async save() {
55 if (!this.needsSave)
56 return;
57 this.needsSave = false;
58 this.saving = (async () => {
59 this.debug('saving');
60 if (!await this.canWrite()) {
61 throw new Error('file modified, cannot save');
62 }
63 await deps_1.default.file.outputJSON(this.file, this.body);
64 })();
65 }
66 async read() {
67 await this.migrate();
68 try {
69 this.mtime = await this.getLastUpdated();
70 let body = await deps_1.default.file.readJSON(this.file);
71 return body;
72 }
73 catch (err) {
74 if (err.code !== 'ENOENT')
75 throw err;
76 this.debug('not found');
77 }
78 }
79 async migrate() {
80 if (await deps_1.default.file.exists(this.file))
81 return;
82 let old = path.join(this.config.configDir, 'config.json');
83 if (!await deps_1.default.file.exists(old))
84 return;
85 this.debug('moving config into new place');
86 await deps_1.default.file.rename(old, this.file);
87 }
88 async canWrite() {
89 if (!this.mtime)
90 return true;
91 return (await this.getLastUpdated()) === this.mtime;
92 }
93 async getLastUpdated() {
94 try {
95 const stat = await deps_1.default.file.stat(this.file);
96 return stat.mtime.getTime();
97 }
98 catch (err) {
99 if (err.code !== 'ENOENT')
100 throw err;
101 }
102 }
103 genInstall() {
104 const uuid = require('uuid/v4');
105 this.install = uuid();
106 return this.install;
107 }
108}
109exports.default = UserConfig;