aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/python/prompt-toolkit/py3/prompt_toolkit/input/posix_pipe.py
blob: 22dd7be6b5db73b2b103b04e86b9c29a673d6c08 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import os
from typing import ContextManager, TextIO, cast

from ..utils import DummyContext
from .base import PipeInput
from .vt100 import Vt100Input

__all__ = [
    "PosixPipeInput",
]


class PosixPipeInput(Vt100Input, PipeInput):
    """
    Input that is send through a pipe.
    This is useful if we want to send the input programmatically into the
    application. Mostly useful for unit testing.

    Usage::

        input = PosixPipeInput()
        input.send_text('inputdata')
    """

    _id = 0

    def __init__(self, text: str = "") -> None:
        self._r, self._w = os.pipe()

        class Stdin:
            encoding = "utf-8"

            def isatty(stdin) -> bool:
                return True

            def fileno(stdin) -> int:
                return self._r

        super().__init__(cast(TextIO, Stdin()))
        self.send_text(text)

        # Identifier for every PipeInput for the hash.
        self.__class__._id += 1
        self._id = self.__class__._id

    def send_bytes(self, data: bytes) -> None:
        os.write(self._w, data)

    def send_text(self, data: str) -> None:
        "Send text to the input."
        os.write(self._w, data.encode("utf-8"))

    def raw_mode(self) -> ContextManager[None]:
        return DummyContext()

    def cooked_mode(self) -> ContextManager[None]:
        return DummyContext()

    def close(self) -> None:
        "Close pipe fds."
        os.close(self._r)
        os.close(self._w)

        # We should assign `None` to 'self._r` and 'self._w',
        # The event loop still needs to know the the fileno for this input in order
        # to properly remove it from the selectors.

    def typeahead_hash(self) -> str:
        """
        This needs to be unique for every `PipeInput`.
        """
        return f"pipe-input-{self._id}"