const deepSet = require('lodash.set');
const yaml = require('js-yaml');
const toFlat = require('./toFlat');

const parseJSON = content => JSON.parse(content);

const toJSON = content => JSON.stringify(content, null, 4);

const parseYAML = content => yaml.safeLoad(content);

const toYAML = (content) => {
    if (!content || Object.keys(content).length === 0) return '';

    return yaml.safeDump(content);
};

const parseFlat = (content) => {
    const body = {};
    const keys = Object.keys(content).sort();

    for (const key of keys) {
        deepSet(body, key, content[key]);
    }

    return body;
};

const toEnvVars = (flatContent) => {
    let source = '';

    for (const key of Object.keys(flatContent).sort()) {
        const value = flatContent[key];
        const envVar = key
            .replace('.', '_')
            .replace('[', '_')
            .replace(']', '')
            .toUpperCase();

        source += `export ${envVar}="${value}";\n`;
    }

    return source;
};

module.exports = {
    parseJSON,
    toJSON,
    parseYAML,
    toYAML,
    parseFlat,
    toEnvVars,
    toFlat,
};

@@ -717,24 +717,131 @@
 ).sort()) %7B%0A
+        // Replace each ' by '%22'%22' in the value%0A        // @see http://stackoverflow.com/a/1250279/3868326%0A
         cons
@@ -866,17 +866,42 @@
 ent%5Bkey%5D
-;
+.replace(%22'%22, %22'%5C%22'%5C%22'%22);%0A
 %0A       
@@ -1081,17 +1081,17 @@
 ar%7D=
-%22
+'
 $%7Bvalue%7D
 %22;%5Cn
@@ -1086,17 +1086,17 @@
 $%7Bvalue%7D
-%22
+'
 ;%5Cn%60;%0A  

Secure envvars format