<commit_before>
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
from scriptcore.console.basescript import BaseScript
from scriptcore.console.output.output import Output
from scriptcore.console.input.input import Input
from scriptcore.console.command import Command
from scriptcore.process.execute import Execute
from scriptcore.console.option import Option
import sys
import types


class CuiScript(BaseScript):

    __metaclass__ = ABCMeta

    def __init__(self, base_path, title, description, arguments=None):
        """
        Construct the script
        :param base_path:   The base path
        :param title:       The title
        :param description: The description
        :param arguments:   The arguments
        """

        super(CuiScript, self).__init__(base_path)

        self._title = title
        self._description = description
        self._arguments = arguments if arguments is not None else sys.argv[1::]
        self._analyzed_arguments = False

        self.output = Output()
        self.input = Input()
        self.execute = Execute()
        self._commands = {}
        self._options = {}

    def _analyze_arguments(self):
        """
        Analyze the arguments
        :return:    void
        """

        # Reset
        for option in self._options.values():
            option.reset()
        for command in self._commands.values():
            command.reset()

        # Loop arguments
        last_option = None
        for i in range(0, len(self._arguments)):
            argument = self._arguments[i]

            # Check commands
            for command in self._commands.values():
                if command.command == argument:
                    command.arguments = self._arguments[i + 1::]
                    command.given = True
                    return

            # Check long options
            if argument[:2] == '--':
                option_given = False
                for option in self._options.values():
                    if option.long == argument[2:]:
                        option.given = True
                        last_option = option
                        option_given = True
                        break
                if not option_given:
                    raise RuntimeError('Unknown option "%s" given' % argument)

            elif argument[:1] == '-':
                option_given = False
                for option in self._options.values():
                    if option.short == argument[1:]:
                        option.given = True
                        last_option = option
                        option_given = True
                        break
                if not option_given:
                    raise RuntimeError('Unknown option "%s" given' % argument)

            elif last_option:
                last_option.add_value(argument)

            else:
                raise RuntimeError('Unknown command "%s" given' % argument)

    def _has_option(self, short):
        """
        Check if has option
        :param short:   Short option
        :return:        Has option
        """

        return self._options[short].given

    def _get_option(self, short):
        """
        Get option value
        :param short:   Short option
        :return:        The value
        """

        return self._options[short].value

    def run(self):
        """
        Run the script
        """

        try:
            self._analyze_arguments()

            for command in self._commands.values():
                if command.given:
                    if type(command.callback) == types.FunctionType:
                        command.callback(arguments=command.arguments)
                    else:
                        subcommand = command.callback(self._base_path, arguments=command.arguments)
                        subcommand.run()
                    return

            self.help()

        except Exception as e:
            self.output(e, 'error')
            self.output('')

    def _register_command(self, command, description, callback):
        """
        Register a command
        :param command:     Command to type
        :param description: Description
        :param callback:    Callback function
        :return:            void
        """

        self._commands[command] = Command(command, description, callback)

    def _register_option(self, short, description, default=None, long=None):
        """
        Register an option
        :param short:       Option in short
        :param description: Description<commit_msg>Separated run and _run. Better error-handling.<commit_after>
from __future__ import absolute_import
from abc import ABCMeta, abstractmethod
from scriptcore.console.basescript import BaseScript
from scriptcore.console.output.output import Output
from scriptcore.console.input.input import Input
from scriptcore.console.command import Command
from scriptcore.process.execute import Execute
from scriptcore.console.option import Option
import sys
import types


class CuiScript(BaseScript):

    __metaclass__ = ABCMeta

    def __init__(self, base_path, title, description, arguments=None):
        """
        Construct the script
        :param base_path:   The base path
        :param title:       The title
        :param description: The description
        :param arguments:   The arguments
        """

        super(CuiScript, self).__init__(base_path)

        self._title = title
        self._description = description
        self._arguments = arguments if arguments is not None else sys.argv[1::]
        self._analyzed_arguments = False

        self.output = Output()
        self.input = Input()
        self.execute = Execute()
        self._commands = {}
        self._options = {}

    def _analyze_arguments(self):
        """
        Analyze the arguments
        :return:    void
        """

        # Reset
        for option in self._options.values():
            option.reset()
        for command in self._commands.values():
            command.reset()

        # Loop arguments
        last_option = None
        for i in range(0, len(self._arguments)):
            argument = self._arguments[i]

            # Check commands
            for command in self._commands.values():
                if command.command == argument:
                    command.arguments = self._arguments[i + 1::]
                    command.given = True
                    return

            # Check long options
            if argument[:2] == '--':
                option_given = False
                for option in self._options.values():
                    if option.long == argument[2:]:
                        option.given = True
                        last_option = option
                        option_given = True
                        break
                if not option_given:
                    raise RuntimeError('Unknown option "%s" given' % argument)

            elif argument[:1] == '-':
                option_given = False
                for option in self._options.values():
                    if option.short == argument[1:]:
                        option.given = True
                        last_option = option
                        option_given = True
                        break
                if not option_given:
                    raise RuntimeError('Unknown option "%s" given' % argument)

            elif last_option:
                last_option.add_value(argument)

            else:
                raise RuntimeError('Unknown command "%s" given' % argument)

    def _has_option(self, short):
        """
        Check if has option
        :param short:   Short option
        :return:        Has option
        """

        return self._options[short].given

    def _get_option(self, short):
        """
        Get option value
        :param short:   Short option
        :return:        The value
        """

        return self._options[short].value

    def run(self):
        """
        Run the script
        """

        try:
            self._analyze_arguments()
            self._run()

        except KeyboardInterrupt:
            sys.exit(1)

        except Exception as e:
            self.output('Error: %s' % e, 'error')
            self.output('')

    def _run(self):
        """
        Actually run the script
        """

        for command in self._commands.values():
            if command.given:
                if type(command.callback) == types.FunctionType:
                    command.callback(arguments=command.arguments)
                else:
                    subcommand = command.callback(self._base_path, arguments=command.arguments)
                    subcommand.run()
                return

        self.help()

    def _register_command(self, command, description, callback):
        """
        Register a command
        :param command:     Command to type
        :param description: Description
        :param callback:    Callback function
        :return:            void
        """

        self._commands[command] = Command(command, description, callback)

    def _register_option(self, short, description, default=None, long=None):
        """
        Register an option
        :param short:       Option in short
        :param description: Description
{'fraction_non_alphanumeric': 0.0811532301121196, 'fraction_numerical': 0.001601708489054992, 'mean_word_length': 1.5646221248630887, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, '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': '1055789', 'n_tokens_mistral': 2272, 'n_tokens_neox': 2126, 'n_words': 634}