Skip to content

Commit 5fcc098

Browse files
committed
Further separated logger, util, recipebases
1 parent 8d0c9b2 commit 5fcc098

File tree

4 files changed

+174
-159
lines changed

4 files changed

+174
-159
lines changed

pythonforandroid/logger.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ def format(self, record):
3838
warning = logger.warning
3939
error = logger.error
4040

41+
4142
class colorama_shim(object):
4243

4344
def __init__(self):
@@ -61,3 +62,105 @@ def __getattr__(self, key):
6162
else:
6263
Err_Style = Null_Style
6364
Err_Fore = Null_Fore
65+
66+
67+
def info_main(*args):
68+
logger.info(''.join([Err_Style.BRIGHT, Err_Fore.GREEN] + list(args) +
69+
[Err_Style.RESET_ALL, Err_Fore.RESET]))
70+
71+
72+
def info_notify(s):
73+
info('{}{}{}{}'.format(Err_Style.BRIGHT, Err_Fore.LIGHTBLUE_EX, s,
74+
Err_Style.RESET_ALL))
75+
76+
77+
def shprint(command, *args, **kwargs):
78+
'''Runs the command (which should be an sh.Command instance), while
79+
logging the output.'''
80+
kwargs["_iter"] = True
81+
kwargs["_out_bufsize"] = 1
82+
kwargs["_err_to_out"] = True
83+
kwargs["_bg"] = True
84+
is_critical = kwargs.pop('_critical', False)
85+
tail_n = kwargs.pop('_tail', 0)
86+
filter_in = kwargs.pop('_filter', None)
87+
filter_out = kwargs.pop('_filterout', None)
88+
if len(logger.handlers) > 1:
89+
logger.removeHandler(logger.handlers[1])
90+
try:
91+
columns = max(25, int(os.popen('stty size', 'r').read().split()[1]))
92+
except:
93+
columns = 100
94+
command_path = str(command).split('/')
95+
command_string = command_path[-1]
96+
string = ' '.join(['running', command_string] + list(args))
97+
98+
# If logging is not in DEBUG mode, trim the command if necessary
99+
if logger.level > logging.DEBUG:
100+
logger.info('{}{}'.format(shorten_string(string, columns - 12),
101+
Err_Style.RESET_ALL))
102+
else:
103+
logger.debug('{}{}'.format(string, Err_Style.RESET_ALL))
104+
105+
need_closing_newline = False
106+
try:
107+
msg_hdr = ' working: '
108+
msg_width = columns - len(msg_hdr) - 1
109+
output = command(*args, **kwargs)
110+
for line in output:
111+
if logger.level > logging.DEBUG:
112+
msg = line.replace(
113+
'\n', ' ').replace(
114+
'\t', ' ').replace(
115+
'\b', ' ').rstrip()
116+
if msg:
117+
sys.stdout.write(u'{}\r{}{:<{width}}'.format(
118+
Err_Style.RESET_ALL, msg_hdr,
119+
shorten_string(msg, msg_width), width=msg_width))
120+
sys.stdout.flush()
121+
need_closing_newline = True
122+
else:
123+
logger.debug(''.join(['\t', line.rstrip()]))
124+
if need_closing_newline:
125+
sys.stdout.write('{}\r{:>{width}}\r'.format(
126+
Err_Style.RESET_ALL, ' ', width=(columns - 1)))
127+
sys.stdout.flush()
128+
except sh.ErrorReturnCode as err:
129+
if need_closing_newline:
130+
sys.stdout.write('{}\r{:>{width}}\r'.format(
131+
Err_Style.RESET_ALL, ' ', width=(columns - 1)))
132+
sys.stdout.flush()
133+
if tail_n or filter_in or filter_out:
134+
def printtail(out, name, forecolor, tail_n=0,
135+
re_filter_in=None, re_filter_out=None):
136+
lines = out.splitlines()
137+
if re_filter_in is not None:
138+
lines = [l for l in lines if re_filter_in.search(l)]
139+
if re_filter_out is not None:
140+
lines = [l for l in lines if not re_filter_out.search(l)]
141+
if tail_n == 0 or len(lines) <= tail_n:
142+
info('{}:\n{}\t{}{}'.format(
143+
name, forecolor, '\t\n'.join(lines), Out_Fore.RESET))
144+
else:
145+
info('{} (last {} lines of {}):\n{}\t{}{}'.format(
146+
name, tail_n, len(lines),
147+
forecolor, '\t\n'.join(lines[-tail_n:]), Out_Fore.RESET))
148+
printtail(err.stdout, 'STDOUT', Out_Fore.YELLOW, tail_n,
149+
re.compile(filter_in) if filter_in else None,
150+
re.compile(filter_out) if filter_out else None)
151+
printtail(err.stderr, 'STDERR', Err_Fore.RED)
152+
if is_critical:
153+
env = kwargs.get("env")
154+
if env is not None:
155+
info("{}ENV:{}\n{}\n".format(
156+
Err_Fore.YELLOW, Err_Fore.RESET, "\n".join(
157+
"set {}={}".format(n, v) for n, v in env.items())))
158+
info("{}COMMAND:{}\ncd {} && {} {}\n".format(
159+
Err_Fore.YELLOW, Err_Fore.RESET, getcwd(), command, ' '.join(args)))
160+
warning("{}ERROR: {} failed!{}".format(
161+
Err_Fore.RED, command, Err_Fore.RESET))
162+
exit(1)
163+
else:
164+
raise
165+
166+
return output

pythonforandroid/recipebases.py

Lines changed: 24 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,18 @@
1-
from os.path import join, dirname, isdir, exists
1+
from os.path import join, dirname, isdir, exists, isfile
22
import importlib
3-
from os import listdir
4-
from logger import (logger, info, debug, warning, error)
3+
import zipfile
4+
import glob
5+
import sh
6+
import shutil
7+
from os import listdir, unlink, environ, mkdir
8+
from sys import stdout
9+
try:
10+
from urlparse import urlparse
11+
except ImportError:
12+
from urllib.parse import urlparse
13+
from pythonforandroid.logger import (logger, info, warning, shprint, info_main)
14+
from pythonforandroid.util import (urlretrieve, current_directory, ensure_dir)
15+
516

617
class Recipe(object):
718
url = None
@@ -85,7 +96,7 @@ def report_hook(index, blksize, size):
8596
urlretrieve(url, target, report_hook)
8697
return target
8798
elif parsed_url.scheme in ('git',):
88-
if os.path.isdir(target):
99+
if isdir(target):
89100
with current_directory(target):
90101
shprint(sh.git, 'pull')
91102
shprint(sh.git, 'pull', '--recurse-submodules')
@@ -100,7 +111,7 @@ def extract_source(self, source, cwd):
100111
"""
101112
if not source:
102113
return
103-
if os.path.isfile(source):
114+
if isfile(source):
104115
info("Extract {} into {}".format(source, cwd))
105116

106117
if source.endswith(".tgz") or source.endswith(".tar.gz"):
@@ -120,7 +131,7 @@ def extract_source(self, source, cwd):
120131
.format(source))
121132
raise Exception()
122133

123-
elif os.path.isdir(source):
134+
elif isdir(source):
124135
info("Copying {} into {}".format(source, cwd))
125136

126137
shprint(sh.cp, '-a', source, cwd)
@@ -153,7 +164,7 @@ def apply_patch(self, filename, arch):
153164
info("Applying patch {}".format(filename))
154165
filename = join(self.recipe_dir, filename)
155166
shprint(sh.patch, "-t", "-d", self.get_build_dir(arch), "-p1",
156-
"-i", filename, _tail=10)
167+
"-i", filename, _tail=10)
157168

158169
def copy_file(self, filename, dest):
159170
info("Copy {} to {}".format(filename, dest))
@@ -287,7 +298,7 @@ def download(self):
287298
do_download = True
288299

289300
marker_filename = '.mark-{}'.format(filename)
290-
if exists(filename) and os.path.isfile(filename):
301+
if exists(filename) and isfile(filename):
291302
if not exists(marker_filename):
292303
shprint(sh.rm, filename)
293304
elif self.md5sum:
@@ -354,7 +365,7 @@ def unpack(self, arch):
354365
if not exists(directory_name) or not isdir(directory_name):
355366
extraction_filename = join(
356367
self.ctx.packages_path, self.name, filename)
357-
if os.path.isfile(extraction_filename):
368+
if isfile(extraction_filename):
358369
if extraction_filename.endswith('.tar.gz') or \
359370
extraction_filename.endswith('.tgz'):
360371
sh.tar('xzf', extraction_filename)
@@ -384,12 +395,12 @@ def unpack(self, arch):
384395
raise Exception(
385396
'Could not extract {} download, it must be .zip, '
386397
'.tar.gz or .tar.bz2')
387-
elif os.path.isdir(extraction_filename):
388-
os.mkdir(directory_name)
389-
for entry in os.listdir(extraction_filename):
398+
elif isdir(extraction_filename):
399+
mkdir(directory_name)
400+
for entry in listdir(extraction_filename):
390401
if entry not in ('.git',):
391402
shprint(sh.cp, '-Rv',
392-
os.path.join(extraction_filename, entry),
403+
join(extraction_filename, entry),
393404
directory_name)
394405
else:
395406
raise Exception(

0 commit comments

Comments
 (0)