/*
returns the env file content

@param {obj} command line options
@return {string} file content
432880
function envFileContent(cmdOptions) {
  var filePath, envFiles;
  var fileContent = '';
  if (cmdOptions.env) {
    envFiles = cmdOptions.env.split(',');
    for (var i = 0; i < envFiles.length; i++ ) {
      filePath = path.normalize(envFiles[i]);
      if (fs.existsSync(filePath)) {
	fileContent += fs.readFileSync(filePath, 'utf8');
	fileContent += "\n";
      }
    }
  } else if (fs.existsSync(parser.cmdWorkingDir(cmdOptions) + '/.env')) {
    filePath = parser.cmdWorkingDir(cmdOptions) + '/.env';
    fileContent = fs.readFileSync(filePath, 'utf8');
  }

  return fileContent;
}
1152721
function replaceEnvironmentVariables (fileContent) {
  const environmentVariable = new RegExp(/\${([^}]+)}/g)
  // eslint-disable-next-line
  fileContent = fileContent.replace(environmentVariable, (a, b) => process.env[b] || '')
  return fileContent
}
1322386
function pr_parse(options) {
    this.traverse(options, function (dir, item, out) {
      fs.readFile(dir + item, function(err, data) {
        console.log('adding log ' + dir + item);

        if (err) {
          console.log(err);
          console.log(data);
          return;
        }

        var source = data.toString();
        var output;

        // if no match in the file
        if (!source.match(regex)) {
          return;
        }

        output = source.replace(regex, replacer);

        fs.writeFile(out + item, output, function(err) {
          if (err) {
            console.log(err);
          } else {
            console.log(out + item + ' was saved!');
          }
        });
      });
    });
  }
727087
function getContentPath(modelId,contentId) {
	//console.log('getContentPath:');
	modelId = modelId.toString();
	contentId = contentId.toString();
	//console.log(modelId);
	//console.log(contentId);
	var path = '';
	path += 'files/model/';
	for(var i=0; i<String(modelId).length; i++) {
		path += modelId.charAt(i)+'/';
	}
	path += 'content/';
	for(i=0; i<String(contentId).length; i++) {
		path += contentId.charAt(i)+'/';
	}
	return path;
}
254211
function procEnvVar(cmdOptions, index) {
  var fileEnvVar = parser.parseEnvOpts(cmdOptions);
  // process.env holds references which can cause unwanted side effects
  // cloning prevents changes to the variable values
  var processEnvVar = _.clone(process.env);
  var envVar = _.extend(processEnvVar, fileEnvVar);
  envVar.PORT = (cmdOptions.port + index);
  return envVar;
}
841079
def read_env():
    """"""
    parser = argparse.ArgumentParser(description='mongo-orchestration server')
    parser.add_argument('-f', '--config',
                        action='store', default=None, type=str, dest='config')
    parser.add_argument('-e', '--env',
                        action='store', type=str, dest='env', default=None)
    parser.add_argument(action='store', type=str, dest='command',
                        default='start', choices=('start', 'stop', 'restart'))
    parser.add_argument('--no-fork',
                        action='store_true', dest='no_fork', default=False)
    parser.add_argument('-b', '--bind',
                        action='store', dest='bind', type=str,
                        default=DEFAULT_BIND)
    parser.add_argument('-p', '--port',
                        action='store', dest='port', type=int,
                        default=DEFAULT_PORT)
    parser.add_argument('--enable-majority-read-concern', action='store_true',
                        default=False)
    parser.add_argument('-s', '--server',
                        action='store', dest='server', type=str,
                        default=DEFAULT_SERVER, choices=('cherrypy', 'wsgiref'))
    parser.add_argument('--version', action='version',
                        version='Mongo Orchestration v' + __version__)
    parser.add_argument('--socket-timeout-ms', action='store',
                        dest='socket_timeout',
                        type=int, default=DEFAULT_SOCKET_TIMEOUT)
    parser.add_argument('--pidfile', action='store', type=str, dest='pidfile',
                        default=PID_FILE)

    cli_args = parser.parse_args()

    if cli_args.env and not cli_args.config:
        print("Specified release '%s' without a config file" % cli_args.env)
        sys.exit(1)
    if cli_args.command == 'stop' or not cli_args.config:
        return cli_args
    try:
        # read config
        with open(cli_args.config, 'r') as fd:
            config = json.loads(fd.read(), object_pairs_hook=SON)
        if not 'releases' in config:
            print("No releases defined in %s" % cli_args.config)
            sys.exit(1)
        releases = config['releases']
        if cli_args.env is not None and cli_args.env not in releases:
            print("Release '%s' is not defined in %s"
                  % (cli_args.env, cli_args.config))
            sys.exit(1)
        cli_args.releases = releases
        return cli_args
    except (IOError):
        print("config file not found")
        sys.exit(1)
    except (ValueError):
        print("config file is corrupted")
        sys.exit(1)
651367
function getEnv(key) {
  return process.env[key.toLowerCase()] || process.env[key.toUpperCase()] || '';
}
40072
function loadEnvFromFile (fileName) {
  try {
    var receivers = fs.readFileSync(fileName).toString()
    if (receivers) {
      var lines = receivers.split('\n')
    }
    // console.log(new Date(), 'loading Sematext receiver URLs from ' + fileName)
    lines.forEach(function (line) {
      var kv = line.split('=')
      if (kv.length === 2 && kv[1].length > 0) {
        process.env[kv[0].trim()] = kv[1].trim()
      // console.log(kv[0].trim() + ' = ' + kv[1].trim())
      }
    })
  } catch (error) {
    // ignore missing file or wrong format
    // console.error(error.message)
  }
}
825434
function getSourceMap(options) {
  var sourceMap = options.sourceMap;

  if (sourceMap && typeof sourceMap !== 'string' && options.outFile) {
    sourceMap = options.outFile + '.map';
  }

  return sourceMap && typeof sourceMap === 'string' ? path.resolve(sourceMap) : null;
}
605970
function getContentFromNode(options, node) {
	return new Promise(function (resolve, reject) {
		if (node.tag === 'link') {
			return fs.readFile(normalizePath(node.attrs.href, options.root, options.from), 'utf8', function (err, res) {
				return err ? reject(err) : resolve(res);
			});
		}

		return resolve(node.content);
	});
}
499950
function Cli(argv) {
  var Cucumber = require('cucumber');
  var Command = require('commander').Command;
  var path = require('path');

  function collect(val, memo) {
    memo.push(val);
    return memo;
  }

  function getProgram() {
    var program = new Command(path.basename(argv[1]));

    program
      .usage('[options] [<DIR|FILE[:LINE]>...]')
      .version(Cucumber.VERSION, '-v, --version')
      .option('-b, --backtrace', 'show full backtrace for errors')
      .option('--compiler <EXTENSION:MODULE>', 'require files with the given EXTENSION after requiring MODULE (repeatable)', collect, [])
      .option('-d, --dry-run', 'invoke formatters without executing steps')
      .option('--fail-fast', 'abort the run on first failure')
      .option('-f, --format <TYPE[:PATH]>', 'specify the output format, optionally supply PATH to redirect formatter output (repeatable)', collect, ['pretty'])
      .option('--name <REGEXP>', 'only execute the scenarios with name matching the expression (repeatable)', collect, [])
      .option('--no-colors', 'disable colors in formatter output')
      .option('--no-snippets', 'hide step definition snippets for pending steps')
      .option('--no-source', 'hide source uris')
      .option('-p, --profile <NAME>', 'specify the profile to use (repeatable)', collect, [])
      .option('-r, --require <FILE|DIR>', 'require files before executing features (repeatable)', collect, [])
      .option('--snippet-syntax <FILE>', 'specify a custom snippet syntax')
      .option('-S, --strict', 'fail if there are any undefined or pending steps')
      .option('-t, --tags <EXPRESSION>', 'only execute the features or scenarios with tags matching the expression (repeatable)', collect, []);

    program.on('--help', function () {
      console.log('  For more details please visit https://github.com/cucumber/cucumber-js#cli\n');
    });

    return program;
  }

  function getConfiguration() {
    var program = getProgram();
    program.parse(argv);
    var profileArgs = Cucumber.Cli.ProfilesLoader.getArgs(program.profile);
    if (profileArgs.length > 0) {
      var fullArgs = argv.slice(0, 2).concat(profileArgs).concat(argv.slice(2));
      program = getProgram();
      program.parse(fullArgs);
    }
    var configuration = Cucumber.Cli.Configuration(program.opts(), program.args);
    return configuration;
  }

  var self = {
    run: function run(callback) {
      var configuration = getConfiguration();
      var runtime = Cucumber.Runtime(configuration);
      var formatters = [createIpcFormatter()].concat(configuration.getFormatters());
      formatters.forEach(function (formatter) {
        runtime.attachListener(formatter);
      });
      try {
        runtime.start(callback);
      } catch (e) {
        console.log(e.stack || e)
        callback(false)
      }
    }
  };
  return self;
}
571122
function loadFromOptions(opts) {
  var defCfg = loadDefault()
  var cfg = opts.config ? loadFromFile(opts.config) : loadDefault()

  // Command line config override file loaded config
  for (var k in opts) {
    defCfg.hasOwnProperty(k) && (defCfg[k] !== opts[k] && (cfg[k] = opts[k]))
  }

  return cfg
}
580269
function getOptions(options, cb) {
  options = options || {};
  options.sourceComments = options.sourceComments || false;
  options.data = options.data || null;
  options.file = getInputFile(options);
  options.outFile = getOutputFile(options);
  options.includePaths = (options.includePaths || []).join(path.delimiter);
  options.precision = parseInt(options.precision) || 5;
  options.sourceMap = getSourceMap(options);
  options.style = getStyle(options);
  options.indentWidth = getIndentWidth(options);
  options.indentType = getIndentType(options);
  options.linefeed = getLinefeed(options);

  // context object represents node-sass environment
  options.context = { options: options, callback: cb };

  options.result = {
    stats: getStats(options)
  };

  return options;
}
1260654
function dockerCommand(options) {
  const cmd = 'docker';
  const ps = spawnSync(cmd, options, { encoding: 'utf-8' });
  if (ps.error) {
    if (ps.error.code === 'ENOENT') {
      throw new Error('docker not found! Please install it.');
    }
    throw new Error(ps.error);
  } else if (ps.status !== 0) {
    throw new Error(ps.stderr);
  }
  return ps;
}
1357050
function envToObject(fullPath) {
    return fs.readFileAsync(fullPath)
        .then((file) => {
            let envVars = {};
            file = file.toString('utf8');
            file = file.replace(/ /g, "");
            let keyvals = file.split(os.EOL)
            for (let i = 0; i <= keyvals.length - 1; ++i) {
                let line = keyvals[i];
                let value = line.substring(line.indexOf('=')+1);
                let key = keyvals[i].split('=')[0];
                if(key !== '') {
                    envVars[key] = value;
                }
            }
            return envVars
        });
}
355373
function toVFile(options) {
  if (typeof options === 'string' || buffer(options)) {
    options = {path: String(options)}
  }

  return vfile(options)
}
829718
function getServeEnv (baseDir) {
  let serverEnv

  const envPath = path.join(baseDir, 'config/env')
  if (fs.existsSync(envPath)) {
    serverEnv = fs.readFileSync(envPath, 'utf8')
  }

  if (!serverEnv) {
    serverEnv = process.env.KNOTWORK_ENV || process.env.KOA_ENV
  }

  if (!serverEnv) {
    if (process.env.NODE_ENV === 'test') {
      serverEnv = 'unittest'
    } else if (process.env.NODE_ENV === 'production') {
      serverEnv = 'prod'
    } else {
      serverEnv = 'local'
    }
  } else {
    serverEnv = serverEnv.trim()
  }

  return serverEnv
}