1 | 'use strict';
|
2 |
|
3 |
|
4 |
|
5 | const path = require('path');
|
6 |
|
7 |
|
8 |
|
9 | const findUp = require('find-up');
|
10 |
|
11 |
|
12 |
|
13 | const CONFIG_FILE = require('./values').CONFIG_FILE;
|
14 | const isURL = require('./utils/url').isURL;
|
15 | const jsonUtils = require('./utils/json');
|
16 |
|
17 |
|
18 |
|
19 | function findConfig () {
|
20 | const cwd = process.env.BMP_WORKING_DIR || process.cwd();
|
21 | return findUp(CONFIG_FILE, { cwd })
|
22 | .then((filePath) => {
|
23 | if (!filePath) {
|
24 | return Promise.reject(new Error(`${CONFIG_FILE} not found`));
|
25 | }
|
26 | return filePath;
|
27 | });
|
28 | }
|
29 |
|
30 | module.exports = {
|
31 |
|
32 | CONFIG_FILE,
|
33 |
|
34 | read () {
|
35 | if (process.env.BMP_SCOPE) {
|
36 | if (!isURL(process.env.BMP_SCOPE)) {
|
37 | return Promise.reject(new TypeError(`"${process.env.BMP_SCOPE}" is not a valid URL`));
|
38 | }
|
39 | return Promise.resolve(process.env.BMP_SCOPE);
|
40 | }
|
41 |
|
42 | return findConfig()
|
43 | .then((filePath) => jsonUtils.loadJsonObject(filePath))
|
44 | .then((cfg) => {
|
45 | if (!cfg.bmp || !cfg.bmp.scope) {
|
46 | return Promise.reject(new Error(`bmp.scope not found in ${CONFIG_FILE}`));
|
47 | }
|
48 | return cfg.bmp.scope;
|
49 | });
|
50 | },
|
51 |
|
52 | write (options) {
|
53 | if (!isURL(options.scope)) {
|
54 | return Promise.reject(new TypeError(`"${options.scope}" is not a valid URL`));
|
55 | }
|
56 |
|
57 | let filePath;
|
58 | return findConfig()
|
59 | .catch(() => {
|
60 | const cwd = process.env.BMP_WORKING_DIR || process.cwd();
|
61 |
|
62 | return path.join(cwd, CONFIG_FILE);
|
63 | })
|
64 | .then((fp) => {
|
65 | filePath = fp;
|
66 | return jsonUtils.updateJson(filePath, (cfg) => {
|
67 | cfg.bmp = cfg.bmp || {};
|
68 | cfg.bmp.scope = options.scope;
|
69 | return cfg;
|
70 | });
|
71 | });
|
72 | }
|
73 |
|
74 | };
|