コード例 #1
0
class Environment(object):
    """Holds information about the execution context.

    Groups various aspects of the environment in a changeable object
    and allows for mocking.

    """

    is_windows = is_windows

    progname = os.path.basename(sys.argv[0])
    if progname not in ['http', 'https']:
        progname = 'http'

    config_dir = DEFAULT_CONFIG_DIR

    # Can be set to 0 to disable colors completely.
    colors = 256 if '256color' in os.environ.get('TERM', '') else 88

    stdin = sys.stdin
    stdin_isatty = sys.stdin.isatty()

    stdout_isatty = sys.stdout.isatty()
    stderr_isatty = sys.stderr.isatty()
    if is_windows:
        # noinspection PyUnresolvedReferences
        from colorama.initialise import wrap_stream
        stdout = wrap_stream(sys.stdout,
                             convert=None,
                             strip=None,
                             autoreset=True,
                             wrap=True)
        stderr = wrap_stream(sys.stderr,
                             convert=None,
                             strip=None,
                             autoreset=True,
                             wrap=True)
    else:
        stdout = sys.stdout
        stderr = sys.stderr

    def __init__(self, **kwargs):
        assert all(hasattr(type(self), attr) for attr in kwargs.keys())
        self.__dict__.update(**kwargs)

    @property
    def config(self):
        if not hasattr(self, '_config'):
            self._config = Config(directory=self.config_dir)
            if self._config.is_new:
                self._config.save()
            else:
                self._config.load()
        return self._config
コード例 #2
0
ファイル: output.py プロジェクト: CleanCut/green
    def __init__(self, stream, override_appveyor=False, disable_windows=False,
            disable_unidecode=False):
        self.disable_unidecode = disable_unidecode
        self.stream = stream
        # Ironically, AppVeyor doesn't support windows win32 system calls for
        # colors, but it WILL interpret posix ansi escape codes!
        on_windows = platform.system() == 'Windows'
        on_appveyor = os.environ.get('APPVEYOR', False)

        if (override_appveyor
                or ((on_windows and not on_appveyor)
                    and not disable_windows)):  # pragma: no cover
            self.stream = wrap_stream(self.stream, None, None, None, True)
            # set output is ascii-only
            self._ascii_only_output = True
        self.closed = False
        # z3 likes to look at sys.stdout.encoding
        try:
            self.encoding = stream.encoding
        except:
            self.encoding = 'UTF-8'
        # Susceptible to false-positives if other matching lines are output,
        # so set this to None immediately before running a coverage report to
        # guarantee accuracy.
        self.coverage_percent = None
コード例 #3
0
ファイル: models.py プロジェクト: simonbuchan/httpie
class Environment(object):
    """Holds information about the execution context.

    Groups various aspects of the environment in a changeable object
    and allows for mocking.

    """

    #noinspection PyUnresolvedReferences
    is_windows = is_windows

    progname = os.path.basename(sys.argv[0])
    if progname not in ['http', 'https']:
        progname = 'http'

    stdin_isatty = sys.stdin.isatty()
    stdin = sys.stdin
    stdout_isatty = sys.stdout.isatty()

    if stdout_isatty and is_windows:
        from colorama.initialise import wrap_stream
        stdout = wrap_stream(sys.stdout, convert=None,
                             strip=None, autoreset=True, wrap=True)
    else:
        stdout = sys.stdout
    stderr = sys.stderr

    # Can be set to 0 to disable colors completely.
    colors = 256 if '256color' in os.environ.get('TERM', '') else 88

    def __init__(self, **kwargs):
        assert all(hasattr(type(self), attr)
                   for attr in kwargs.keys())
        self.__dict__.update(**kwargs)
コード例 #4
0
ファイル: output.py プロジェクト: dhruvkuncha/type-master
    def __init__(self,
                 stream,
                 override_appveyor=False,
                 disable_windows=False,
                 disable_unidecode=False):
        self.disable_unidecode = disable_unidecode
        self.stream = stream
        # Ironically, AppVeyor doesn't support windows win32 system calls for
        # colors, but it WILL interpret posix ansi escape codes!
        on_windows = platform.system() == 'Windows'
        on_appveyor = os.environ.get('APPVEYOR', False)

        if (override_appveyor
                or ((on_windows and not on_appveyor)
                    and not disable_windows)):  # pragma: no cover
            self.stream = wrap_stream(self.stream, None, None, None, True)
            # set output is ascii-only
            self._ascii_only_output = True
        self.closed = False
        # z3 likes to look at sys.stdout.encoding
        try:
            self.encoding = stream.encoding
        except:
            self.encoding = 'UTF-8'
        # Susceptible to false-positives if other matching lines are output,
        # so set this to None immediately before running a coverage report to
        # guarantee accuracy.
        self.coverage_percent = None
コード例 #5
0
ファイル: wrapper.py プロジェクト: zhangf911/phpsploit
def colorama_wrap(outfile=sys.__stdout__):
    """Returns an colorama wrap file that acts as an stdout proxy
    between userspace and given output file

    """
    from colorama.initialise import wrap_stream
    return wrap_stream(outfile, None, None, False, True)
コード例 #6
0
ファイル: output.py プロジェクト: Milstein/green
 def __init__(self, stream, html=False):
     self.stream = stream
     if platform.system() == 'Windows': # pragma: no cover
         from colorama.initialise import wrap_stream
         self.stream = wrap_stream(self.stream, None, None, None, True)
     self.html = html
     self.closed = False
コード例 #7
0
def _colorama_init(autoreset=False, convert=None, strip=None, wrap=True):
    "Patch-func for `colorama` to stop wrapping STDOUT and convert ANSI seqs."
    import atexit
    from colorama import initialise

    if not wrap and any([autoreset, convert, strip]):
        raise ValueError('wrap=False conflicts with any other arg=True')

    #global wrapped_stdout, wrapped_stderr
    #global orig_stdout, orig_stderr

    #orig_stdout = sys.stdout
    initialise.orig_stderr = sys.stderr

    ## Fix https://github.com/JRCSTU/co2mpas/issues/475
    #
    #if sys.stdout is None:
    #    wrapped_stdout = None
    #else:
    #    sys.stdout = wrapped_stdout = \
    #        wrap_stream(orig_stdout, convert, strip, autoreset, wrap)
    if sys.stderr is None:
        initialise.wrapped_stderr = None
    else:
        sys.stderr = initialise.wrapped_stderr = \
            initialise.wrap_stream(initialise.orig_stderr,
                                   convert, strip, autoreset, wrap)

    #global atexit_done
    if not initialise.atexit_done:
        atexit.register(initialise.reset_all)
        initialise.atexit_done = True
コード例 #8
0
    def __init__(
        self,
        stream,
        override_appveyor=False,
        disable_windows=False,
        disable_unidecode=False,
    ):
        self.disable_unidecode = disable_unidecode
        self.stream = stream
        # Ironically, Windows CI platforms such as GitHub Actions and AppVeyor don't support windows
        # win32 system calls for colors, but it WILL interpret posix ansi escape codes! (The
        # opposite of an actual windows command prompt)
        on_windows = platform.system() == "Windows"
        on_windows_ci = os.environ.get(
            "GITHUB_ACTIONS", False) or os.environ.get("APPVEYOR", False)

        if override_appveyor or ((on_windows and not on_windows_ci)
                                 and not disable_windows):  # pragma: no cover
            self.stream = wrap_stream(self.stream, None, None, None, True)
            # set output is ascii-only
            self._ascii_only_output = True
        self.closed = False
        # z3 likes to look at sys.stdout.encoding
        try:
            self.encoding = stream.encoding
        except:
            self.encoding = "UTF-8"
        # Susceptible to false-positives if other matching lines are output,
        # so set this to None immediately before running a coverage report to
        # guarantee accuracy.
        self.coverage_percent = None
コード例 #9
0
ファイル: output.py プロジェクト: simudream/green
 def __init__(self, stream, override_appveyor=False):
     self.stream = stream
     # Ironically, AppVeyor doesn't support windows win32 system calls for
     # colors, but it WILL interpret posix ansi escape codes!
     if override_appveyor or (
             (platform.system() == 'Windows')
             and (not os.environ.get('APPVEYOR', False))): # pragma: no cover
         self.stream = wrap_stream(self.stream, None, None, None, True)
     self.closed = False
コード例 #10
0
ファイル: output.py プロジェクト: MinchinWeb/green
    def __init__(self, stream, override_appveyor=False, disable_windows=False):
        self.stream = stream
        # Ironically, AppVeyor doesn't support windows win32 system calls for
        # colors, but it WILL interpret posix ansi escape codes!
        on_windows = platform.system() == 'Windows'
        on_appveyor = os.environ.get('APPVEYOR', False)

        if (override_appveyor
                or ((on_windows and not on_appveyor)
                    and not disable_windows)):  # pragma: no cover
            self.stream = wrap_stream(self.stream, None, None, None, True)
            # set output is ascii-only
            self._ascii_only_output = True
        self.closed = False
コード例 #11
0
    def __init__(self, stream, override_appveyor=False, disable_windows=False):
        self.stream = stream
        # Ironically, AppVeyor doesn't support windows win32 system calls for
        # colors, but it WILL interpret posix ansi escape codes!
        on_windows = platform.system() == 'Windows'
        on_appveyor = os.environ.get('APPVEYOR', False)

        if (override_appveyor
                or ((on_windows and not on_appveyor)
                    and not disable_windows)):  # pragma: no cover
            self.stream = wrap_stream(self.stream, None, None, None, True)
            # set output is ascii-only
            self._ascii_only_output = True
        self.closed = False
コード例 #12
0
def wrap_stream_for_windows(
    f: io.TextIOWrapper,
) -> Union[io.TextIOWrapper, "colorama.AnsiToWin32"]:
    """
    Wrap stream with colorama's wrap_stream so colors are shown on Windows.

    If `colorama` is unavailable, the original stream is returned unmodified.
    Otherwise, the `wrap_stream()` function determines whether the stream needs
    to be wrapped for a Windows environment and will accordingly either return
    an `AnsiToWin32` wrapper or the original stream.
    """
    try:
        from colorama.initialise import wrap_stream
    except ImportError:
        return f
    else:
        # Set `strip=False` to avoid needing to modify test_express_diff_with_color.
        return wrap_stream(f, convert=None, strip=False, autoreset=False, wrap=True)
コード例 #13
0
ファイル: context.py プロジェクト: zhoule/httpie
class Environment(object):
    """
    Information about the execution context
    (standard streams, config directory, etc).

    By default, it represents the actual environment.
    All of the attributes can be overwritten though, which
    is used by the test suite to simulate various scenarios.

    """
    is_windows = is_windows
    config_dir = DEFAULT_CONFIG_DIR
    colors = 256 if '256color' in os.environ.get('TERM', '') else 88
    stdin = sys.stdin
    stdin_isatty = stdin.isatty()
    stdin_encoding = None
    stdout = sys.stdout
    stdout_isatty = stdout.isatty()
    stdout_encoding = None
    stderr = sys.stderr
    stderr_isatty = stderr.isatty()
    if is_windows:
        # noinspection PyUnresolvedReferences
        from colorama.initialise import wrap_stream
        stdout = wrap_stream(stdout,
                             convert=None,
                             strip=None,
                             autoreset=True,
                             wrap=True)
        stderr = wrap_stream(stderr,
                             convert=None,
                             strip=None,
                             autoreset=True,
                             wrap=True)

    def __init__(self, **kwargs):
        """
        Use keyword arguments to overwrite
        any of the class attributes for this instance.

        """
        assert all(hasattr(type(self), attr) for attr in kwargs.keys())
        self.__dict__.update(**kwargs)

        # Keyword arguments > stream.encoding > default utf8
        if self.stdin_encoding is None:
            self.stdin_encoding = getattr(self.stdin, 'encoding',
                                          None) or 'utf8'
        if self.stdout_encoding is None:
            actual_stdout = self.stdout
            if is_windows:
                from colorama import AnsiToWin32
                if isinstance(self.stdout, AnsiToWin32):
                    actual_stdout = self.stdout.wrapped
            self.stdout_encoding = getattr(actual_stdout, 'encoding',
                                           None) or 'utf8'

    @property
    def config(self):
        if not hasattr(self, '_config'):
            self._config = Config(directory=self.config_dir)
            if self._config.is_new():
                self._config.save()
            else:
                self._config.load()
        return self._config
コード例 #14
0
    def GenerateAnsiSequenceStream( cls,
                                    stream,
                                    preserve_ansi_escape_sequences=False,
                                    autoreset=False,
                                    do_not_modify_std_streams=False,
                                  ):
        """
        Ensures that sys.stdout and sys.stderr are configured to preserve
        (or not preserve) ansi escape sequences.
        """

        # By default, colorama initializes sys.stdout and sys.stderr to strip
        # and convert ansi escape sequences.
        cls.InitAnsiSequenceStreams()

        if not preserve_ansi_escape_sequences:
            if not isinstance(stream, cls):
                stream = cls(stream)

            yield stream
            return

        import colorama.initialise as cinit
        from colorama.ansitowin32 import AnsiToWin32

        restore_functors = []

        if do_not_modify_std_streams:
            # CallOnExit needs at least 1 functor
            restore_functors.append(lambda: None)
        else:
            # ----------------------------------------------------------------------
            def RestoreConvertor(wrapped_stream, original_convertor):
                wrapped_stream._StreamWrapper__convertor = original_convertor

            # ----------------------------------------------------------------------

            for wrapped_stream, original_stream in [ ( cinit.wrapped_stdout, cinit.orig_stdout ),
                                                     ( cinit.wrapped_stderr, cinit.orig_stderr ),
                                                   ]:
                original_convertor = wrapped_stream._StreamWraper__convertor

                if not getattr(original_convertor, "_modified", False):
                    convertor = AnsiToWin32( original_stream,
                                             strip=False,
                                             convert=False,
                                             autoreset=autoreset,
                                           )
                    convertor._modified = True

                    wrapped_stream._StreamWrapper__convertor = convertor

                    restore_functors.append(lambda wrapped_stream=wrapped_stream, original_convertor=original_convertor: RestoreConvertor(wrapped_stream, original_convertor))

            if restore_functors:
                cinit.reinit()
                restore_functors.append(cinit.reinit)

        with CallOnExit(*restore_functors):
            this_stream = None

            wrapped = getattr(stream, "_StreamWrapper__wrapped")
            if wrapped:
                if wrapped == cinit.orig_stdout:
                    this_stream = cinit.wrapped_stdout
                elif wrapped == cinit.orig_stderr:
                    this_stream = cinit.wrapped_stderr

            if this_stream is None:
                this_stream = stream

            yield StreamDecorator(cinit.wrap_stream( this_stream,
                                                     convert=False,
                                                     strip=False,
                                                     autoreset=autoreset,
                                                     wrap=True,
                                                   ))