From 367ced2eef38baa70f2fde4a2e034d1bdf18fe85 Mon Sep 17 00:00:00 2001 From: Ivan Habunek Date: Thu, 5 Sep 2019 22:35:29 +0200 Subject: [PATCH] Don't use ANSI color codes when not desired Which is when not supported by terminal or when not in a tty. --- changelog.yaml | 1 + toot/output.py | 25 +++++++++++++++++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/changelog.yaml b/changelog.yaml index 2de5412..ea78971 100644 --- a/changelog.yaml +++ b/changelog.yaml @@ -2,6 +2,7 @@ 0.24.0: date: TBA changes: + - "CLI: Don't use ANSI colors if not supported by terminal or when not in a tty" - "TUI: Implement deleting own status messages" 0.23.1: diff --git a/toot/output.py b/toot/output.py index 2a52e77..7fbe87a 100644 --- a/toot/output.py +++ b/toot/output.py @@ -1,7 +1,8 @@ # -*- coding: utf-8 -*- -import sys +import os import re +import sys from datetime import datetime from textwrap import wrap @@ -46,7 +47,27 @@ def strip_tags(text): return text -USE_ANSI_COLOR = "--no-color" not in sys.argv +def use_ansi_color(): + """Returns True if ANSI color codes should be used.""" + + # Windows doesn't support color unless ansicon is installed + # See: http://adoxa.altervista.org/ansicon/ + if sys.platform == 'win32' and 'ANSICON' not in os.environ: + return False + + # Don't show color if stdout is not a tty, e.g. if output is piped on + if not sys.stdout.isatty(): + return False + + # Don't show color if explicitly specified in options + if "--no-color" in sys.argv: + return False + + return True + + +USE_ANSI_COLOR = use_ansi_color() + QUIET = "--quiet" in sys.argv