• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

kivy / python-for-android / 26681571906

30 May 2026 10:31AM UTC coverage: 62.67% (-1.2%) from 63.887%
26681571906

Pull #3278

github

web-flow
Merge 117fe4eef into 74b559a3c
Pull Request #3278: Handling system bars and Edge-to-Edge enforcement (android 15+)

1832 of 3194 branches covered (57.36%)

Branch coverage included in aggregate %.

5407 of 8357 relevant lines covered (64.7%)

3.88 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

84.65
/pythonforandroid/logger.py
1
import logging
6✔
2
import os
6✔
3
import re
6✔
4
import sh
6✔
5
from sys import stdout, stderr
6✔
6
from math import log10
6✔
7
from collections import defaultdict
6✔
8
from colorama import Style as Colo_Style, Fore as Colo_Fore
6✔
9

10

11
# monkey patch to show full output
12
sh.ErrorReturnCode.truncate_cap = 999999
6✔
13

14

15
class LevelDifferentiatingFormatter(logging.Formatter):
6✔
16
    def format(self, record):
6✔
17
        if record.levelno > 30:
6✔
18
            record.msg = '{}{}[ERROR]{}{}:   '.format(
6✔
19
                Err_Style.BRIGHT, Err_Fore.RED, Err_Fore.RESET,
20
                Err_Style.RESET_ALL) + record.msg
21
        elif record.levelno > 20:
6✔
22
            record.msg = '{}{}[WARNING]{}{}: '.format(
6✔
23
                Err_Style.BRIGHT, Err_Fore.RED, Err_Fore.RESET,
24
                Err_Style.RESET_ALL) + record.msg
25
        elif record.levelno > 10:
6✔
26
            record.msg = '{}[INFO]{}:    '.format(
6✔
27
                Err_Style.BRIGHT, Err_Style.RESET_ALL) + record.msg
28
        else:
29
            record.msg = '{}{}[DEBUG]{}{}:   '.format(
6✔
30
                Err_Style.BRIGHT, Err_Fore.LIGHTBLACK_EX, Err_Fore.RESET,
31
                Err_Style.RESET_ALL) + record.msg
32
        return super().format(record)
6✔
33

34

35
logger = logging.getLogger('p4a')
6✔
36
# Necessary as importlib reloads this,
37
# which would add a second handler and reset the level
38
if not hasattr(logger, 'touched'):
6!
39
    logger.setLevel(logging.INFO)
6✔
40
    logger.touched = True
6✔
41
    ch = logging.StreamHandler(stderr)
6✔
42
    formatter = LevelDifferentiatingFormatter('%(message)s')
6✔
43
    ch.setFormatter(formatter)
6✔
44
    logger.addHandler(ch)
6✔
45
info = logger.info
6✔
46
debug = logger.debug
6✔
47
warning = logger.warning
6✔
48
error = logger.error
6✔
49

50

51
class colorama_shim:
6✔
52

53
    def __init__(self, real):
6✔
54
        self._dict = defaultdict(str)
6✔
55
        self._real = real
6✔
56
        self._enabled = False
6✔
57

58
    def __getattr__(self, key):
6✔
59
        return getattr(self._real, key) if self._enabled else self._dict[key]
6✔
60

61
    def enable(self, enable):
6✔
62
        self._enabled = enable
6✔
63

64

65
Out_Style = colorama_shim(Colo_Style)
6✔
66
Out_Fore = colorama_shim(Colo_Fore)
6✔
67
Err_Style = colorama_shim(Colo_Style)
6✔
68
Err_Fore = colorama_shim(Colo_Fore)
6✔
69

70

71
def setup_color(color):
6✔
72
    enable_out = (False if color == 'never' else
6✔
73
                  True if color == 'always' else
74
                  stdout.isatty())
75
    Out_Style.enable(enable_out)
6✔
76
    Out_Fore.enable(enable_out)
6✔
77

78
    enable_err = (False if color == 'never' else
6✔
79
                  True if color == 'always' else
80
                  stderr.isatty())
81
    Err_Style.enable(enable_err)
6✔
82
    Err_Fore.enable(enable_err)
6✔
83

84

85
def info_main(*args):
6✔
86
    logger.info(''.join([Err_Style.BRIGHT, Err_Fore.GREEN] + list(args) +
6✔
87
                        [Err_Style.RESET_ALL, Err_Fore.RESET]))
88

89

90
def info_notify(s):
6✔
91
    info('{}{}{}{}'.format(Err_Style.BRIGHT, Err_Fore.LIGHTBLUE_EX, s,
6✔
92
                           Err_Style.RESET_ALL))
93

94

95
def shorten_string(string, max_width):
6✔
96
    ''' make limited length string in form:
97
      "the string is very lo...(and 15 more)"
98
    '''
99
    string_len = len(string)
6✔
100
    if string_len <= max_width:
6✔
101
        return string
6✔
102
    visible = max_width - 16 - int(log10(string_len))
6✔
103
    # expected suffix len "...(and XXXXX more)"
104
    if not isinstance(string, str):
6✔
105
        visstring = str(string[:visible], errors='ignore')
6✔
106
    else:
107
        visstring = string[:visible]
6✔
108
    return u''.join((visstring, u'...(and ',
6✔
109
                     str(string_len - visible), u' more)'))
110

111

112
def get_console_width():
6✔
113
    try:
6✔
114
        cols = int(os.environ['COLUMNS'])
6✔
115
    except (KeyError, ValueError):
6✔
116
        pass
6✔
117
    else:
118
        if cols >= 25:
6!
119
            return cols
6✔
120

121
    try:
6✔
122
        cols = max(25, int(os.popen('stty size', 'r').read().split()[1]))
6✔
123
    except Exception:
6✔
124
        pass
6✔
125
    else:
126
        return cols
6✔
127

128
    return 100
6✔
129

130

131
def shprint(command, *args, **kwargs):
6✔
132
    '''Runs the command (which should be an sh.Command instance), while
133
    logging the output.'''
134
    kwargs["_iter"] = True
6✔
135
    kwargs["_out_bufsize"] = 1
6✔
136
    kwargs["_err_to_out"] = True
6✔
137
    kwargs["_bg"] = True
6✔
138

139
    # silent mode
140
    silent = kwargs.get("silent", False)
6✔
141
    kwargs.pop("silent", False)
6✔
142
    if silent:
6!
143
        kwargs["_out"] = None
×
144

145
    is_critical = kwargs.pop('_critical', False)
6✔
146
    tail_n = kwargs.pop('_tail', None)
6✔
147
    full_debug = False
6✔
148
    if "P4A_FULL_DEBUG" in os.environ:
6✔
149
        tail_n = 0
6✔
150
        full_debug = True
6✔
151
    filter_in = kwargs.pop('_filter', None)
6✔
152
    filter_out = kwargs.pop('_filterout', None)
6✔
153
    if len(logger.handlers) > 1:
6!
154
        logger.removeHandler(logger.handlers[1])
×
155
    columns = get_console_width()
6✔
156
    command_path = str(command).split('/')
6✔
157
    command_string = command_path[-1]
6✔
158
    string = ' '.join(['{}->{} running'.format(Out_Fore.LIGHTBLACK_EX,
6✔
159
                                               Out_Style.RESET_ALL),
160
                       command_string] + list(args))
161

162
    # If logging is not in DEBUG mode, trim the command if necessary
163
    if logger.level > logging.DEBUG:
6!
164
        logger.info('{}{}'.format(shorten_string(string, columns - 12),
6✔
165
                                  Err_Style.RESET_ALL))
166
    else:
167
        logger.debug('{}{}'.format(string, Err_Style.RESET_ALL))
×
168

169
    need_closing_newline = False
6✔
170
    try:
6✔
171
        msg_hdr = '           working: '
6✔
172
        msg_width = columns - len(msg_hdr) - 1
6✔
173
        output = command(*args, **kwargs)
6✔
174
        for line in output:
6✔
175
            if isinstance(line, bytes):
6!
176
                line = line.decode('utf-8', errors='replace')
×
177
            if logger.level > logging.DEBUG:
6!
178
                if full_debug:
6✔
179
                    stdout.write(line)
6✔
180
                    stdout.flush()
6✔
181
                    continue
6✔
182
                msg = line.replace(
6✔
183
                    '\n', ' ').replace(
184
                        '\t', ' ').replace(
185
                            '\b', ' ').rstrip()
186
                if msg:
6!
187
                    if "CI" not in os.environ:
6!
188
                        stdout.write(u'{}\r{}{:<{width}}'.format(
6✔
189
                            Err_Style.RESET_ALL, msg_hdr,
190
                            shorten_string(msg, msg_width), width=msg_width))
191
                        stdout.flush()
6✔
192
                        need_closing_newline = True
6✔
193
            else:
194
                logger.debug(''.join(['\t', line.rstrip()]))
×
195
        if need_closing_newline:
6✔
196
            stdout.write('{}\r{:>{width}}\r'.format(
6✔
197
                Err_Style.RESET_ALL, ' ', width=(columns - 1)))
198
            stdout.flush()
6✔
199
    except sh.ErrorReturnCode as err:
6✔
200
        if silent:
6!
201
            if is_critical:
×
202
                exit(1)
×
203
            else:
204
                raise
×
205
        if need_closing_newline:
6!
206
            stdout.write('{}\r{:>{width}}\r'.format(
×
207
                Err_Style.RESET_ALL, ' ', width=(columns - 1)))
208
            stdout.flush()
×
209
        if tail_n is not None or filter_in or filter_out:
6!
210
            def printtail(out, name, forecolor, tail_n=0,
6✔
211
                          re_filter_in=None, re_filter_out=None):
212
                lines = out.splitlines()
6✔
213
                if re_filter_in is not None:
6!
214
                    lines = [line for line in lines if re_filter_in.search(line)]
×
215
                if re_filter_out is not None:
6!
216
                    lines = [line for line in lines if not re_filter_out.search(line)]
×
217
                if tail_n == 0 or len(lines) <= tail_n:
6!
218
                    info('{}:\n{}\t{}{}'.format(
6✔
219
                        name, forecolor, '\t\n'.join(lines), Out_Fore.RESET))
220
                else:
221
                    info('{} (last {} lines of {}):\n{}\t{}{}'.format(
×
222
                        name, tail_n, len(lines),
223
                        forecolor, '\t\n'.join([s for s in lines[-tail_n:]]),
224
                        Out_Fore.RESET))
225
            printtail(err.stdout.decode('utf-8'), 'STDOUT', Out_Fore.YELLOW, tail_n,
6✔
226
                      re.compile(filter_in) if filter_in else None,
227
                      re.compile(filter_out) if filter_out else None)
228
            printtail(err.stderr.decode('utf-8'), 'STDERR', Err_Fore.RED)
6✔
229
        if is_critical or full_debug:
6!
230
            env = kwargs.get("_env")
6✔
231
            if env is not None:
6!
232
                info("{}ENV:{}\n{}\n".format(
×
233
                    Err_Fore.YELLOW, Err_Fore.RESET, "\n".join(
234
                        "export {}='{}'".format(n, v) for n, v in env.items())))
235
            info("{}COMMAND:{}\ncd {} && {} {}\n".format(
6✔
236
                Err_Fore.YELLOW, Err_Fore.RESET, os.getcwd(), command,
237
                ' '.join(args)))
238
            warning("{}ERROR: {} failed!{}".format(
6✔
239
                Err_Fore.RED, command, Err_Fore.RESET))
240
        if is_critical:
6!
241
            exit(1)
6✔
242
        else:
243
            raise
×
244

245
    return output
6✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc