Skip to content

Commit f4978fd

Browse files
committed
send notifications to stderr. use colorization on stdout or stderr only if a tty
1 parent e5302af commit f4978fd

File tree

1 file changed

+55
-42
lines changed

1 file changed

+55
-42
lines changed

pythonforandroid/toolchain.py

Lines changed: 55 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@
99
from __future__ import print_function
1010

1111
import sys
12-
from sys import stdout, platform
12+
from sys import stdout, stderr, platform
1313
from os.path import (join, dirname, realpath, exists, isdir, basename,
1414
expanduser)
1515
from os import listdir, unlink, makedirs, environ, chdir, getcwd, walk, uname
@@ -42,16 +42,29 @@
4242
import argparse
4343
from appdirs import user_data_dir
4444
import sh
45-
if sys.stdout.isatty():
46-
from colorama import Style, Fore
45+
46+
from colorama import Style as Colo_Style, Fore as Colo_Fore
47+
from collections import defaultdict
48+
class colorama_shim(object):
49+
def __init__(self):
50+
self._dict = defaultdict(str)
51+
def __getattr__(self, key):
52+
return self._dict[key]
53+
Null_Style = Null_Fore = colorama_shim()
54+
55+
if stdout.isatty():
56+
Out_Style = Colo_Style
57+
Out_Fore = Colo_Fore
58+
else:
59+
Out_Style = Null_Style
60+
Out_Fore = Null_Fore
61+
62+
if stderr.isatty():
63+
Err_Style = Colo_Style
64+
Err_Fore = Colo_Fore
4765
else:
48-
from collections import defaultdict
49-
class colorama_shim(object):
50-
def __init__(self):
51-
self._dict = defaultdict(str)
52-
def __getattr__(self, key):
53-
return self._dict[key]
54-
Style = Fore = colorama_shim()
66+
Err_Style = Null_Style
67+
Err_Fore = Null_Fore
5568

5669
user_dir = dirname(realpath(os.path.curdir))
5770
toolchain_dir = dirname(__file__)
@@ -64,13 +77,13 @@ class LevelDifferentiatingFormatter(logging.Formatter):
6477
def format(self, record):
6578
if record.levelno > 20:
6679
record.msg = '{}{}[WARNING]{}{}: '.format(
67-
Style.BRIGHT, Fore.RED, Fore.RESET, Style.RESET_ALL) + record.msg
80+
Err_Style.BRIGHT, Err_Fore.RED, Err_Fore.RESET, Err_Style.RESET_ALL) + record.msg
6881
elif record.levelno > 10:
6982
record.msg = '{}[INFO]{}: '.format(
70-
Style.BRIGHT, Style.RESET_ALL) + record.msg
83+
Err_Style.BRIGHT, Err_Style.RESET_ALL) + record.msg
7184
else:
7285
record.msg = '{}{}[DEBUG]{}{}: '.format(
73-
Style.BRIGHT, Fore.LIGHTBLACK_EX, Fore.RESET, Style.RESET_ALL) + record.msg
86+
Err_Style.BRIGHT, Err_Fore.LIGHTBLACK_EX, Err_Fore.RESET, Err_Style.RESET_ALL) + record.msg
7487
return super(LevelDifferentiatingFormatter, self).format(record)
7588

7689
logger = logging.getLogger('p4a')
@@ -79,7 +92,7 @@ def format(self, record):
7992
# handler and reset the level
8093
logger.setLevel(logging.INFO)
8194
logger.touched = True
82-
ch = logging.StreamHandler(stdout) if sys.stdout.isatty() else logging.NullHandler()
95+
ch = logging.StreamHandler(stderr)
8396
formatter = LevelDifferentiatingFormatter('%(message)s')
8497
ch.setFormatter(formatter)
8598
logger.addHandler(ch)
@@ -90,20 +103,20 @@ def format(self, record):
90103

91104
IS_PY3 = sys.version_info[0] >= 3
92105

93-
info(''.join([Style.BRIGHT, Fore.RED,
106+
info(''.join([Err_Style.BRIGHT, Err_Fore.RED,
94107
'This python-for-android revamp is an experimental alpha release!',
95-
Style.RESET_ALL]))
96-
info(''.join([Fore.RED,
108+
Err_Style.RESET_ALL]))
109+
info(''.join([Err_Fore.RED,
97110
('It should work (mostly), but you may experience '
98111
'missing features or bugs.'),
99-
Style.RESET_ALL]))
112+
Err_Style.RESET_ALL]))
100113

101114
def info_main(*args):
102-
logger.info(''.join([Style.BRIGHT, Fore.GREEN] + list(args) +
103-
[Style.RESET_ALL, Fore.RESET]))
115+
logger.info(''.join([Err_Style.BRIGHT, Err_Fore.GREEN] + list(args) +
116+
[Err_Style.RESET_ALL, Err_Fore.RESET]))
104117

105118
def info_notify(s):
106-
info('{}{}{}{}'.format(Style.BRIGHT, Fore.LIGHTBLUE_EX, s, Style.RESET_ALL))
119+
info('{}{}{}{}'.format(Err_Style.BRIGHT, Err_Fore.LIGHTBLUE_EX, s, Err_Style.RESET_ALL))
107120

108121
def pretty_log_dists(dists, log_func=info):
109122
infos = []
@@ -112,7 +125,7 @@ def pretty_log_dists(dists, log_func=info):
112125
'includes recipes ({Fore.GREEN}{recipes}'
113126
'{Style.RESET_ALL})'.format(
114127
name=dist.name, recipes=', '.join(dist.recipes),
115-
Fore=Fore, Style=Style))
128+
Fore=Err_Fore, Style=Err_Style))
116129

117130
for line in infos:
118131
log_func('\t' + line)
@@ -135,15 +148,15 @@ def shprint(command, *args, **kwargs):
135148
short_string = string
136149
if len(string) > 100:
137150
short_string = string[:100] + '... (and {} more)'.format(len(string) - 100)
138-
logger.info(short_string + Style.RESET_ALL)
151+
logger.info(short_string + Err_Style.RESET_ALL)
139152
else:
140-
logger.debug(string + Style.RESET_ALL)
153+
logger.debug(string + Err_Style.RESET_ALL)
141154

142155
output = command(*args, **kwargs)
143156
need_closing_newline = False
144157
for line in output:
145158
if logger.level > logging.DEBUG:
146-
string = ''.join([Style.RESET_ALL, '\r', ' '*11, 'working ... ',
159+
string = ''.join([Err_Style.RESET_ALL, '\r', ' '*11, 'working ... ',
147160
line[:100].replace('\n', '').rstrip(), ' ...'])
148161
if len(string) < 20:
149162
continue
@@ -225,12 +238,12 @@ def is_exe(fpath):
225238
@contextlib.contextmanager
226239
def current_directory(new_dir):
227240
cur_dir = getcwd()
228-
logger.info(''.join((Fore.CYAN, '-> directory context ', new_dir,
229-
Fore.RESET)))
241+
logger.info(''.join((Err_Fore.CYAN, '-> directory context ', new_dir,
242+
Err_Fore.RESET)))
230243
chdir(new_dir)
231244
yield
232-
logger.info(''.join((Fore.CYAN, '<- directory context ', cur_dir,
233-
Fore.RESET)))
245+
logger.info(''.join((Err_Fore.CYAN, '<- directory context ', cur_dir,
246+
Err_Fore.RESET)))
234247
chdir(cur_dir)
235248

236249

@@ -2606,13 +2619,13 @@ def recipes(self, args):
26062619
print('{Fore.BLUE}{Style.BRIGHT}{recipe.name:<12} '
26072620
'{Style.RESET_ALL}{Fore.LIGHTBLUE_EX}'
26082621
'{version:<8}{Style.RESET_ALL}'.format(
2609-
recipe=recipe, Fore=Fore, Style=Style,
2622+
recipe=recipe, Fore=Out_Fore, Style=Out_Style,
26102623
version=version))
26112624
print(' {Fore.GREEN}depends: {recipe.depends}'
2612-
'{Fore.RESET}'.format(recipe=recipe, Fore=Fore))
2625+
'{Fore.RESET}'.format(recipe=recipe, Fore=Out_Fore))
26132626
if recipe.conflicts:
26142627
print(' {Fore.RED}conflicts: {recipe.conflicts}'
2615-
'{Fore.RESET}'.format(recipe=recipe, Fore=Fore))
2628+
'{Fore.RESET}'.format(recipe=recipe, Fore=Out_Fore))
26162629
else:
26172630
print("{recipe.name:<12} {recipe.version:<8}".format(
26182631
recipe=recipe))
@@ -2624,9 +2637,9 @@ def bootstraps(self, args):
26242637
for bs in Bootstrap.list_bootstraps():
26252638
bs = Bootstrap.get_bootstrap(bs, self.ctx)
26262639
print('{Fore.BLUE}{Style.BRIGHT}{bs.name}{Style.RESET_ALL}'.format(
2627-
bs=bs, Fore=Fore, Style=Style))
2640+
bs=bs, Fore=Out_Fore, Style=Out_Style))
26282641
print(' {Fore.GREEN}depends: {bs.recipe_depends}{Fore.RESET}'.format(
2629-
bs=bs, Fore=Fore))
2642+
bs=bs, Fore=Out_Fore))
26302643

26312644
def clean_all(self, args):
26322645
'''Delete all build components; the package cache, package builds,
@@ -2852,11 +2865,11 @@ def distributions(self, args):
28522865

28532866
if dists:
28542867
print('{Style.BRIGHT}Distributions currently installed are:'
2855-
'{Style.RESET_ALL}'.format(Style=Style, Fore=Fore))
2868+
'{Style.RESET_ALL}'.format(Style=Out_Style, Fore=Out_Fore))
28562869
pretty_log_dists(dists, print)
28572870
else:
28582871
print('{Style.BRIGHT}There are no dists currently built.'
2859-
'{Style.RESET_ALL}'.format(Style=Style))
2872+
'{Style.RESET_ALL}'.format(Style=Out_Style))
28602873

28612874
def delete_dist(self, args):
28622875
dist = self._dist
@@ -2915,24 +2928,24 @@ def logcat(self, args):
29152928
def build_status(self, args):
29162929

29172930
print('{Style.BRIGHT}Bootstraps whose core components are probably already built:'
2918-
'{Style.RESET_ALL}'.format(Style=Style))
2931+
'{Style.RESET_ALL}'.format(Style=Out_Style))
29192932
for filen in os.listdir(join(self.ctx.build_dir, 'bootstrap_builds')):
29202933
print(' {Fore.GREEN}{Style.BRIGHT}{filen}{Style.RESET_ALL}'.format(
2921-
filen=filen, Fore=Fore, Style=Style))
2934+
filen=filen, Fore=Out_Fore, Style=Out_Style))
29222935

29232936
print('{Style.BRIGHT}Recipes that are probably already built:'
2924-
'{Style.RESET_ALL}'.format(Style=Style))
2937+
'{Style.RESET_ALL}'.format(Style=Out_Style))
29252938
if exists(join(self.ctx.build_dir, 'other_builds')):
29262939
for filen in sorted(os.listdir(join(self.ctx.build_dir, 'other_builds'))):
29272940
name = filen.split('-')[0]
29282941
dependencies = filen.split('-')[1:]
29292942
recipe_str = (' {Style.BRIGHT}{Fore.GREEN}{name}'
29302943
'{Style.RESET_ALL}'.format(
2931-
Style=Style, name=name, Fore=Fore))
2944+
Style=Out_Style, name=name, Fore=Out_Fore))
29322945
if dependencies:
29332946
recipe_str += (' ({Fore.BLUE}with ' + ', '.join(dependencies) +
2934-
'{Fore.RESET})').format(Fore=Fore)
2935-
recipe_str += '{Style.RESET_ALL}'.format(Style=Style)
2947+
'{Fore.RESET})').format(Fore=Out_Fore)
2948+
recipe_str += '{Style.RESET_ALL}'.format(Style=Out_Style)
29362949
print(recipe_str)
29372950

29382951

0 commit comments

Comments
 (0)