UNPKG

1.78 kBJavaScriptView Raw
1'use strict';
2
3// Node.js built-ins
4
5const path = require('path');
6
7// foreign modules
8
9const findUp = require('find-up');
10
11// local modules
12
13const CONFIG_FILE = require('./values').CONFIG_FILE;
14const isURL = require('./utils/url').isURL;
15const jsonUtils = require('./utils/json');
16
17// this module
18
19function 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
30module.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 // not found, so assume we want to make one in cwd
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};