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

kivy / python-for-android / 10347694551

12 Aug 2024 07:28AM UTC coverage: 59.07% (-0.07%) from 59.14%
10347694551

push

github

AndreMiras
:arrow_up: Bump to sh 2

1048 of 2361 branches covered (44.39%)

Branch coverage included in aggregate %.

0 of 4 new or added lines in 2 files covered. (0.0%)

6 existing lines in 3 files now uncovered.

4862 of 7644 relevant lines covered (63.61%)

2.53 hits per line

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

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

10

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

14

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

34

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

50

51
class colorama_shim:
4✔
52

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

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

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

64

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

70

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

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

84

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

89

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

94

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

111

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

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

128
    return 100
4✔
129

130

131
def shprint(command, *args, **kwargs):
4✔
132
    '''Runs the command (which should be an sh.Command instance), while
133
    logging the output.'''
134
    kwargs["_iter"] = True
4✔
135
    kwargs["_out_bufsize"] = 1
4✔
136
    kwargs["_err_to_out"] = True
4✔
137
    kwargs["_bg"] = True
4✔
138
    is_critical = kwargs.pop('_critical', False)
4✔
139
    tail_n = kwargs.pop('_tail', None)
4✔
140
    full_debug = False
4✔
141
    if "P4A_FULL_DEBUG" in os.environ:
4!
142
        tail_n = 0
×
143
        full_debug = True
×
144
    filter_in = kwargs.pop('_filter', None)
4✔
145
    filter_out = kwargs.pop('_filterout', None)
4✔
146
    if len(logger.handlers) > 1:
4!
147
        logger.removeHandler(logger.handlers[1])
×
148
    columns = get_console_width()
4✔
149
    command_path = str(command).split('/')
4✔
150
    command_string = command_path[-1]
4✔
151
    string = ' '.join(['{}->{} running'.format(Out_Fore.LIGHTBLACK_EX,
4✔
152
                                               Out_Style.RESET_ALL),
153
                       command_string] + list(args))
154

155
    # If logging is not in DEBUG mode, trim the command if necessary
156
    if logger.level > logging.DEBUG:
4!
157
        logger.info('{}{}'.format(shorten_string(string, columns - 12),
4✔
158
                                  Err_Style.RESET_ALL))
159
    else:
160
        logger.debug('{}{}'.format(string, Err_Style.RESET_ALL))
×
161

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

234
    return output
4✔
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

© 2025 Coveralls, Inc