From 8a6c26a650c07c3cf0c72b382428a418d2b078aa Mon Sep 17 00:00:00 2001 From: Jan Engelhardt Date: Thu, 21 Jun 2018 16:04:45 +0200 Subject: [PATCH] Only emit color messages when stdout is a tty Fixes #213. --- TarSCM/scm/git.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/TarSCM/scm/git.py b/TarSCM/scm/git.py index eed4df87..268fff2d 100644 --- a/TarSCM/scm/git.py +++ b/TarSCM/scm/git.py @@ -6,6 +6,10 @@ from TarSCM.scm.base import Scm +def color_red(s): + if not os.isatty(1): + return s + return "\033[0;31m" + s + "\033[0m" class Git(Scm): scm = 'git' @@ -200,9 +204,8 @@ def _detect_parent_tag(self, args): def _detect_version_parent_tag(self, parent_tag, versionformat): # noqa pylint: disable=no-self-use if not parent_tag: - sys.exit("\033[31mNo parent tag present for the checked out " - "revision, thus @PARENT_TAG@ cannot be expanded." - "\033[0m") + sys.exit(color_red("No parent tag present for the checked out " + "revision, thus @PARENT_TAG@ cannot be expanded.")) versionformat = re.sub('@PARENT_TAG@', parent_tag, versionformat) @@ -218,17 +221,15 @@ def _detect_version_tag_offset(self, parent_tag, versionformat): self.clone_dir ) if rcode != 0: - sys.exit("\033[31mparent_tag is not an ancestor of HEAD. " + - "Cannot compute a (meaningful) distance.\033[0m") + sys.exit(color_red("parent_tag is not an ancestor of HEAD. " + + "Cannot compute a (meaningful) distance.")) cmd = self._get_scm_cmd() cmd.extend(['rev-list', '--count', parent_tag + '..HEAD']) rcode, out = self.helpers.run_cmd(cmd, self.clone_dir) if rcode: - msg = "\033[31m@TAG_OFFSET@ can not be expanded: %s\033[0m" - msg.format(out) - sys.exit(msg) + sys.exit(color_red("@TAG_OFFSET@ can not be expanded: " + output)) tag_offset = out.strip() versionformat = re.sub('@TAG_OFFSET@', tag_offset,