<commit_before># -*- coding: utf8 - *-
"""Configuration parsing and export for tmuxp.

tmuxp.config
~~~~~~~~~~~~

:copyright: Copyright 2013 <NAME>.
:license: BSD, see LICENSE for details

"""

from __future__ import absolute_import, division, print_function, with_statement
import os
import logging
from . import exc
from .util import basestring

logger = logging.getLogger(__name__)


def validate_schema(sconf):
    """Return True if config schema is correct.

    :param sconf: session configuration
    :type sconf: dict
    :rtype: bool

    """

    # verify session_name
    if not 'session_name' in sconf:
        raise exc.ConfigError('config requires "session_name"')

    if not 'windows' in sconf:
        raise exc.ConfigError('config requires list of "windows"')

    for window in sconf['windows']:
        if not 'window_name' in window:
            raise exc.ConfigError('config window is missing "window_name"')

        if not 'panes' in window:
            raise exc.ConfigError(
                'config window %s requires list of panes' % window['window_name'])

    return True


def is_config_file(filename, extensions=['.yml', '.yaml', '.json', '.ini']):
    """Return True if file has a valid config file type.

    :param filename: filename to check (e.g. ``mysession.json``).
    :type filename: string
    :param extensions: filetypes to check (e.g. ``['.yaml', '.json']``).
    :type extensions: list or string
    :rtype: bool

    """

    extensions = [extensions] if isinstance(
        extensions, basestring) else extensions
    return any(filename.endswith(e) for e in extensions)


def in_dir(config_dir=os.path.expanduser('~/.tmuxp'), extensions=['.yml', '.yaml', '.json', '.ini']):
    """Return a list of configs in ``config_dir``.

    :param config_dir: directory to search
    :type config_dir: string
    :param extensions: filetypes to check (e.g. ``['.yaml', '.json']``).
    :type extensions: list
    :rtype: list

    """
    configs = []

    for filename in os.listdir(config_dir):
        if is_config_file(filename, extensions) and not filename.startswith('.'):
            configs.append(filename)

    return configs


def in_cwd():
    """Return list of configs in current working directory.

    If filename is ``.tmuxp.py``, ``.tmuxp.json``, ``.tmuxp.yaml`` or
    ``.tmuxp.ini``.

    :rtype: list

    """
    configs = []

    for filename in os.listdir(os.getcwd()):
        if filename.startswith('.tmuxp') and is_config_file(filename):
            configs.append(filename)

    return configs


def inline(sconf):
    """ Return config in inline form, opposite of :meth:`config.expand`.

    :param sconf: unexpanded config file
    :type sconf: dict
    :rtype: dict

    """

    if ('shell_command' in sconf and isinstance(sconf['shell_command'], list) and len(sconf['shell_command']) == 1):
        sconf['shell_command'] = sconf['shell_command'][0]

        if len(sconf.keys()) == int(1):
            sconf = sconf['shell_command']
    if ('shell_command_before' in sconf and isinstance(sconf['shell_command_before'], list) and len(sconf['shell_command_before']) == 1):
        sconf['shell_command_before'] = sconf['shell_command_before'][0]

    # recurse into window and pane config items
    if 'windows' in sconf:
        sconf['windows'] = [
            inline(window) for window in sconf['windows']
        ]
    if 'panes' in sconf:
        sconf['panes'] = [inline(pane) for pane in sconf['panes']]

    return sconf


def expand(sconf, cwd=None):
    """Return config with shorthand and inline properties expanded.

    This is necessary to keep the code in the :class:`WorkspaceBuilder` clean
    and also allow for neat, short-hand configurations.

    As a simple example, internally, tmuxp expects that config options
    like ``shell_command`` are a list (array)::

        'shell_command': ['htop']

    tmuxp configs allow for it to be simply a string::

        'shell_command': 'htop'

    Kaptan will load JSON/YAML/INI files into python dicts for you.

    :param sconf: the configuration for the session
    :type sconf: dict
    :param cwd: directory to expand relative paths against. should be the dir
                of the config directory.
    :rtype: dict

    """

    if not cwd:
        cwd = os.getcwd()<commit_msg>Remove .ini as a possible tmux config in api docs<commit_after># -*- coding: utf8 - *-
"""Configuration parsing and export for tmuxp.

tmuxp.config
~~~~~~~~~~~~

:copyright: Copyright 2013 <NAME>.
:license: BSD, see LICENSE for details

"""

from __future__ import absolute_import, division, print_function, with_statement
import os
import logging
from . import exc
from .util import basestring

logger = logging.getLogger(__name__)


def validate_schema(sconf):
    """Return True if config schema is correct.

    :param sconf: session configuration
    :type sconf: dict
    :rtype: bool

    """

    # verify session_name
    if not 'session_name' in sconf:
        raise exc.ConfigError('config requires "session_name"')

    if not 'windows' in sconf:
        raise exc.ConfigError('config requires list of "windows"')

    for window in sconf['windows']:
        if not 'window_name' in window:
            raise exc.ConfigError('config window is missing "window_name"')

        if not 'panes' in window:
            raise exc.ConfigError(
                'config window %s requires list of panes' % window['window_name'])

    return True


def is_config_file(filename, extensions=['.yml', '.yaml', '.json']):
    """Return True if file has a valid config file type.

    :param filename: filename to check (e.g. ``mysession.json``).
    :type filename: string
    :param extensions: filetypes to check (e.g. ``['.yaml', '.json']``).
    :type extensions: list or string
    :rtype: bool

    """

    extensions = [extensions] if isinstance(
        extensions, basestring) else extensions
    return any(filename.endswith(e) for e in extensions)


def in_dir(config_dir=os.path.expanduser('~/.tmuxp'), extensions=['.yml', '.yaml', '.json']):
    """Return a list of configs in ``config_dir``.

    :param config_dir: directory to search
    :type config_dir: string
    :param extensions: filetypes to check (e.g. ``['.yaml', '.json']``).
    :type extensions: list
    :rtype: list

    """
    configs = []

    for filename in os.listdir(config_dir):
        if is_config_file(filename, extensions) and not filename.startswith('.'):
            configs.append(filename)

    return configs


def in_cwd():
    """Return list of configs in current working directory.

    If filename is ``.tmuxp.py``, ``.tmuxp.json``, ``.tmuxp.yaml``.

    :rtype: list

    """
    configs = []

    for filename in os.listdir(os.getcwd()):
        if filename.startswith('.tmuxp') and is_config_file(filename):
            configs.append(filename)

    return configs


def inline(sconf):
    """ Return config in inline form, opposite of :meth:`config.expand`.

    :param sconf: unexpanded config file
    :type sconf: dict
    :rtype: dict

    """

    if ('shell_command' in sconf and isinstance(sconf['shell_command'], list) and len(sconf['shell_command']) == 1):
        sconf['shell_command'] = sconf['shell_command'][0]

        if len(sconf.keys()) == int(1):
            sconf = sconf['shell_command']
    if ('shell_command_before' in sconf and isinstance(sconf['shell_command_before'], list) and len(sconf['shell_command_before']) == 1):
        sconf['shell_command_before'] = sconf['shell_command_before'][0]

    # recurse into window and pane config items
    if 'windows' in sconf:
        sconf['windows'] = [
            inline(window) for window in sconf['windows']
        ]
    if 'panes' in sconf:
        sconf['panes'] = [inline(pane) for pane in sconf['panes']]

    return sconf


def expand(sconf, cwd=None):
    """Return config with shorthand and inline properties expanded.

    This is necessary to keep the code in the :class:`WorkspaceBuilder` clean
    and also allow for neat, short-hand configurations.

    As a simple example, internally, tmuxp expects that config options
    like ``shell_command`` are a list (array)::

        'shell_command': ['htop']

    tmuxp configs allow for it to be simply a string::

        'shell_command': 'htop'

    Kaptan will load JSON/YAML files into python dicts for you.

    :param sconf: the configuration for the session
    :type sconf: dict
    :param cwd: directory to expand relative paths against. should be the dir
                of the config directory.
    :rtype: dict

    """

    if not cwd:
        cwd = os.getcwd()
{'fraction_non_alphanumeric': 0.12282734646581692, 'fraction_numerical': 0.002317497103128621, 'mean_word_length': 3.0712264150943396, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3659404', 'n_tokens_mistral': 2661, 'n_tokens_neox': 2549, 'n_words': 858}