UNPKG

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