Check xdg locations for config files
775305
def xdg_config_dir():
    '''
    
    '''
    xdg_config = os.getenv('XDG_CONFIG_HOME', os.path.expanduser('~/.config'))
    xdg_config_directory = os.path.join(xdg_config, 'salt')
    return xdg_config_directory
1281947
def parse_cli_args():
    
    # get config paths
    home_path = os.path.expanduser("~")
    xdg_home_path = os.environ.get("XDG_CONFIG_HOME", "{}/.config".format(home_path))
    xdg_dirs_path = os.environ.get("XDG_CONFIG_DIRS", "/etc/xdg")

    # get i3status path
    try:
        with open(os.devnull, "w") as devnull:
            command = ["which", "i3status"]
            i3status_path = (
                subprocess.check_output(command, stderr=devnull).decode().strip()
            )
    except subprocess.CalledProcessError:
        i3status_path = None

    # get window manager
    with open(os.devnull, "w") as devnull:
        if subprocess.call(["pgrep", "i3"], stdout=devnull) == 0:
            wm = "i3"
        else:
            wm = "sway"

    # i3status config file default detection
    # respect i3status' file detection order wrt issue #43
    i3status_config_file_candidates = [
        "{}/py3status/config".format(xdg_home_path),
        "{}/i3status/config".format(xdg_home_path),
        "{}/i3/i3status.conf".format(xdg_home_path),  # custom
        "{}/.i3status.conf".format(home_path),
        "{}/.i3/i3status.conf".format(home_path),  # custom
        "{}/i3status/config".format(xdg_dirs_path),
        "/etc/i3status.conf",
    ]
    for fn in i3status_config_file_candidates:
        if os.path.isfile(fn):
            i3status_config_file_default = fn
            break
    else:
        # if files does not exists, defaults to ~/.i3/i3status.conf
        i3status_config_file_default = i3status_config_file_candidates[3]

    class Parser(argparse.ArgumentParser):
        # print usages and exit on errors
        def error(self, message):
            print("\x1b[1;31merror: \x1b[0m{}".format(message))
            self.print_help()
            self.exit(1)

        # hide choices on errors
        def _check_value(self, action, value):
            if action.choices is not None and value not in action.choices:
                raise argparse.ArgumentError(
                    action, "invalid choice: '{}'".format(value)
                )

    class HelpFormatter(argparse.ArgumentDefaultsHelpFormatter):
        def _format_action_invocation(self, action):
            metavar = self._format_args(action, action.dest.upper())
            return "{} {}".format(", ".join(action.option_strings), metavar)

    # command line options
    parser = Parser(
        description="The agile, python-powered, i3status wrapper",
        formatter_class=HelpFormatter,
    )
    parser.add_argument(
        "-b",
        "--dbus-notify",
        action="store_true",
        dest="dbus_notify",
        help="send notifications via dbus instead of i3-nagbar",
    )
    parser.add_argument(
        "-c",
        "--config",
        action="store",
        default=i3status_config_file_default,
        dest="i3status_config_path",
        help="load config",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-d",
        "--debug",
        action="store_true",
        help="enable debug logging in syslog and --log-file",
    )
    parser.add_argument(
        "-g",
        "--gevent",
        action="store_true",
        dest="gevent",
        help="enable gevent monkey patching",
    )
    parser.add_argument(
        "-i",
        "--include",
        action="append",
        dest="include_paths",
        help="append additional user-defined module paths",
        metavar="PATH",
    )
    parser.add_argument(
        "-l",
        "--log-file",
        action="store",
        dest="log_file",
        help="enable logging to FILE",
        metavar="FILE",
        type=str,
    )
    parser.add_argument(
        "-s",
        "--standalone",
        action="store_true",
        dest="standalone",
        help="run py3status without i3status",
    )
    parser.add_argument(
        "-t",
        "--timeout",
        action="store",
        default=60,
        dest="cache_timeout",
        help="default module cache timeout in seconds",
        metavar="INT",
        type=int,
    )
    parser.add_argument(
        "-m",
        "--disable-click-events",
        action="store_true",
        dest="disable_click_events",
        help="disable all click events",
    )
    parser.add_argument(
        "-u",
        "--i3status",
        action="store",
        default=i3status_path,
        dest="i3status_path",
        help="specify i3status path",
        metavar="PATH",
        type=str,
    )
    parser.add_argument(
        "-v",
        "--version",
        action="store_true",
        dest="print_version",
        help="show py3status version and exit",
    )
    parser.add_argument(
        "--wm",
        action="store",  # add comment to preserve formatting
        dest="wm",
        metavar="WINDOW_MANAGER",
        default=wm,
        choices=["i3", "sway"],
        help="specify window manager i3 or sway",
    )

    # deprecations
    parser.add_argument("-n", "--interval", help=argparse.SUPPRESS)

    # parse options, command, etc
    options = parser.parse_args()

    # make versions
    options.python_version = python_version()
    options.version = version
    if options.print_version:
        msg = "py3status version {version} (python {python_version}) on {wm}"
        print(msg.format(**vars(options)))
        parser.exit()

    # get wm
    options.wm_name = options.wm
    options.wm = {
        "i3": {"msg": "i3-msg", "nag": "i3-nagbar"},
        "sway": {"msg": "swaymsg", "nag": "swaynag"},
    }[options.wm]

    # make it i3status if None
    if not options.i3status_path:
        options.i3status_path = "i3status"

    # make include path to search for user modules if None
    if not options.include_paths:
        options.include_paths = [
            "{}/py3status/modules".format(xdg_home_path),
            "{}/i3status/py3status".format(xdg_home_path),
            "{}/i3/py3status".format(xdg_home_path),
            "{}/.i3/py3status".format(home_path),
        ]

    include_paths = []
    for path in options.include_paths:
        path = os.path.abspath(path)
        if os.path.isdir(path) and os.listdir(path):
            include_paths.append(path)
    options.include_paths = include_paths

    # defaults
    del options.interval
    del options.print_version
    options.minimum_interval = 0.1  # minimum module update interval
    options.click_events = not options.__dict__.pop("disable_click_events")

    # all done
    return options
38268
def system_config_dir():
    
    """
    if LINUX or SUNOS:
        path = '/etc'
    elif BSD or MACOS:
        path = '/usr/local/etc'
    else:
        path = os.environ.get('APPDATA')
    if path is None:
        path = ''
    else:
        path = os.path.join(path, 'glances')

    return path
364417
private static function findDirectories(): string
    {
        if ($value = trim((string) self::getEnvVariable(self::CONFIG_PATH))) {
            // add env config path to top of possible locations.
            array_unshift(self::$possibleLocations, $value);
        }

        foreach (self::$possibleLocations as $path) {
            if (($location = realpath($path)) !== false) {
                return $location;
            }
        }

        throw new LogicException(sprintf(
            'Configuration directory not found in known path\'s: %s',
            join(',', self::$possibleLocations)
        ));
    }
701723
def xdg_open(uri):
    '''
    '''
    try:
        subprocess.call(['xdg-open', uri, ])
    except FileNotFoundError:
        logger.error(traceback.format_exc())
950867
def config(check):
    """"""
    if check:
        checks = [check]
    else:
        checks = sorted(get_valid_checks())

    files_failed = {}
    files_warned = {}
    num_files = 0

    echo_waiting('Validating default configuration files...')
    for check in checks:
        check_display_queue = []

        config_files = get_config_files(check)
        for config_file in config_files:
            num_files += 1
            file_display_queue = []
            file_name = basepath(config_file)

            try:
                config_data = yaml.safe_load(read_file(config_file))
            except Exception as e:
                files_failed[config_file] = True

                # We must convert to text here to free Exception object before it goes out of scope
                error = str(e)

                check_display_queue.append(lambda: echo_info('{}:'.format(file_name), indent=True))
                check_display_queue.append(lambda: echo_failure('Invalid YAML -', indent=FILE_INDENT))
                check_display_queue.append(lambda: echo_info(error, indent=FILE_INDENT * 2))
                continue

            # Verify there is an `instances` section
            if 'instances' not in config_data:
                files_failed[config_file] = True
                file_display_queue.append(lambda: echo_failure('Missing `instances` section', indent=FILE_INDENT))

            # Verify there is a default instance
            else:
                instances = config_data['instances']
                if check not in IGNORE_DEFAULT_INSTANCE and not isinstance(instances, list):
                    files_failed[config_file] = True
                    file_display_queue.append(lambda: echo_failure('No default instance', indent=FILE_INDENT))

            if file_display_queue:
                check_display_queue.append(lambda: echo_info('{}:'.format(file_name), indent=True))
                check_display_queue.extend(file_display_queue)

        if check_display_queue:
            echo_success('{}:'.format(check))
            for display in check_display_queue:
                display()

    files_failed = len(files_failed)
    files_warned = len(files_warned)
    files_passed = num_files - (files_failed + files_warned)

    if files_failed or files_warned:
        click.echo()

    if files_failed:
        echo_failure('Files with errors: {}'.format(files_failed))

    if files_warned:
        echo_warning('Files with warnings: {}'.format(files_warned))

    if files_passed:
        if files_failed or files_warned:
            echo_success('Files valid: {}'.format(files_passed))
        else:
            echo_success('All {} configuration files are valid!'.format(num_files))

    if files_failed:
        abort()
773480
function findConfigFile() {
	let configDir
	try {
		configDir = findup.sync(process.cwd(), CONFIG_FILENAME)
	} catch (exception) {
		return false
	}

	return path.join(configDir, CONFIG_FILENAME)
}
993437
def _ensure_config_file_exists():
    
    config_file = Path(ELIBConfig.config_file_path).absolute()
    if not config_file.exists():
        raise ConfigFileNotFoundError(ELIBConfig.config_file_path)
296786
def check_cfg_files(cfg_files,module_name):
    

    cfg = ConfigParser.SafeConfigParser()
    cfg.read(cfg_files)
    if cfg.has_section(module_name):
        section_items = cfg.items(module_name)
    else:
        section_items = []
    default_items = cfg.items('DEFAULT')

    n_items = len(section_items) + len(default_items)
    if n_items==0:
        log.warn('configuration files were specified, but no options were '
                 'found in "%s" or "DEFAULT" sections.' % (module_name,) )
1183360
def get_conf_path(filename=None):
    """"""
    # Define conf_dir
    if running_under_pytest() or SAFE_MODE:
        # Use clean config dir if running tests or the user requests it.
        conf_dir = get_clean_conf_dir()
    elif sys.platform.startswith('linux'):
        # This makes us follow the XDG standard to save our settings
        # on Linux, as it was requested on Issue 2629
        xdg_config_home = os.environ.get('XDG_CONFIG_HOME', '')
        if not xdg_config_home:
            xdg_config_home = osp.join(get_home_dir(), '.config')
        if not osp.isdir(xdg_config_home):
            os.makedirs(xdg_config_home)
        conf_dir = osp.join(xdg_config_home, SUBFOLDER)
    else:
        conf_dir = osp.join(get_home_dir(), SUBFOLDER)

    # Create conf_dir
    if not osp.isdir(conf_dir):
        if running_under_pytest() or SAFE_MODE:
            os.makedirs(conf_dir)
        else:
            os.mkdir(conf_dir)
    if filename is None:
        return conf_dir
    else:
        return osp.join(conf_dir, filename)
203981
def default_hass_config_dir():
    """"""
    data_dir = os.getenv("APPDATA") if os.name == "nt" else os.path.expanduser("~")
    return os.path.join(data_dir, ".homeassistant")
151843
def get_config_path(config_file):
    
    config_path = os.getenv('XDG_CONFIG_HOME')
    if not config_path:
        config_path = os.path.join(os.getenv('HOME'), ".config")
    if not config_file:
        config_file = "default"
    return os.path.join(config_path, "trovebox", config_file)
348953
def get_system_config_directory():
    
    if platform.system().lower() == 'windows':
        _cfg_directory = Path(os.getenv('APPDATA') or '~')
    elif platform.system().lower() == 'darwin':
        _cfg_directory = Path('~', 'Library', 'Preferences')
    else:
        _cfg_directory = Path(os.getenv('XDG_CONFIG_HOME') or '~/.config')

    logger.debug('Fetching configt directory for {}.'
                 .format(platform.system()))
    return _cfg_directory.joinpath(Path('mayalauncher/.config'))
344529
def get_xdg_env(env_name, fallback):
    
    env = os.environ.get(env_name)
    return env if env else fallback
744031
function (rootdir, configData, platform) {
        var configFiles = lib.getConfigFilesByTargetAndParent(rootdir, platform),
            type = 'configFile';

        for (var key in configFiles) {
            if (configFiles.hasOwnProperty(key)) {
                var configFile = configFiles[key];

                var keyParts = key.split('|');
                var target = keyParts[0];
                var parent = keyParts[1];
                var items = configData[target] || [];

                configFile.getchildren().forEach(function (element) {
                    items.push({
                        parent: parent,
                        type: type,
                        destination: element.tag,
                        data: element
                    });
                });

                configData[target] = items;
            }
        }
    }
1213269
def user_config_dir():
    
    """
    if WINDOWS:
        path = os.environ.get('APPDATA')
    elif MACOS:
        path = os.path.expanduser('~/Library/Application Support')
    else:
        path = os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config')
    if path is None:
        path = ''
    else:
        path = os.path.join(path, 'glances')

    return path
314904
def search_configuration_files(findstr, replacestr = None):
    ''''''

    F = open(configurationFilesLocation, "r")
    lines = F.readlines()
    F.close()
    allerrors = {}
    alloutput = {}

    for line in lines:
        line = line.strip()
        if line:
            if line.endswith("generate_fragments.py"):
                # Do not parse the Python script but check that it exists
                if not(os.path.exists(line)):
                    allerrors[line] = "File/directory %s does not exist." % line
            else:
                cmd = ["grep", "-n", "-i",  findstr, line]
                output = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()
                errors = output[1]
                output = output[0]
                if errors:
                    errors = errors.strip()
                    allerrors[line] = errors
                if output:
                    output = output.strip()
                    alloutput[line] = output.split("\n")
    return alloutput, allerrors