Read and parse configuration file from disc

@param {string} filePath Path of file to read
@param {configComplete} callback Completion callback
@returns {Promise<*>} Resolves tyo YAML parsed configuration file
345128
function readYaml(filePath) {
    return new Promise((resolve, reject) => {
        if (!filePath || typeof filePath !== 'string') {
            throw new Error('Path must be a string');
        }
        fs.readFile(filePath, (err, data) => {
            if (err) {
                return reject(err);
            }
            // Remove UTF-8 BOM if present
            if (data.length >= 3 && data[0] === 0xef &&
                data[1] === 0xbb && data[2] === 0xbf) {
                data = data.slice(3);
            }
            try {
                return resolve(yaml.safeLoad(data));
            } catch (yamlerr) {
                return reject(yamlerr);
            }
        });
    });
}
87153
function(configFilePath) {
  FileRegistry.super_.call(this);
  this._configFilePath = configFilePath || this._getDefaultConfigFilePath();
  try {
    var data = fs.readFileSync(this._configFilePath, 'utf-8');
    this._registryConfig = JSON.parse(data);
  } catch(e) {}
}
668820
function readFiles (filepaths, callback) {
  async.map(filepaths, readFile.bind(this), function (err, files) {

    if (err) callback(err);

    callback(null, files);
  });
}
178258
function getFile(filepath) {
	var fileObj = {
			path: filepath,
			content: null
	};
    try {
        fs.accessSync(filepath, fs.F_OK);
    } catch(e) {
			console.log(e.message);
        return fileObj;
    }
		fileObj.content = fs.readFileSync(filepath, 'utf-8').trim();
		return fileObj;
}
1272632
function (filePath) {

    // console.warn(filePath);


    var contents = String(fs.readFileSync(filePath));
    var fileExt = path.extname(filePath).substr(1);
    var fileType = fileTypes[fileExt] || fileTypes['default'];
    var returnType = /\r\n/.test(contents) ? '\r\n' : '\n';


    // console.log(fileType);

    var newContents = contents.replace(
        fileType.block,
        replaceIncludes(filePath, fileType, returnType)
    );

    // console.log(newContents);
    //  
    // return;

    if (contents !== newContents) {
        fs.writeFileSync(filePath, newContents);

        if (process.env.NODE_ENV !== 'test') {
            console.log(filePath + ' modified.');
        }
    }
}
966750
def setup(self, filepath):
        
        if self.log is not None:
            self.log.warning("Disallowed multiple setup of config.")
            return

        self.log = logging.getLogger(__name__)
        self.parser = ConfigParser.RawConfigParser()
        self.parser.read(filepath)
        self.sections = self.parser.sections()
        self.log_output.append(
            {"level": "info", "msg": "Loading config-file (%s)" % filepath})
        self.load_config()
        self.handle_logging()
1266229
function findConfig (filePath) {

    var foundConfig;

    var finders = [
        _codetagsrc,
        _embedded
    ];

    var dir = $path.dirname(filePath);
    while (!foundConfig && finders.length) {
        foundConfig = finders.shift()(dir);
    }

    if (!foundConfig) {
        // screwed. should not happen.
        throw 'Oops. Could not find a config, and embedded config also appears to be missing?';
    }

    return foundConfig;

}
229701
function readFileStats(filePath) {
  return new Promise((resolve, reject) => {
    fs.stat(filePath, (err, fstat) => {
      if (err) {
        reject(err);
        return;
      }
      resolve(fstat);
    });
  });
}
1060866
function (filepath) {

            // console.log('processing: ' + filepath);

            // read file source, saved in RAM
            var content = grunt.file.read(filepath);

            /*
             * Reset pattern's last search index to 0
             * at the beginning for each file content.
             *
             * NOTE:
             *   Since the pattern is always the same regex instance,
             *   property 'lastIndex' changes each time when .exec() is performed.
             *   To avoid 'lastIndex' affected by recursive function call,
             *   its value MUST be cached for each file content.
             */
            var cacheLastIndex = 0;
            _.pattern.lastIndex = cacheLastIndex;
            var matches = _.pattern.exec(content);
            cacheLastIndex = _.pattern.lastIndex;

            // While there are matches (of import-links) in file content
            while (matches !== null) {

                /*
                 * Construct the imported file's absolute path
                 *   (doesn't matter whether or not a relative path),
                 * and recursively search in imported file. (dept-first)
                 *
                 * NOTE:
                 *    - the regex uses capture group, the first match is the fragment file path.
                 */
                var currentDir = path.dirname(filepath),
                    relativeFilepath = matches[1].trim(),
                    importedFilepath = path.resolve(currentDir, relativeFilepath);

                var returnContent = getReplacedFileContent(importedFilepath);


                /*
                 * For current file content,
                 * replace import-link tag with return value.
                 *
                 * NOTE:
                 *   Because of dept-first search,
                 *   should ONLY replace the first match in current content.
                 *   rather than search globally.
                 */
                content = content.replace(_.patternNonGlobal, returnContent);
                // console.log(content);
                // console.log(matches);
                // console.log('-----');


                /*
                 * Keep searching in current file.
                 *
                 * NOTE:
                 *   After replacing part of the content (the step above),
                 *   the content's length changes accordingly.
                 *   Thus the 'lastIndex' property should shift to
                 *   the proper position to ensure next search.
                 */
                var deltaLength = returnContent.length - matches[0].length;

                _.pattern.lastIndex = cacheLastIndex + deltaLength;
                matches = _.pattern.exec(content);
                cacheLastIndex = _.pattern.lastIndex;
            }

            // When searching and replacing is done, return the result.
            return content;
        }
1049362
static String scanConfigFile(String dirPath) throws ConfigurationException {

        String filePath = dirPath + File.separator + CONFIG_FILE_NAME + ".";

        String fullFilePath;
        // Scan for Yaml file
        if (AuditUtil.isFileExists(filePath + YML_EXTENTION)) {
            fullFilePath = filePath + YML_EXTENTION;
        } else if (AuditUtil.isFileExists(filePath + YAML_EXTENTION)) {
            fullFilePath = filePath + YAML_EXTENTION;
        } else if (AuditUtil.isFileExists(filePath + XML_EXTENTION)) {
            // Scan for XML file
            fullFilePath = filePath + XML_EXTENTION;
        } else {
            // Default configuratin file
            fullFilePath = filePath + YML_EXTENTION;
            generateConfigFile(fullFilePath);
        }
        return fullFilePath;
    }
859874
def load_config(filepath)
      return {} if filepath.nil? || !File.exist?(filepath)

      config_file = File.open(filepath).read

      # Replace environment variables
      config_file = parse_environment_variables(config_file)

      YAML.safe_load(config_file)
    end
1108666
function findConfigFile(filePath) {
		let prev = null
		do {
			const testPath = path.join(filePath, 'tsconfig.json')
			if (fs.existsSync(testPath)) {
				return testPath
			}
			prev = filePath
			filePath = path.dirname(filePath)
		} while (prev !== filePath)
		return undefined
	}
1331913
function loadConfig(path) {
  try {
    var configJSON = JSON.parse(fs.readFileSync(process.cwd() + "/" + path));
    console.log("Config file detected: " + path)
    return configJSON;
  }
  catch(e) {
    console.log("Config file: " + e.toString())
  }
}
985817
function setupConfigurationFile(configFilePath) {
    const fileName = '.wistrc.json';

    try {
        let contents = require(configFilePath);
        fs.writeFileSync(fileName, JSON.stringify(contents, null, 2));
        log.info(`Initialized directory with a ${fileName}`)
    } catch (e) {
        console.error(e.message);
        return 1;
    }
    return 0;
}
233788
function loadYAMLConfig(configPath) {
  try {
    return safeLoad(readFileSync(configPath, 'utf8'))
  } catch (e) {
    if (e.constructor.name === 'YAMLException') {
      throw e
    }
    log.error({
      message: chalk.red(`Unable to find YML config at "${configPath}".`),
      ref: 'unable-to-find-config',
    })
    return undefined
  }
}
1127675
function readConfigFromFile(filePath) {
  var config = {};

  if (isFilePath(filePath)) {
    try {
      config = yaml.safeLoad(stripComments(fs.readFileSync(filePath, 'utf8'))) || {};
    } catch (e) {
      e.message = 'Cannot read config file: ' + filePath + '\nError: ' + e.message;
      throw e;
    }

    if (path.basename(filePath) === PACKAGE_CONFIG_FILENAME) {
      config = config[PACKAGE_CONFIG_FIELD_NAME] || {};
    }

  } else {

        // it's a package

    if (filePath.charAt(0) === '@') {
            // it's a scoped package

            // package name is 'nplint-config', or just a username
      var scopedPackageShortcutRegex = /^(@[^\/]+)(?:\/(?:eslint-config)?)?$/;
      if (scopedPackageShortcutRegex.test(filePath)) {
        filePath = filePath.replace(scopedPackageShortcutRegex, '$1/nplint-config');
      } else if (filePath.split('/')[1].indexOf('eslint-config-') !== 0) {
                // for scoped packages, insert the eslint-config after the first /
        filePath = filePath.replace(/^@([^\/]+)\/(.*)$/, '@$1/nplint-config-$2');
      }
    } else if (filePath.indexOf('nplint-config-') !== 0) {
      filePath = 'nplint-config-' + filePath;
    }

    config = util.mergeConfigs(config, require(filePath));
  }
  return config;
}
998427
function resolvePath(filepath) {
  filepath = filepath.replace(RE_TRAILING, '');
  const cwd = process.cwd();
  const npmPackage = filepath.includes('node_modules');

  // Find nearest node_modules directory
  if (npmPackage) {
    const parts = filepath.split(path.sep);
    let idx = parts.lastIndexOf('node_modules');

    if (idx < parts.length - 1) idx += 2;
    // Handle scoped
    if (parts[idx - 1].charAt(0) == '@') idx++;

    const dir = parts.slice(0, idx).join(path.sep);

    // Installed packages must have manifest, otherwise continue
    if (exists(path.join(dir, 'package.json'))) return dir;
  }

  // Find nearest directory with node_modules subdirectory
  if (filepath.includes(cwd)) {
    let depth = maxFileSystemDepth;
    let dir = filepath;
    let parent = '';

    while (true) {
      parent = path.dirname(dir);
      // Stop if we hit max file system depth or root
      // Convert to lowercase to fix problems on Windows
      if (!--depth || parent.toLowerCase() === dir.toLowerCase()) {
        break;
      }

      // Stop at nearest directory with node_modules or cwd
      if (dir == cwd || exists(path.resolve(dir, 'node_modules'))) return dir;

      // Walk
      dir = parent;
    }
  }

  // Return project directory if file isn't a project file
  return cwd;
}