Esempio n. 1
0
    def __init__(self):
        """
        Creates a new StringPrinter with an empty print string.
        """
        Printer.__init__(self)

        self._string = ""
Esempio n. 2
0
    def __init__(self,
                 section: Section,
                 message_queue,
                 timeout=0):
        """
        Constructs a new bear.

        :param section:       The section object where bear settings are
                              contained.
        :param message_queue: The queue object for messages. Can be ``None``.
        :param timeout:       The time the bear is allowed to run. To set no
                              time limit, use 0.
        :raises TypeError:    Raised when ``message_queue`` is no queue.
        :raises RuntimeError: Raised when bear requirements are not fulfilled.
        """
        Printer.__init__(self)

        if message_queue is not None and not hasattr(message_queue, 'put'):
            raise TypeError('message_queue has to be a Queue or None.')

        self.section = section
        self.message_queue = message_queue
        self.timeout = timeout

        self.setup_dependencies()
        cp = type(self).check_prerequisites()
        if cp is not True:
            error_string = ('The bear ' + self.name +
                            ' does not fulfill all requirements.')
            if cp is not False:
                error_string += ' ' + cp

            self.err(error_string)
            raise RuntimeError(error_string)
Esempio n. 3
0
    def __init__(self,
                 log_level=LOG_LEVEL.WARNING,
                 timestamp_format='%X'):
        Printer.__init__(self)
        self.log_level = log_level

        self.logs = []
Esempio n. 4
0
File: Bear.py Progetto: yland/coala
    def __init__(self,
                 section: Section,
                 message_queue,
                 timeout=0):
        """
        Constructs a new bear.

        :param section:       The section object where bear settings are
                              contained.
        :param message_queue: The queue object for messages. Can be `None`.
        :param timeout:       The time the bear is allowed to run. To set no
                              time limit, use 0.
        :raises TypeError:    Raised when `message_queue` is no queue.
        :raises RuntimeError: Raised when bear requirements are not fulfilled.
        """
        Printer.__init__(self)
        LogPrinter.__init__(self, self)

        if message_queue is not None and not hasattr(message_queue, "put"):
            raise TypeError("message_queue has to be a Queue or None.")

        self.section = section
        self.message_queue = message_queue
        self.timeout = timeout

        cp = type(self).check_prerequisites()
        if cp is not True:
            error_string = ("The bear " + type(self).__name__ +
                            " does not fulfill all requirements.")
            if cp is not False:
                error_string += " " + cp

            self.warn(error_string)
            raise RuntimeError(error_string)
Esempio n. 5
0
    def __init__(self,
                 section: Section,
                 message_queue,
                 timeout=0):
        """
        Constructs a new bear.

        :param section:       The section object where bear settings are
                              contained.
        :param message_queue: The queue object for messages. Can be ``None``.
        :param timeout:       The time the bear is allowed to run. To set no
                              time limit, use 0.
        :raises TypeError:    Raised when ``message_queue`` is no queue.
        :raises RuntimeError: Raised when bear requirements are not fulfilled.
        """
        Printer.__init__(self)
        LogPrinter.__init__(self, self)

        if message_queue is not None and not hasattr(message_queue, "put"):
            raise TypeError("message_queue has to be a Queue or None.")

        self.section = section
        self.message_queue = message_queue
        self.timeout = timeout

        self.setup_dependencies()
        cp = type(self).check_prerequisites()
        if cp is not True:
            error_string = ("The bear " + self.name +
                            " does not fulfill all requirements.")
            if cp is not False:
                error_string += " " + cp

            self.warn(error_string)
            raise RuntimeError(error_string)
Esempio n. 6
0
    def __init__(self,
                 log_level=LOG_LEVEL.WARNING,
                 timestamp_format="%X"):
        Printer.__init__(self)
        LogPrinter.__init__(self, self, log_level, timestamp_format)

        self.logs = []
Esempio n. 7
0
    def __init__(self):
        """
        Creates a new StringPrinter with an empty print string.
        """
        Printer.__init__(self)

        self._string = ""
Esempio n. 8
0
    def __init__(self, print_colored=None):
        """
        Creates a new ColorPrinter.

        :param print_colored: Can be set to False to use uncolored printing
                              only. If None prints colored only when supported.
        """
        Printer.__init__(self)

        self.print_colored = print_colored
Esempio n. 9
0
    def __init__(self,
                 section: Section,
                 message_queue,
                 timeout=0):
        Printer.__init__(self)
        LogPrinter.__init__(self, self)

        if not hasattr(message_queue, "put") and message_queue is not None:
            raise TypeError("message_queue has to be a Queue or None.")

        self.section = section
        self.message_queue = message_queue
        self.timeout = timeout
Esempio n. 10
0
    def __init__(self, filehandle):
        """
        Creates a new FilePrinter. If the directory of the given file doesn't
        exist or if there's any access problems, an exception will be thrown.

        :param filehandle: A file-like object to put the data into. It's write
                           method will be invoked.
        """
        Printer.__init__(self)

        if not hasattr(filehandle, "write"):
            raise TypeError("filehandle must be a file like object " "i.e. provide a write method.")

        self.file = filehandle
Esempio n. 11
0
    def __init__(self, filehandle):
        """
        Creates a new FilePrinter. If the directory of the given file doesn't
        exist or if there's any access problems, an exception will be thrown.

        :param filehandle: A file-like object to put the data into. It's write
                           method will be invoked.
        """
        Printer.__init__(self)

        if not hasattr(filehandle, "write"):
            raise TypeError("filehandle must be a file like object "
                            "i.e. provide a write method.")

        self.file = filehandle
Esempio n. 12
0
def ask_yes_no(question,
               default=None,
               printer: Printer = None):
    """
    Asks the user a yes/no question until the user gives a clear answer,
    and returns a boolean value representing the answer.

    :param question:
        String to be used as question.
    :param default:
        The default answer to be returned if the user gives a void answer
        to the question. It must be one of ('yes', 'no', None).
    :param printer:
        The printer object used for console interactions. If this is not
        given, it defaults to a ``ConsolePrinter`` which prints outputs to
        the console.
    :return:
        True if the user input is one of coala-utils.Constants.TRUE_STRING,
        False if the user input is one of coala-utils.Constant.FALSE_STRING.
        The user input is case insensitive.
    """
    if printer is None:
        printer = ConsolePrinter()

    if default is None:
        prompt = ' [y/n] '
    elif default == 'yes':
        prompt = ' [Y/n] '
    elif default == 'no':
        prompt = ' [y/N] '
    else:
        raise ValueError('Invalid default answer: %s' % default)

    while True:
        printer.print(question + prompt, color='yellow', end=' ')
        answer = input().lower().strip()

        if default and len(answer) == 0:
            answer = default

        if answer in TRUE_STRINGS:
            return True
        elif answer in FALSE_STRINGS:
            return False
        else:
            printer.print('Invalid answer, please try again.', color='red')
Esempio n. 13
0
    def __init__(self):
        """
        Raises EnvironmentError if VoiceOutput is impossible.
        """
        Printer.__init__(self)
        ClosableObject.__init__(self)
        # TODO retrieve language from get_locale and select appropriate voice

        try:
            self.espeak = subprocess.Popen(['espeak'], stdin=subprocess.PIPE)
        except OSError:  # pragma: no cover
            print("eSpeak doesn't seem to be installed. You cannot use the "
                  "voice output feature without eSpeak. It can be downloaded"
                  " from http://espeak.sourceforge.net/ or installed via "
                  "your usual package repositories.")
            raise EnvironmentError
        except:  # pragma: no cover
            print("Failed to execute eSpeak. An unknown error occurred.",
                  Constants.THIS_IS_A_BUG)
            raise EnvironmentError
Esempio n. 14
0
    def __init__(self):
        """
        :raises EnvironmentError: If VoiceOutput is impossible.
        """
        Printer.__init__(self)
        ClosableObject.__init__(self)
        # TODO retrieve language from get_locale and select appropriate voice

        try:
            self.espeak = subprocess.Popen(['espeak'], stdin=subprocess.PIPE)
        except OSError:  # pragma: no cover
            print("eSpeak doesn't seem to be installed. You cannot use the "
                  "voice output feature without eSpeak. It can be downloaded"
                  " from http://espeak.sourceforge.net/ or installed via "
                  "your usual package repositories.")
            raise EnvironmentError
        except subprocess.SubprocessError:  # pragma: no cover
            print("Failed to execute eSpeak. An unknown error occurred. "
                  "This is a bug. We are sorry for the inconvenience. "
                  "Please contact the developers for assistance.")
            raise EnvironmentError
Esempio n. 15
0
    def __init__(self):
        """
        :raises EnvironmentError: If VoiceOutput is impossible.
        """
        Printer.__init__(self)
        ClosableObject.__init__(self)
        # TODO retrieve language from get_locale and select appropriate voice

        try:
            self.espeak = subprocess.Popen(['espeak'], stdin=subprocess.PIPE)
        except OSError:  # pragma: no cover
            print("eSpeak doesn't seem to be installed. You cannot use the "
                  "voice output feature without eSpeak. It can be downloaded"
                  " from http://espeak.sourceforge.net/ or installed via "
                  "your usual package repositories.")
            raise EnvironmentError
        except subprocess.SubprocessError:  # pragma: no cover
            print("Failed to execute eSpeak. An unknown error occurred. "
                  "This is a bug. We are sorry for the inconvenience. "
                  "Please contact the developers for assistance.")
            raise EnvironmentError
Esempio n. 16
0
    def __init__(self,
                 section: Section,
                 message_queue,
                 timeout=0):
        """
        Constructs a new bear.

        :param section:       The section object where bear settings are
                              contained.
        :param message_queue: The queue object for messages. Can be ``None``.
        :param timeout:       The time the bear is allowed to run. To set no
                              time limit, use 0.
        :raises TypeError:    Raised when ``message_queue`` is no queue.
        :raises RuntimeError: Raised when bear requirements are not fulfilled.
        """
        Printer.__init__(self)

        if message_queue is not None and not hasattr(message_queue, 'put'):
            raise TypeError('message_queue has to be a Queue or None.')

        self.section = section
        self.message_queue = message_queue
        self.timeout = timeout
        self.debugger = _is_debugged(bear=self)
        self.profile = _is_profiled(bear=self)

        if self.profile and self.debugger:
            raise ValueError(
                'Cannot run debugger and profiler at the same time.')

        self.setup_dependencies()
        cp = type(self).check_prerequisites()
        if cp is not True:
            error_string = ('The bear ' + self.name +
                            ' does not fulfill all requirements.')
            if cp is not False:
                error_string += ' ' + cp

            self.err(error_string)
            raise RuntimeError(error_string)
Esempio n. 17
0
def ask_question(question,
                 default=None,
                 printer: Printer = None,
                 typecast=str,
                 **kwargs):
    """
    Asks the user a question and returns the answer.

    :param question:
        String to be used as question.
    :param default:
        The default answer to be returned if the user gives a void answer
        to the question.
    :param printer:
        The printer object used for console interactions. If this is not
        given, it defaults to a ``ConsolePrinter`` which prints outputs to
        the console.
    :param typecast:
        Type to cast the input to. Defaults to a ``str``.
    :param kwargs:
        The additional keyword arguments are held for backwards compatibility
        and for future use with the ``prompt_toolkit``.
    :return:
        The response from the user.
    """
    if printer is None:
        printer = ConsolePrinter()

    while True:
        printer.print(question, color="yellow", end=" ")
        if default:
            printer.print("[" + default + "]", end=" ")
        printer.print("")

        answer = input()
        if default and len(answer) == 0:
            answer = default

        try:
            answer = typecast(StringConverter(answer))
        except BaseException as e:
            printer.print(
                str(e) + "\nPlease enter a valid answer.",
                color="blue")
        else:
            return answer
Esempio n. 18
0
 def __init__(self):
     """
     Instantiates a new NullPrinter.
     """
     Printer.__init__(self)
Esempio n. 19
0
    def __init__(self, log_level=LOG_LEVEL.WARNING, timestamp_format="%X"):
        Printer.__init__(self)
        LogPrinter.__init__(self, self, log_level, timestamp_format)

        self.logs = []
Esempio n. 20
0
 def test_get_printer(self):
     self.assertIs(LogPrinter(None).printer, None)
     printer = Printer()
     self.assertIs(LogPrinter(printer).printer, printer)
Esempio n. 21
0
 def test_interface(self):
     uut = LogPrinter(Printer())
     self.assertRaises(NotImplementedError,
                       uut.log_message,
                       self.log_message)
Esempio n. 22
0
 def __init__(self):
     """
     Instantiates a new NullPrinter.
     """
     Printer.__init__(self)