Skip to content

Commit b1abecb

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

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
@@ -41,16 +41,29 @@
4141
import argparse
4242
from appdirs import user_data_dir
4343
import sh
44-
if sys.stdout.isatty():
45-
from colorama import Style, Fore
44+
45+
from colorama import Style as Colo_Style, Fore as Colo_Fore
46+
from collections import defaultdict
47+
class colorama_shim(object):
48+
def __init__(self):
49+
self._dict = defaultdict(str)
50+
def __getattr__(self, key):
51+
return self._dict[key]
52+
Null_Style = Null_Fore = colorama_shim()
53+
54+
if stdout.isatty():
55+
Out_Style = Colo_Style
56+
Out_Fore = Colo_Fore
57+
else:
58+
Out_Style = Null_Style
59+
Out_Fore = Null_Fore
60+
61+
if stderr.isatty():
62+
Err_Style = Colo_Style
63+
Err_Fore = Colo_Fore
4664
else:
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-
Style = Fore = colorama_shim()
65+
Err_Style = Null_Style
66+
Err_Fore = Null_Fore
5467

5568
user_dir = dirname(realpath(os.path.curdir))
5669
toolchain_dir = dirname(__file__)
@@ -63,13 +76,13 @@ class LevelDifferentiatingFormatter(logging.Formatter):
6376
def format(self, record):
6477
if record.levelno > 20:
6578
record.msg = '{}{}[WARNING]{}{}: '.format(
66-
Style.BRIGHT, Fore.RED, Fore.RESET, Style.RESET_ALL) + record.msg
79+
Err_Style.BRIGHT, Err_Fore.RED, Err_Fore.RESET, Err_Style.RESET_ALL) + record.msg
6780
elif record.levelno > 10:
6881
record.msg = '{}[INFO]{}: '.format(
69-
Style.BRIGHT, Style.RESET_ALL) + record.msg
82+
Err_Style.BRIGHT, Err_Style.RESET_ALL) + record.msg
7083
else:
7184
record.msg = '{}{}[DEBUG]{}{}: '.format(
72-
Style.BRIGHT, Fore.LIGHTBLACK_EX, Fore.RESET, Style.RESET_ALL) + record.msg
85+
Err_Style.BRIGHT, Err_Fore.LIGHTBLACK_EX, Err_Fore.RESET, Err_Style.RESET_ALL) + record.msg
7386
return super(LevelDifferentiatingFormatter, self).format(record)
7487

7588
logger = logging.getLogger('p4a')
@@ -78,7 +91,7 @@ def format(self, record):
7891
# handler and reset the level
7992
logger.setLevel(logging.INFO)
8093
logger.touched = True
81-
ch = logging.StreamHandler(stdout) if sys.stdout.isatty() else logging.NullHandler()
94+
ch = logging.StreamHandler(stderr)
8295
formatter = LevelDifferentiatingFormatter('%(message)s')
8396
ch.setFormatter(formatter)
8497
logger.addHandler(ch)
@@ -89,20 +102,20 @@ def format(self, record):
89102

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

92-
info(''.join([Style.BRIGHT, Fore.RED,
105+
info(''.join([Err_Style.BRIGHT, Err_Fore.RED,
93106
'This python-for-android revamp is an experimental alpha release!',
94-
Style.RESET_ALL]))
95-
info(''.join([Fore.RED,
107+
Err_Style.RESET_ALL]))
108+
info(''.join([Err_Fore.RED,
96109
('It should work (mostly), but you may experience '
97110
'missing features or bugs.'),
98-
Style.RESET_ALL]))
111+
Err_Style.RESET_ALL]))
99112

100113
def info_main(*args):
101-
logger.info(''.join([Style.BRIGHT, Fore.GREEN] + list(args) +
102-
[Style.RESET_ALL, Fore.RESET]))
114+
logger.info(''.join([Err_Style.BRIGHT, Err_Fore.GREEN] + list(args) +
115+
[Err_Style.RESET_ALL, Err_Fore.RESET]))
103116

104117
def info_notify(s):
105-
info('{}{}{}{}'.format(Style.BRIGHT, Fore.LIGHTBLUE_EX, s, Style.RESET_ALL))
118+
info('{}{}{}{}'.format(Err_Style.BRIGHT, Err_Fore.LIGHTBLUE_EX, s, Err_Style.RESET_ALL))
106119

107120
def pretty_log_dists(dists, log_func=info):
108121
infos = []
@@ -111,7 +124,7 @@ def pretty_log_dists(dists, log_func=info):
111124
'includes recipes ({Fore.GREEN}{recipes}'
112125
'{Style.RESET_ALL})'.format(
113126
name=dist.name, recipes=', '.join(dist.recipes),
114-
Fore=Fore, Style=Style))
127+
Fore=Err_Fore, Style=Err_Style))
115128

116129
for line in infos:
117130
log_func('\t' + line)
@@ -134,15 +147,15 @@ def shprint(command, *args, **kwargs):
134147
short_string = string
135148
if len(string) > 100:
136149
short_string = string[:100] + '... (and {} more)'.format(len(string) - 100)
137-
logger.info(short_string + Style.RESET_ALL)
150+
logger.info(short_string + Err_Style.RESET_ALL)
138151
else:
139-
logger.debug(string + Style.RESET_ALL)
152+
logger.debug(string + Err_Style.RESET_ALL)
140153

141154
output = command(*args, **kwargs)
142155
need_closing_newline = False
143156
for line in output:
144157
if logger.level > logging.DEBUG:
145-
string = ''.join([Style.RESET_ALL, '\r', ' '*11, 'working ... ',
158+
string = ''.join([Err_Style.RESET_ALL, '\r', ' '*11, 'working ... ',
146159
line[:100].replace('\n', '').rstrip(), ' ...'])
147160
if len(string) < 20:
148161
continue
@@ -224,12 +237,12 @@ def is_exe(fpath):
224237
@contextlib.contextmanager
225238
def current_directory(new_dir):
226239
cur_dir = getcwd()
227-
logger.info(''.join((Fore.CYAN, '-> directory context ', new_dir,
228-
Fore.RESET)))
240+
logger.info(''.join((Err_Fore.CYAN, '-> directory context ', new_dir,
241+
Err_Fore.RESET)))
229242
chdir(new_dir)
230243
yield
231-
logger.info(''.join((Fore.CYAN, '<- directory context ', cur_dir,
232-
Fore.RESET)))
244+
logger.info(''.join((Err_Fore.CYAN, '<- directory context ', cur_dir,
245+
Err_Fore.RESET)))
233246
chdir(cur_dir)
234247

235248

@@ -2587,13 +2600,13 @@ def recipes(self, args):
25872600
print('{Fore.BLUE}{Style.BRIGHT}{recipe.name:<12} '
25882601
'{Style.RESET_ALL}{Fore.LIGHTBLUE_EX}'
25892602
'{version:<8}{Style.RESET_ALL}'.format(
2590-
recipe=recipe, Fore=Fore, Style=Style,
2603+
recipe=recipe, Fore=Out_Fore, Style=Out_Style,
25912604
version=version))
25922605
print(' {Fore.GREEN}depends: {recipe.depends}'
2593-
'{Fore.RESET}'.format(recipe=recipe, Fore=Fore))
2606+
'{Fore.RESET}'.format(recipe=recipe, Fore=Out_Fore))
25942607
if recipe.conflicts:
25952608
print(' {Fore.RED}conflicts: {recipe.conflicts}'
2596-
'{Fore.RESET}'.format(recipe=recipe, Fore=Fore))
2609+
'{Fore.RESET}'.format(recipe=recipe, Fore=Out_Fore))
25972610
else:
25982611
print("{recipe.name:<12} {recipe.version:<8}".format(
25992612
recipe=recipe))
@@ -2605,9 +2618,9 @@ def bootstraps(self, args):
26052618
for bs in Bootstrap.list_bootstraps():
26062619
bs = Bootstrap.get_bootstrap(bs, self.ctx)
26072620
print('{Fore.BLUE}{Style.BRIGHT}{bs.name}{Style.RESET_ALL}'.format(
2608-
bs=bs, Fore=Fore, Style=Style))
2621+
bs=bs, Fore=Out_Fore, Style=Out_Style))
26092622
print(' {Fore.GREEN}depends: {bs.recipe_depends}{Fore.RESET}'.format(
2610-
bs=bs, Fore=Fore))
2623+
bs=bs, Fore=Out_Fore))
26112624

26122625
def clean_all(self, args):
26132626
'''Delete all build components; the package cache, package builds,
@@ -2833,11 +2846,11 @@ def distributions(self, args):
28332846

28342847
if dists:
28352848
print('{Style.BRIGHT}Distributions currently installed are:'
2836-
'{Style.RESET_ALL}'.format(Style=Style, Fore=Fore))
2849+
'{Style.RESET_ALL}'.format(Style=Out_Style, Fore=Out_Fore))
28372850
pretty_log_dists(dists, print)
28382851
else:
28392852
print('{Style.BRIGHT}There are no dists currently built.'
2840-
'{Style.RESET_ALL}'.format(Style=Style))
2853+
'{Style.RESET_ALL}'.format(Style=Out_Style))
28412854

28422855
def delete_dist(self, args):
28432856
dist = self._dist
@@ -2896,24 +2909,24 @@ def logcat(self, args):
28962909
def build_status(self, args):
28972910

28982911
print('{Style.BRIGHT}Bootstraps whose core components are probably already built:'
2899-
'{Style.RESET_ALL}'.format(Style=Style))
2912+
'{Style.RESET_ALL}'.format(Style=Out_Style))
29002913
for filen in os.listdir(join(self.ctx.build_dir, 'bootstrap_builds')):
29012914
print(' {Fore.GREEN}{Style.BRIGHT}{filen}{Style.RESET_ALL}'.format(
2902-
filen=filen, Fore=Fore, Style=Style))
2915+
filen=filen, Fore=Out_Fore, Style=Out_Style))
29032916

29042917
print('{Style.BRIGHT}Recipes that are probably already built:'
2905-
'{Style.RESET_ALL}'.format(Style=Style))
2918+
'{Style.RESET_ALL}'.format(Style=Out_Style))
29062919
if exists(join(self.ctx.build_dir, 'other_builds')):
29072920
for filen in sorted(os.listdir(join(self.ctx.build_dir, 'other_builds'))):
29082921
name = filen.split('-')[0]
29092922
dependencies = filen.split('-')[1:]
29102923
recipe_str = (' {Style.BRIGHT}{Fore.GREEN}{name}'
29112924
'{Style.RESET_ALL}'.format(
2912-
Style=Style, name=name, Fore=Fore))
2925+
Style=Out_Style, name=name, Fore=Out_Fore))
29132926
if dependencies:
29142927
recipe_str += (' ({Fore.BLUE}with ' + ', '.join(dependencies) +
2915-
'{Fore.RESET})').format(Fore=Fore)
2916-
recipe_str += '{Style.RESET_ALL}'.format(Style=Style)
2928+
'{Fore.RESET})').format(Fore=Out_Fore)
2929+
recipe_str += '{Style.RESET_ALL}'.format(Style=Out_Style)
29172930
print(recipe_str)
29182931

29192932

0 commit comments

Comments
 (0)