all files / lib/ config.js

69.44% Statements 25/36
44.44% Branches 8/18
100% Functions 5/5
69.44% Lines 25/36
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 891×   1×   1×       1× 117×     1× 84× 84×                         1× 7× 117× 117×                           1× 42× 42×           42×       42× 42×           1× 84×   84× 84×                 84× 42×         1×            
const fs = require('fs'),
      os = require('os')
      s3 = require('./s3-helpers');
 
let configured = false,
    localConfig = {},
    remoteConfig = {};
 
function isConfigured() {
    return !!localConfig.rootBucket;
}
 
function _loadKartRc(path) {
    Eif (!path) {
        return Promise.resolve();
    }
 
    return new Promise((resolve, reject) => {
        fs.readFile(path, 'utf8', (err, data) => {
            if (!err) {
                Object.assign(localConfig, JSON.parse(data));
            }
            resolve();
        });
    });
}
 
function configGuard(func) {
    return (...args) => {
        Eif (isConfigured()) {
            return func.apply(this, args);
        } else {
            return configure({})
                .then(() => {
                    if (isConfigured()) {
                        return func.apply(this, args);
                    } else {
                        return Promise.reject('kart not configured properly');
                    }
                });
        }
    };
}
 
function _downloadRemoteConfig(root) {
    return new Promise((resolve, reject) => {
        s3.getInstance().getObject(
            {
                Bucket: root.name,
                Key: root.config || 'kart-projects.json'
            },
            (err, data) => {
                Iif (err) {
                    return reject('Unable to download remote config: ' + err);
                }
 
                Object.assign(remoteConfig, JSON.parse(data.Body.toString()));
                resolve();
            }
        );
    });
}
 
function configure(c, kartRcPath) {
    return _loadKartRc(kartRcPath)
        .then(() => {
            localConfig = Object.assign(localConfig, c);
            Iif (localConfig.awsKey && localConfig.awsSecret) {
                aws.config.update(
                    {
                        accessKeyId: localConfig.awsKey,
                        secretAccessKey: localConfig.awsSecret,
                    }
                );
            }
 
            if (localConfig.rootBucket) {
                return _downloadRemoteConfig(localConfig.rootBucket);
            }
        });
}
 
module.exports = {
    isConfigured,
    local: localConfig,
    remote: remoteConfig,
    configure,
    guard: configGuard
};