Пример #1
0
 fs.stat('.env', (err, stat) => {
   if (err === null) {
     console.log("*Found .env file; incorporating user auth data into specs.*");
     console.log("NOTE: if your user is not Premium with R-18 enabled some specs will fail.");
     const dotenv = require('dotenv')
     const envConfig = dotenv.parse(fs.readFileSync('.env'))
     for (var k in envConfig) {
       process.env[k] = envConfig[k]
     }
     let output = `
       let user_info = {
         auth_user: '******',
         email: '${process.env.EMAIL}',
         password: '******',
         auth_token: '${process.env.AUTH_TOKEN}'
       };
       let premium_user_info = {
         auth_user: '******',
         auth_token: '${process.env.AUTH_TOKEN}'
       };
     `;
     fs.ensureFileSync('tmp/authinfo.js');
     fs.writeFileSync('tmp/authinfo.js', output);
   } else {
     console.log("*.env file not found; only some specs will run.*");
     console.log("Check the '.env' secion in README.md for details on how to set .env");
     fs.ensureFileSync('tmp/authinfo.js');
     fs.writeFileSync('tmp/authinfo.js', '');
   }
 });
Пример #2
0
Lambda.prototype._setEnvironmentVars = function (program, codeDirectory) {
  console.log('=> Setting "environment variables" for Lambda from %s', program.configFile);
  // Which file is the handler?
  var handlerFileName = codeDirectory + '/' + program.handler.split('.').shift() + '.js';
  var contents = fs.readFileSync(handlerFileName);

  var configValues = fs.readFileSync(program.configFile);
  var prefix = '////////////////////////////////////\n// "Environment Variables"\n';
  var config = dotenv.parse(configValues);
  var contentStr = contents.toString();

  for (var k in config) {
    if (!config.hasOwnProperty(k)) {
      continue;
    }

    // Use JSON.stringify to ensure that it's valid code.
    prefix += 'process.env["' + k + '"]=' + JSON.stringify(config[k]) + ';\n';
  }
  prefix += '////////////////////////////////////\n\n';

  // If the first line of the file is 'use strict', append after
  if (contentStr.trim().indexOf('use strict') === 1) {
    contentStr = contentStr.replace(/([`'"]use strict[`'"][;]?)/, '$1\n' + prefix);
  } else {
    contentStr = prefix + contentStr;
  }

  fs.writeFileSync(handlerFileName, contentStr);
};
Пример #3
0
module.exports = function() {

  if (!fs.existsSync(userhome(".npm-diplomat"))) {
    fs.writeFileSync(userhome(".npm-diplomat"), "GMAIL_PASSWORD=???\nNPM_EMPLOYEE_USERNAME=???")
    console.log(
      "Created default config. Please go fill in the blanks.",
      "\n\n$EDITOR " + userhome(".npm-diplomat")
    )
    process.exit(1);
  } else {
    var config = dotenv.parse(fs.readFileSync(userhome(".npm-diplomat")));
    Object.keys(config).forEach(function(key){
      process.env[key] = config[key]
    })

    if (!process.env.GMAIL_PASSWORD || process.env.GMAIL_PASSWORD === "???") {
      console.log("Please specify GMAIL_PASSWORD in " + userhome(".npm-diplomat"))
      process.exit(1);
    }

    if (!process.env.NPM_EMPLOYEE_USERNAME || process.env.NPM_EMPLOYEE_USERNAME === "???") {
      console.log("Please specify NPM_EMPLOYEE_USERNAME in " + userhome(".npm-diplomat"))
      process.exit(1);
    }
  }

}
Пример #4
0
Lambda.prototype._params = function (program, buffer) {
  var params = {
    FunctionName: program.functionName +
      (program.environment ? '-' + program.environment : '') +
      (program.lambdaVersion ? '-' + program.lambdaVersion : ''),
    Code: {
      ZipFile: buffer
    },
    Handler: program.handler,
    Role: program.role,
    Runtime: program.runtime,
    Description: program.description,
    MemorySize: program.memorySize,
    Timeout: program.timeout,
    Publish: program.publish,
    VpcConfig: {
      SubnetIds: [],
      SecurityGroupIds: []
    },
    Environment: {
      Variables: null
    },
    DeadLetterConfig: {
      TargetArn: null
    },
    TracingConfig: {
      Mode: null
    }
  }

  // Escape characters that is not allowed by AWS Lambda
  params.FunctionName = params.FunctionName.replace(/[^a-zA-Z0-9-_]/g, '_')

  if (program.vpcSubnets && program.vpcSecurityGroups) {
    params.VpcConfig = {
      'SubnetIds': program.vpcSubnets.split(','),
      'SecurityGroupIds': program.vpcSecurityGroups.split(',')
    }
  }
  if (program.configFile) {
    var configValues = fs.readFileSync(program.configFile)
    var config = dotenv.parse(configValues)
    // If `configFile` is an empty file, `config` value will be `{}`
    params.Environment = {
      Variables: config
    }
  }
  if (program.deadLetterConfigTargetArn !== undefined) {
    params.DeadLetterConfig = {
      TargetArn: program.deadLetterConfigTargetArn
    }
  }
  if (program.tracingConfig) {
    params.TracingConfig.Mode = program.tracingConfig
  }

  return params
}
Пример #5
0
    get: function () {
        var dotenv = require('dotenv'),
            fs = require('fs'),
            node_env = (typeof process.env.NODE_ENV === "undefined") ? "development" : process.env.NODE_ENV,
            file = fs.readFileSync(__dirname + "/../config/env/" + node_env + ".env"),
            env = dotenv.parse(file);

        return env;
    }
Пример #6
0
      fs.readFile(path.join(home, '.optk'), function(err, buf) {
        // if the file doesn't exist or we cannot read it, just return nothing in callback
        if (err) {
          return cb({});
        }

        var options = dotenv.parse(buf);

        cb(_.pick(options, 'key', 'secret'));
      });
Пример #7
0
 const load = path => {
   if (existsSync(path)) {
     debug(`load env from ${path}`);
     const parsed = parse(readFileSync(path, 'utf-8'));
     Object.keys(parsed).forEach(key => {
       if (!process.env.hasOwnProperty(key)) {
         process.env[key] = parsed[key];
       }
     });
   }
 };
Пример #8
0
      test('with specified config values', () => {
        const env = slateEnv.getEmptySlateEnv();
        const store = 'test-shop.myshopify.com';

        env[config.envStoreVar] = store;
        slateEnv.create({values: env});

        const envParsed = dotenv.parse(fs.readFileSync(envPath, 'utf8'));

        expect(envParsed).toHaveProperty(config.envStoreVar, store);
      });
Пример #9
0
function loadEnvVar() {
  const enviroment = process.env.NODE_ENV || "development";

  if (enviroment !== "production") {
    dotenv.config();
  }

  if (fs.existsSync(".env.local")) {
    override(dotenv.parse(fs.readFileSync(".env.local")));
  }
}
Пример #10
0
function loadEnvironmentFile(path, encoding, silent) {
    try {
        var data = fs.readFileSync(path, encoding);
        return dotenv.parse(data);
    } catch (err) {
        if (!silent) {
            console.error(err.message);
        }
        return {};
    }
}
Пример #11
0
function appConfig () {
    var config = {};
    try {
        const env = fs.readFileSync(".env-cordova");
        config = dotenv.parse(env);
    } catch (ignore) {
        console.log("Failed to read configuration from file `.env`");
    }
    const code = `window.APP_CONFIG = ${JSON.stringify(config, null, 4)};`;
    fs.writeFileSync("build/app-config.js", code);
}
Пример #12
0
      test('with empty config values', () => {
        slateEnv.create();

        const envParsed = dotenv.parse(fs.readFileSync(envPath, 'utf8'));

        expect(envParsed).toEqual({
          [config.envStoreVar]: '',
          [config.envPasswordVar]: '',
          [config.envThemeIdVar]: '',
          [config.envIgnoreFilesVar]: '',
        });
      });
Пример #13
0
Lambda.prototype._setRunTimeEnvironmentVars = function (program) {
  var configValues = fs.readFileSync(program.configFile);
  var config = dotenv.parse(configValues);

  for (var k in config) {
    if (!config.hasOwnProperty(k)) {
      continue;
    }

    process.env[k] = config[k];
  }
};
Пример #14
0
  _setRunTimeEnvironmentVars (program) {
    const configValues = fs.readFileSync(program.configFile)
    const config = dotenv.parse(configValues)

    for (let k in config) {
      if (!config.hasOwnProperty(k)) {
        continue
      }

      process.env[k] = config[k]
    }
  }
Пример #15
0
    config: function (options) {
        options = options || {};
        dotenv.load(options);
        var sampleVars = dotenv.parse(fs.readFileSync(options.sample || '.env.example'));
        var allowEmptyValues = options.allowEmptyValues || false;
        var processEnv = allowEmptyValues ? process.env : compact(process.env);
        var missing = difference(Object.keys(sampleVars), Object.keys(processEnv));

        if (missing.length > 0) {
            throw new Error('Missing environment variables: ' + missing.join(', '));
        }
        return true;
    },
Пример #16
0
      test('with invalid config values ommited', () => {
        const env = slateEnv.getEmptySlateEnv();
        const store = 'test-shop.myshopify.com';
        const invalidKey = 'INVALID_VARIABLE';
        const invalidValue = 'some value';

        env[config.envStoreVar] = store;
        env[invalidKey] = invalidValue;
        slateEnv.create({values: env});

        const envParsed = dotenv.parse(fs.readFileSync(envPath, 'utf8'));

        expect(envParsed).toHaveProperty(config.envStoreVar, store);
        expect(envParsed).not.toHaveProperty(invalidKey, invalidValue);
      });
Пример #17
0
const loadEnv = (envPath, options = {}) => {
  const { cwd, stage } = options
  let fileName = '.env'
  if (stage) {
    fileName += `-${stage}`
  }
  let pathParts = [envPath, fileName]
  if (!isAbsolute(envPath)) {
    pathParts = prepend(cwd, pathParts)
  }
  const envFilePath = resolve(...pathParts)
  try {
    const data = readFileSync(envFilePath, 'utf8')
    return dotenv.parse(data)
  } catch (error) {
    if (!error.message.includes('ENOENT')) {
      throw error
    }
  }
  return {}
}
Пример #18
0
Lambda.prototype._setEnvironmentVars = function (program, codeDirectory) {
  console.log('=> Setting "environment variables" for Lambda from %s', program.configFile);
  // Which file is the handler?
  var handlerFileName = codeDirectory + '/' + program.handler.split('.').shift() + '.js';
  var contents = fs.readFileSync(handlerFileName);

  var configValues = fs.readFileSync(program.configFile);
  var prefix = '////////////////////////////////////\n// "Environment Variables"\n';
  var config = dotenv.parse(configValues);

  for (var k in config) {
    if (!config.hasOwnProperty(k)) {
      continue;
    }

    // Use JSON.stringify to ensure that it's valid code.
    prefix += 'process.env["' + k + '"]=' + JSON.stringify(config[k]) + ';\n';
  }
  prefix += '////////////////////////////////////\n\n';

  fs.writeFileSync(handlerFileName, prefix + contents.toString());
};
Пример #19
0
proGulp.task("config", () => {
    var config = {};
    if (NODE_ENV === "development") {
        // In development, read from the `.env` file
        try {
            const env = fs.readFileSync(`${process.cwd()}/.env`);
            config = dotenv.parse(env);
        } catch (ignore) {
            console.log("Failed to read configuration from file `.env`");
        }
    }
    if (NODE_ENV === "production") {
        // In production, read from the `process.env` but only those variables
        // having a key that starts with __APP_CONFIG__
        const prefixRegexp = /^__APP_CONFIG__/;
        config = _(process.env)
            .pickBy((value, key) => prefixRegexp.test(key))
            .mapKeys((value, key) => key.replace(prefixRegexp, ""));
    }
    const code = `window.APP_CONFIG = ${JSON.stringify(config, null, 4)};`;
    fs.writeFileSync(`${buildDir}/app-config.js`, code);
});
Пример #20
0
app.post('*', (req, res) => {
  // Создание файла из объекта конфигурации
  const env = Object.keys(req.body)
    .filter(key => req.body[key])
    .map(key => key + '=' + req.body[key])
    .join('\n')
  const config = dotenv.parse(env)
  // Инициализация
  Promise.resolve(config)
    .then(init.createDatabase)
    .then(init.connectDatabase)
    .then(init.createTables)
    // .then(console.log)
    .then(() => {
      fs.writeFileSync('./.env', env)
      res.redirect('http://localhost:3000')
      process.exit()
    })
    .catch(err => {
      console.error(err)
      res.json(err)
    })
})
Пример #21
0
var envParse = function envParse(doc) {
  return dotenv.parse(doc);
};
Пример #22
0
// Load /path/to/project-root/.env file and returns the key-value object
// Load .env.staging, .env.production if NODE_ENV environment variable is defined.
function main() {
    const projectRoot = getProjectRoot()
    const nodeEnv = getNodeEnv()
    const file = loadEnvFile(projectRoot, nodeEnv)
    return dotenv.parse(file)
}
/**
 * Base webpack config used across other specific configs
 */

import path from 'path';
import webpack from 'webpack';
import fs from 'fs';
import dotenv from 'dotenv';
import { dependencies as externals } from './app/package.json';

// Get all the possible flags
const data = fs.readFileSync('.env.example', { encoding: 'utf8' });
const buffer = new Buffer(data);
const flags = Object.keys(dotenv.parse(buffer));

export default {
  externals: Object.keys(externals || {}),

  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            cacheDirectory: true
          }
        }
      }
    ]
Пример #24
0
  console.log(yargs.help());
  process.exit(1);
} else {
  // Docker image.
  var image = args._[0];
  // Arguments for docker cmd (note that we do not specify a shell here very
  // similar to how docker run does not specify a default shell for commands)
  var command = args._.slice(1);
}

// Command line arguments should take precedence over those listed in the env 
// file. Allows selective overwriting of env variables.
var env = {};
if (args.envFile) {
  if (fs.existsSync(args.envFile)) {
    env = dotenv.parse(fs.readFileSync(args.envFile));
  } else {
    console.error('Environment file does not exist at the location provided.');
    process.exit(1);
  }
}

if (args.env) {
  var cliEnvs = args.env;
  if (args.env instanceof Array) {
    cliEnvs = args.env.join('\n');
  }
  var parsedEnvs = dotenv.parse(cliEnvs);
  for (var envName in parsedEnvs) {
    env[envName] = parsedEnvs[envName];
  }
Пример #25
0
  var run = function(mode, container, exitCb, cb) {
    var cmd = container.specific.execute.exec;
    var cwd = container.specific.path;
    var envFile = getEnvFile(container);

    var env;
    var toExec;
    var child = {};
    var envArgs = '';
    var called = false;

    if (cmd.slice(0, 5) === 'node ' && cmd.slice(0, 7) !== 'node -r') {
      // use same node running fuge
      var fugePath = process.mainModule.filename;
      cmd = process.argv[0] + ' -r ' + fugePath + ' ' + cmd.slice(5);
      container.type = 'node';
    }

    if (envFile && !fs.existsSync(envFile)) {
      return cb('Error: ' + envFile + ' does not exist');
    }

    if (container.specific && container.specific.environment) {
      envArgs = generateEnvironment(container.specific.environment);
    }

    if (envFile) {
      var envFileData = dotenv.parse(fs.readFileSync(envFile));
      envArgs += ' ' + generateEnvironment(envFileData || {});
    }

    if (isWin) {
      toExec = envArgs + ' ' + cmd;
    }
    else {
      toExec = envArgs + ' exec ' + cmd;
    }


    toExec = handleIpAddress(container, toExec);

    console.log('running: ' + toExec);

    env = Object.create(process.env);
    if (mode !== 'preview') {
      var options = {cwd: cwd, env: env, stdio: [0, 'pipe', 'pipe'], detached: false};
      if (container.type === 'node') {
        options.stdio[3] = 'ipc';
      }

      if (isWin) {
        child = spawn(process.env.comspec, ['/c', toExec], options);
      }
      else {
        child = spawn('/bin/bash', ['-c', toExec], options);
      }

      child.unref();

      child.on('error', function(err) {
        if (!called) {
          called = true;
          exitCb(child.pid, container.name, err);
        }
      });

      child.on('exit', function(code) {
        if (!called) {
          called = true;
          exitCb(child.pid, container.name, code);
        }
      });
    }
    else {
      child.detail = { cmd: cmd,
        environment: container.specific.environment,
        cwd: cwd };
    }

    cb(null, child);



    function getEnvFile(container) {
      /* jshint ignore:start */
      var envFile = container.specific.source.env_file;
      /* jshint ignore:end */
      var yamlPath = container.specific.yamlPath;
      return envFile && path.resolve(path.dirname(yamlPath), envFile);
    }
  };
gulp.task('transifex-download', function () {
    var project_slug = 'ushahidi-v3',
        mode = 'default',
        resource = 'client-en',
        // Get languages that are at least 90% translated
        completion_threshold = 70,
        config = {};

    // Try to load user's ~/.transifexrc config
    // see http://docs.transifex.com/client/config/
    try {
        config = dotenv.parse(fs.readFileSync(process.env.HOME + '/.transifexrc'));
    } catch (e) {
        // silently skip
    }

    // Try to load username/password from env
    config.username = config.username || process.env.TX_USERNAME;
    config.password = config.password || process.env.TX_PASSWORD;

    if (!config.username || !config.password) {
        throw 'Missing transifex username and password';
    }

    var transifex = new Transifex({
        project_slug: project_slug,
        credential: config.username + ':' + config.password
    });

    // Get language info
    transifex.languageSetMethods(function (err, data) {
        if (err) {
            throw err;
        }

        try {
            fs.mkdirSync(transifex_dir);
            fs.mkdirSync(locales_dir);
        }
        catch (err) {
            if (err.code !== 'EEXIST') {
                throw err;
            }
        }

        // Get language stats
        transifex.statisticsMethods(project_slug, resource, function (err, stats) {
            if (err) {
                throw err;
            }

            // Only download languages that have been translated past the completion threshold
            data = data.filter(function (language) {
                if (stats[language.code] !== undefined && parseInt(stats[language.code].completed) >= completion_threshold) {
                    return true;
                }

                return false;
            });

            // Download translations
            data.forEach(function (language) {
                transifex.translationInstanceMethod(project_slug, resource, language.code, { mode: mode }, function (err, data) {
                    if (err) {
                        throw err;
                    }

                    fs.writeFileSync(transifex_dir +
                                     // Replace underscore with hyphen
                                     language.code.replace('_', '-') +
                                     '.json', data);
                });
            });


            // Replace language code underscores with hyphens
            var languages = data.map(function (language) {
                language.code = language.code.replace('_', '-');
                return language;
            });

            // Save translated language list
            fs.writeFileSync(transifex_dir + 'languages.json', JSON.stringify({languages: languages}));

        });
    });
});
Пример #27
0
function Server (opts) {
  if (!(this instanceof Server)) return new Server(opts);
  opts || (opts = {});
  
  var envFile = fs.readFileSync((opts.dir || process.cwd()) + '/.env');
  var secrets = dotenv.parse(envFile);

  this.site = opts.site;

  /*
  * Set path for static files
  */

  this.staticFiles = opts.staticFiles || __dirname + '/public';

  /*
  * Create leveldb using level-sublevel
  */

  this.db = level(opts.db || __dirname + '/data/db');


  /*
  * Create sublevel for sheets
  */

  this.sheets = Sheets(sublevel(this.db).sublevel('sheets', {
    valueEncoding: 'json'
  }));


  /*
  * Create sublevel for sessions using level-session
  */

  this.session = levelSession({
    db: sublevel(this.db).sublevel('sessions')
  });


  /*
  * Set up accountdown with accountdown-basic for account management
  */

  this.accounts = accountdown(this.db, {
    login: { basic: require('accountdown-basic') },
    keyEncoding: 'buffer',
    valueEncoding: 'json'
  });


  /*
  * Invites sublevel
  */

  this.invites = sublevel(this.db).sublevel('invites', {
    valueEncoding: 'json'
  });


  /*
  * Email
  */

  var options = {
    auth: {
      api_user: secrets.SENDGRID_USER,
      api_key: secrets.SENDGRID_PASS
    }
  };

  this.email = nodemailer.createTransport(sgTransport(options));


  /*
  * Set up the application's views
  */

  this.views = {};
  this.viewsDir = opts.viewsDir || __dirname + '/views/';
  this.createViews();

  this.viewData = {
    site: this.site
  };
  
  opts.cors || (opts.cors = {});
  
  this.cors = corsify({
    'Access-Control-Allow-Origin': opts.cors['Access-Control-Allow-Origin'] || '*',
    'Access-Control-Allow-Methods': opts.cors['Access-Control-Allow-Methods'] || 'GET, POST, PUT, DELETE',
    'Access-Control-Allow-Headers': opts.cors['Access-Control-Allow-Headers'] || 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept, Authorization'
  });


  /*
  *  Create the http server
  */

  this.createServer();


  /*
  * Set up the routes of the app
  */

  if (opts.defaultRoutes !== false) {
    apiV2.install(this);
    sheets.install(this);
    accounts.install(this);
    sessions.install(this);
  }
}
Пример #28
0
	return new Promise(async (_resolve, reject) => {
		const start = Date.now()
		const rawPath = argv._[0]

		const nowPlans = new NowPlans({
			apiUrl,
			token,
			debug,
			currentTeam
		})
		const planPromise = nowPlans.getCurrent()

		try {
			await fs.stat(rawPath || path)
		} catch (err) {
			let repo
			let isValidRepo = false

			try {
				isValidRepo = isRepoPath(rawPath)
			} catch (_err) {
				if (err.code === 'INVALID_URL') {
					await stopDeployment(_err)
				} else {
					reject(_err)
				}
			}

			if (isValidRepo) {
				const gitParts = gitPathParts(rawPath)
				Object.assign(gitRepo, gitParts)

				const searchMessage = setTimeout(() => {
					console.log(
						`> Didn't find directory. Searching on ${gitRepo.type}...`
					)
				}, 500)

				try {
					repo = await fromGit(rawPath, debug)
					/*eslint-disable */
				} catch (err) {}
				/*eslint-enable */

				clearTimeout(searchMessage)
			}

			if (repo) {
				// Tell now which directory to deploy
				path = repo.path

				// Set global variable for deleting tmp dir later
				// once the deployment has finished
				Object.assign(gitRepo, repo)
			} else if (isValidRepo) {
				const gitRef = gitRepo.ref ? `with "${chalk.bold(gitRepo.ref)}" ` : ''

				await stopDeployment(
					`There's no repository named "${chalk.bold(
						gitRepo.main
					)}" ${gitRef}on ${gitRepo.type}`
				)
			} else {
				console.error(error(`The specified directory "${basename(path)}" doesn't exist.`))
				await exit(1)
			}
		}

		// Make sure that directory is deployable
		try {
			await checkPath(path)
		} catch (err) {
			console.error(error({
				message: err.message,
				slug: 'path-not-deployable'
			}))
			await exit(1)
		}

		if (!quiet) {
			if (gitRepo.main) {
				const gitRef = gitRepo.ref ? ` at "${chalk.bold(gitRepo.ref)}" ` : ''
				console.log(
					info(`Deploying ${gitRepo.type} repository "${chalk.bold(
						gitRepo.main
					)}"${gitRef} under ${chalk.bold(
						(currentTeam && currentTeam.slug) || user.username || user.email
					)}`)
				)
			} else {
				console.log(
					info(`Deploying ${chalk.bold(toHumanPath(path))} under ${chalk.bold(
						(currentTeam && currentTeam.slug) || user.username || user.email
					)}`)
				)
			}
		}

		let deploymentType

		// CLI deployment type explicit overrides
		if (argv.docker) {
			if (debug) {
				console.log('> [debug] Forcing `deploymentType` = `docker`')
			}

			deploymentType = 'docker'
		} else if (argv.npm) {
			if (debug) {
				console.log('> [debug] Forcing `deploymentType` = `npm`')
			}

			deploymentType = 'npm'
		} else if (argv.static) {
			if (debug) {
				console.log('> [debug] Forcing `deploymentType` = `static`')
			}

			deploymentType = 'static'
		}

		let meta
    ;({
			meta,
			deploymentName,
			deploymentType,
			sessionAffinity
		} = await readMeta(path, deploymentName, deploymentType, sessionAffinity))
		const nowConfig = meta.nowConfig

		const now = new Now({ apiUrl, token, debug, currentTeam })

		let dotenvConfig
		let dotenvOption

		if (argv.dotenv) {
			dotenvOption = argv.dotenv
		} else if (nowConfig && nowConfig.dotenv) {
			dotenvOption = nowConfig.dotenv
		}

		if (dotenvOption) {
			const dotenvFileName =
        typeof dotenvOption === 'string' ? dotenvOption : '.env'

			try {
				const dotenvFile = await fs.readFile(dotenvFileName)
				dotenvConfig = dotenv.parse(dotenvFile)
			} catch (err) {
				if (err.code === 'ENOENT') {
					console.error(error({
						message: `--dotenv flag is set but ${dotenvFileName} file is missing`,
						slug: 'missing-dotenv-target'
					}))
					await exit(1)
				} else {
					throw err
				}
			}
		}

		// Merge dotenv config, `env` from now.json, and `--env` / `-e` arguments
		const deploymentEnv = Object.assign(
			{},
			dotenvConfig,
			parseEnv(nowConfig && nowConfig.env, null),
			parseEnv(argv.env, undefined)
		)

		// If there's any envs with `null` then prompt the user for the values
		const askFor = Object.keys(deploymentEnv).filter(key => deploymentEnv[key] === null)
		Object.assign(deploymentEnv, await promptForEnvFields(askFor))

		let secrets
		const findSecret = async uidOrName => {
			if (!secrets) {
				secrets = await now.listSecrets()
			}

			return secrets.filter(secret => {
				return secret.name === uidOrName || secret.uid === uidOrName
			})
		}

		const env_ = await Promise.all(
			Object.keys(deploymentEnv).map(async key => {
				if (!key) {
					console.error(error({
						message: 'Environment variable name is missing',
						slug: 'missing-env-key-value'
					}))
					await exit(1)
				}

				if (/[^A-z0-9_]/i.test(key)) {
					console.error(error(
						`Invalid ${chalk.dim('-e')} key ${chalk.bold(
							`"${chalk.bold(key)}"`
						)}. Only letters, digits and underscores are allowed.`
					))
					await exit(1)
				}

				let val = deploymentEnv[key]

				if (val === undefined) {
					if (key in getProcess().env) {
						console.log(
							`> Reading ${chalk.bold(
								`"${chalk.bold(key)}"`
							)} from your env (as no value was specified)`
						)
						// Escape value if it begins with @
						val = getProcess().env[key].replace(/^@/, '\\@')
					} else {
						console.error(error(
							`No value specified for env ${chalk.bold(
								`"${chalk.bold(key)}"`
							)} and it was not found in your env.`
						))
						await exit(1)
					}
				}

				if (val[0] === '@') {
					const uidOrName = val.substr(1)
					const _secrets = await findSecret(uidOrName)
					if (_secrets.length === 0) {
						if (uidOrName === '') {
							console.error(error(
								`Empty reference provided for env key ${chalk.bold(
									`"${chalk.bold(key)}"`
								)}`
							))
						} else {
							console.error(error({
								message: `No secret found by uid or name ${chalk.bold(`"${uidOrName}"`)}`,
								slug: 'env-no-secret'
							}))
						}
						await exit(1)
					} else if (_secrets.length > 1) {
						console.error(error(
							`Ambiguous secret ${chalk.bold(
								`"${uidOrName}"`
							)} (matches ${chalk.bold(_secrets.length)} secrets)`
						))
						await exit(1)
					}

					val = { uid: _secrets[0].uid }
				}

				return [key, typeof val === 'string' ? val.replace(/^\\@/, '@') : val]
			})
		)

		const env = {}
		env_.filter(v => Boolean(v)).forEach(([key, val]) => {
			if (key in env) {
				console.log(
					note(`Overriding duplicate env key ${chalk.bold(`"${key}"`)}`)
				)
			}

			env[key] = val
		})

		let syncCount
		try {
			const createArgs = Object.assign(
				{
					env,
					followSymlinks,
					forceNew,
					forwardNpm: alwaysForwardNpm || forwardNpm,
					quiet,
					wantsPublic,
					sessionAffinity
				},
				meta
			)

			await now.create(path, createArgs)
			if (now.syncFileCount > 0) {
				await new Promise((resolve) => {
					if (debug && now.syncFileCount !== now.fileCount) {
						console.log(
							`> [debug] total files ${now.fileCount}, ${now.syncFileCount} changed. `
						)
					}
					const size = bytes(now.syncAmount)
					syncCount = `${now.syncFileCount} file${now.syncFileCount > 1
						? 's'
						: ''}`
					const bar = new Progress(
						`> Upload [:bar] :percent :etas (${size}) [${syncCount}]`,
						{
							width: 20,
							complete: '=',
							incomplete: '',
							total: now.syncAmount,
							clear: true
						}
					)

					now.upload()

					now.on('upload', ({ names, data }) => {
						const amount = data.length
						if (debug) {
							console.log(
								`> [debug] Uploaded: ${names.join(' ')} (${bytes(data.length)})`
							)
						}
						bar.tick(amount)
					})

					now.on('complete', () => resolve())

					now.on('error', err => {
						console.error(error('Upload failed'))
						reject(err)
					})
				})

				await now.create(path, createArgs)
			}
		} catch (err) {
			if (debug) {
				console.log(`> [debug] error: ${err}\n${err.stack}`)
			}

			await stopDeployment(err)
		}

		const { url } = now
		const elapsed = ms(new Date() - start)

		if (isTTY) {
			if (clipboard) {
				try {
					await copy(url)
					console.log(
						`${chalk.cyan('> Ready!')} ${chalk.bold(
							url
						)} (copied to clipboard) [${elapsed}]`
					)
				} catch (err) {
					console.log(
						`${chalk.cyan('> Ready!')} ${chalk.bold(url)} [${elapsed}]`
					)
				}
			} else {
				console.log(`> ${url} [${elapsed}]`)
			}
		} else {
			getProcess().stdout.write(url)
		}

		const startU = new Date()
		const plan = await planPromise
		if (plan.id === 'oss' && !wantsPublic) {
			if (isTTY) {
				console.log(
					info(
						`${chalk.bold(
							(currentTeam && `${currentTeam.slug} is`) ||
                `You (${user.username || user.email}) are`
						)} on the OSS plan. Your code and logs will be made ${chalk.bold(
							'public'
						)}.`
					)
				)

				const proceed = await promptBool(
					'Are you sure you want to proceed with the deployment?',
					{ trailing: eraseLines(1) }
				)

				if (proceed) {
					console.log(
						note(`You can use ${cmd('now --public')} to skip this prompt`)
					)
				} else {
					const stopSpinner = wait('Canceling deployment')
					await now.remove(now.id, { hard: true })
					stopSpinner()
					console.log(
						info(
							'Deployment aborted. No files were synced.',
							`  You can upgrade by running ${cmd('now upgrade')}.`
						)
					)
					return 0
				}
			} else if (!wantsPublic) {
				const msg =
          '\nYou are on the OSS plan. Your code and logs will be made public.' +
          ' If you agree with that, please run again with --public.'
				await stopDeployment(msg)
			}
		}

		if (!quiet) {
			if (syncCount) {
				const elapsedU = ms(new Date() - startU)
				console.log(
					`> Synced ${syncCount} (${bytes(now.syncAmount)}) [${elapsedU}] `
				)
			}
		}

		// Show build logs
		if (deploymentType === 'static') {
			if (!quiet) {
				console.log(success('Deployment complete!'))
			}
			await exit(0)
		} else {
			if (nowConfig && nowConfig.atlas) {
				const cancelWait = wait('Initializing…')
				try {
					await printEvents(now, currentTeam, {
						onOpen: cancelWait,
						debug
					})
				} catch (err) {
					cancelWait()
					throw err
				}
				await exit(0)
			} else {
				if (!quiet) {
					console.log(info('Initializing…'))
				}
				printLogs(now.host, token, currentTeam, user)
			}
		}
	})
Пример #29
0
function getEnvVars(){
	let envFileContents = fs.readFileSync(ENV_FILE);
	return dotenv.parse(envFileContents);
}
Пример #30
0
function Server (opts, cb) {
  if (!(this instanceof Server)) return new Server(opts, cb);

  opts = extend({ 
    site: { 
      title: 'flatsheet',
      email: '*****@*****.**',
      url: 'http://127.0.0.1',
      contact: 'flatsheet admin' 
    }
  }, opts)

  var self = this;
  this.site = opts.site;

  var envFilePath = path.join((opts.dir || process.cwd()), '.env');

  if (fs.existsSync(envFilePath)) {
    var envFile = fs.readFileSync(envFilePath);
    var secrets = dotenv.parse(envFile);
  } else {
    var secrets = {
      SENDGRID_USER: process.env.SENDGRID_USER,
      SENDGRID_PASS: process.env.SENDGRID_PASS
    }
  }

  /*
  * Set path for static files
  */

  this.staticFiles = opts.staticFiles || path.join(__dirname, '..', 'public');
  this.staticFileUrl = opts.staticFileUrl || '/public/'

  mkdirp(this.staticFiles, function (err) {
    if (err) console.error(err)
  });

  /*
  * Set path for db
  */

  this.dataDir = opts.dataDir || opts.db || path.join(__dirname, '..', 'data');

  mkdirp(this.dataDir, function (err) {
    if (err) console.error(err);
    else initdb(self, cb);
  });

  /*
  * Email
  */

  var options = {
    auth: {
      api_user: secrets.SENDGRID_USER,
      api_key: secrets.SENDGRID_PASS
    }
  };

  this.email = nodemailer.createTransport(sgTransport(options));
  
  this.router = Router()
  
  /*
  * Set up the application's views
  */

  this.views = {}
  this.viewsDir = path.join(__dirname, '/../views/');
  this.viewData = { site: opts.site };
  this.addViews();

  if (opts.views) {
    if (opts.views[opts.views.length - 1] !== '/')  opts.views += '/';
    this.viewsOverrideDir = opts.views;
    this.overrideViews();
  }

}