<commit_before># -*- coding: utf-8 -*-
__author__ = 'nickl-'
from __version__ import __version__

import os
import re
import sys
import subprocess
from random import choice

import argparse
import textwrap

from .command import SearchCommand, InstallCommand, InfoCommand
from .adapters import AVAILABLE_ADAPTERS


AERO_PATH = os.path.dirname(os.path.realpath(__file__))


class ArgumentDelegate(argparse.ArgumentParser):

    pager = None

    class UsageFormatter(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
        def _get_help_string(self, action):
            action.help = textwrap.fill(re.sub('\n| +', ' ', action.help), 54).replace('Choose one', 'Choose one')
            help = super(self.__class__, self)._get_help_string(action)
            return help.replace('(default: %(default)s)', '\n\ndefault: %(default)s\n\n')

        def _format_action_invocation(self, action):
            if not action.option_strings:
                return self._metavar_formatter(action, action.dest)(1)[0]
            args_string = self._format_args(action, action.dest.upper())
            if action.nargs > 1:
                args_string = "{}\n".format(args_string)
            return '{} {}'.format(', '.join(action.option_strings), args_string)

        def _fill_text(self, text, width, indent):
            return super(self.__class__, self)._fill_text(textwrap.dedent(text), width, indent)

    def __init__(self, prog='', version=''):

        with open(os.path.join(AERO_PATH, "assets", "descrip.ascii"), "r") as file:
            content = ''.join(file.readlines())
        with open(os.path.join(AERO_PATH, "assets", "epilog.ascii"), "r") as file:
            epilog = ''.join(file.readlines())

        super(self.__class__, self).__init__(
            description=content,
            formatter_class=self.UsageFormatter,
            epilog=epilog,
            fromfile_prefix_chars='@',
        )

        self.version = prog + ' ' + version
        if '-' in self.prefix_chars:
            default_prefix = '-'
        else:
            default_prefix = self.prefix_chars[0]

        if self.version:
            self.add_argument(
                default_prefix + 'v', default_prefix * 2 + 'version',
                action='version', default=argparse.SUPPRESS,
                version=self.version,
                help="Show program's version number and exit",
            )

        self.add_argument(
            default_prefix + 'p', default_prefix * 2 + 'pager',
            help='''The pager to use for long paged displays. The default
            is based on the environment variable $PAGER, if it is
            not set, some common pagers like "less", "more", "most"
             and finally "cat" are tried, in this order.''',
            default=self.discover_pager(),
        )

        choices = list(x for x, y in AVAILABLE_ADAPTERS)

        self.add_argument(
            default_prefix + 'd', default_prefix * 2 + 'disable',
            action='append', dest='disabled',
            const='disabled',
            help='''Add the items you wish to disable to the list.
                Multiple disable arguments may be supplied.
                ''',
            default=[], choices=choices, nargs='?',
        )

        self.add_argument(
            default_prefix + 'i', default_prefix * 2 + 'invalidate-cache',
            action='store_true',
            dest='invalidate',
            help='''Clear the search cache and enquire anew from the
                package managers.''',
        )

        self.add_argument(
            default_prefix + '--', default_prefix * 2 + 'pass-through',
            dest='passthru',
            help='''Passthru arguments to be added as argumennts to the
                package manager's command execution. Enclose the arguments
                in quotes to distinguish them from others.''',
        )

        self.add_argument(
            default_prefix + 'c', default_prefix * 2 + 'completion',
            action=CompletionResponse,
            help='''Command outo completion is supported for both bash and zsh.
                The result from the completion option can be appended to your
                .profile or simply using eval.
                ex.
                `       aero --completion zsh >> ~/.profile`
                Remember to source the changes.
                To use eval you might try something like:
                ex.
                `       eval "$(aero --completion bash)"`
                ''',
            choices=['bash', 'zsh']
        )

    def discover_pager(self, pager=None):
        if not ArgumentDelegate.pager:
            try:
                pagers = [os.environ['PAGER']]
            except KeyError:
                pagers = []
            pagers += ['less', 'more', 'most', 'cat']
            if pager is not None:
                pagers = [pager] + pagers
            for pager in pagers:
                p = subprocess.Popen(
                    ["type", pager],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE).communicate()[0]
                if 'not found' not in p:
                    r = re.match('^[^/]*([/\w]*)', p).groups()[0]
                    if r:
                        ArgumentDelegate.pager = r
                        break

        return ArgumentDelegate.pager

    def convert_arg_line_to_args(self, conf):
        for arg in conf.split(','):
            yield arg

    def add_package_commands(self, cmds):
        commargs = self.add_subparsers(
            metavar='command [mngr:] package',
            title="Command arguments", action=CommandParser,
            description='''
                The aero commands are based on the typical package manager
                commands followed by the package name(s) to perform the task on.
                At least one command is required but several packages can be
                processed simultaneously.
                Use "aero cammand --help" to get further details for specific
                commands.''',
            help='''Optionally provide the specific manager to use prepended to
                the package name(s) with a colon ":" or alternatively aero will
                execute the command against all enabled package managers.
                ##choose one of the following valid aero commands:##''',
        )<commit_msg>using which instead of type because it is a bash builtin not a command like "which" this fixes #22<commit_after># -*- coding: utf-8 -*-
__author__ = 'nickl-'
from __version__ import __version__

import os
import re
import sys
import subprocess
from random import choice

import argparse
import textwrap

from .command import SearchCommand, InstallCommand, InfoCommand
from .adapters import AVAILABLE_ADAPTERS


AERO_PATH = os.path.dirname(os.path.realpath(__file__))


class ArgumentDelegate(argparse.ArgumentParser):

    pager = None

    class UsageFormatter(argparse.RawTextHelpFormatter, argparse.ArgumentDefaultsHelpFormatter):
        def _get_help_string(self, action):
            action.help = textwrap.fill(re.sub('\n| +', ' ', action.help), 54).replace('Choose one', 'Choose one')
            help = super(self.__class__, self)._get_help_string(action)
            return help.replace('(default: %(default)s)', '\n\ndefault: %(default)s\n\n')

        def _format_action_invocation(self, action):
            if not action.option_strings:
                return self._metavar_formatter(action, action.dest)(1)[0]
            args_string = self._format_args(action, action.dest.upper())
            if action.nargs > 1:
                args_string = "{}\n".format(args_string)
            return '{} {}'.format(', '.join(action.option_strings), args_string)

        def _fill_text(self, text, width, indent):
            return super(self.__class__, self)._fill_text(textwrap.dedent(text), width, indent)

    def __init__(self, prog='', version=''):

        with open(os.path.join(AERO_PATH, "assets", "descrip.ascii"), "r") as file:
            content = ''.join(file.readlines())
        with open(os.path.join(AERO_PATH, "assets", "epilog.ascii"), "r") as file:
            epilog = ''.join(file.readlines())

        super(self.__class__, self).__init__(
            description=content,
            formatter_class=self.UsageFormatter,
            epilog=epilog,
            fromfile_prefix_chars='@',
        )

        self.version = prog + ' ' + version
        if '-' in self.prefix_chars:
            default_prefix = '-'
        else:
            default_prefix = self.prefix_chars[0]

        if self.version:
            self.add_argument(
                default_prefix + 'v', default_prefix * 2 + 'version',
                action='version', default=argparse.SUPPRESS,
                version=self.version,
                help="Show program's version number and exit",
            )

        self.add_argument(
            default_prefix + 'p', default_prefix * 2 + 'pager',
            help='''The pager to use for long paged displays. The default
            is based on the environment variable $PAGER, if it is
            not set, some common pagers like "less", "more", "most"
             and finally "cat" are tried, in this order.''',
            default=self.discover_pager(),
        )

        choices = list(x for x, y in AVAILABLE_ADAPTERS)

        self.add_argument(
            default_prefix + 'd', default_prefix * 2 + 'disable',
            action='append', dest='disabled',
            const='disabled',
            help='''Add the items you wish to disable to the list.
                Multiple disable arguments may be supplied.
                ''',
            default=[], choices=choices, nargs='?',
        )

        self.add_argument(
            default_prefix + 'i', default_prefix * 2 + 'invalidate-cache',
            action='store_true',
            dest='invalidate',
            help='''Clear the search cache and enquire anew from the
                package managers.''',
        )

        self.add_argument(
            default_prefix + '--', default_prefix * 2 + 'pass-through',
            dest='passthru',
            help='''Passthru arguments to be added as argumennts to the
                package manager's command execution. Enclose the arguments
                in quotes to distinguish them from others.''',
        )

        self.add_argument(
            default_prefix + 'c', default_prefix * 2 + 'completion',
            action=CompletionResponse,
            help='''Command outo completion is supported for both bash and zsh.
                The result from the completion option can be appended to your
                .profile or simply using eval.
                ex.
                `       aero --completion zsh >> ~/.profile`
                Remember to source the changes.
                To use eval you might try something like:
                ex.
                `       eval "$(aero --completion bash)"`
                ''',
            choices=['bash', 'zsh']
        )

    def discover_pager(self, pager=None):
        if not ArgumentDelegate.pager:
            try:
                pagers = [os.environ['PAGER']]
            except KeyError:
                pagers = []
            pagers += ['less', 'more', 'most', 'cat']
            if pager is not None:
                pagers = [pager] + pagers
            for pager in pagers:
                p = subprocess.Popen(
                    ["which", pager],
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE)

                if p.wait() == 0:
                    ArgumentDelegate.pager = p.stdout.read().strip()


        return ArgumentDelegate.pager

    def convert_arg_line_to_args(self, conf):
        for arg in conf.split(','):
            yield arg

    def add_package_commands(self, cmds):
        commargs = self.add_subparsers(
            metavar='command [mngr:] package',
            title="Command arguments", action=CommandParser,
            description='''
                The aero commands are based on the typical package manager
                commands followed by the package name(s) to perform the task on.
                At least one command is required but several packages can be
                processed simultaneously.
                Use "aero cammand --help" to get further details for specific
                commands.''',
            help='''Optionally provide the specific manager to use prepended to
                the package name(s) with a colon ":" or alternatively aero will
                execute the command against all enabled package managers.
                ##choose one of the following valid aero commands:##''',
        )
{'fraction_non_alphanumeric': 0.10331872260488416, 'fraction_numerical': 0.0024264245460237947, 'mean_word_length': 1.8907239819004524, 'pattern_counts': {'":': 2, '<': 3, '<?xml version=': 0, '>': 9, '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': '3574543', 'n_tokens_mistral': 3488, 'n_tokens_neox': 3281, 'n_words': 979}