Skip to content

Commit

Permalink
Only emit color messages when stdout is a tty
Browse files Browse the repository at this point in the history
Fixes #213.
  • Loading branch information
jengelh committed Nov 12, 2018
1 parent 76ef782 commit 6378bcd
Showing 1 changed file with 14 additions and 15 deletions.
29 changes: 14 additions & 15 deletions TarSCM/scm/git.py
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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)
Expand All @@ -214,15 +217,14 @@ def check_ancestry(self, parent_tag):
self.clone_dir
)
if rcode:
sys.exit("\033[31m`git rev-parse " + parent_tag + "` failed: " +
tgcommit + "\033[0m")
sys.exit(color_red("`git rev-parse " + parent_tag + "` failed: " +
tgcommit))
rcode, head = self.helpers.run_cmd(
["git", "rev-parse", "HEAD"],
self.clone_dir
)
if rcode:
sys.exit("\033[31m`git rev-parse HEAD` failed: " +
head + "\033[0m")
sys.exit(color_red("`git rev-parse HEAD` failed: " + head))
rcode, mgbase = self.helpers.run_cmd(
["git", "merge-base", parent_tag, "HEAD"],
self.clone_dir
Expand All @@ -231,14 +233,13 @@ def check_ancestry(self, parent_tag):
head = head.strip()
mgbase = mgbase.strip()
if mgbase != tgcommit:
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."))

def _detect_version_tag_offset(self, parent_tag, versionformat):
if not parent_tag:
sys.exit("\033[31m@TAG_OFFSET@ cannot be expanded, "
"as no parent tag was discovered.\033[0m")

sys.exit(color_red("@TAG_OFFSET@ cannot be expanded, as no " +
"parent tag was discovered."))
self.check_ancestry(parent_tag)
rcode, output = self.helpers.run_cmd(
self._get_scm_cmd() + ['rev-list', '--count', parent_tag +
Expand All @@ -247,9 +248,7 @@ def _detect_version_tag_offset(self, parent_tag, versionformat):
)

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,
Expand Down

0 comments on commit 6378bcd

Please sign in to comment.