1216bad50219c36d56f9355f44c46a4593591b50
[samba.git] / third_party / waf / waflib / Logs.py
1 #! /usr/bin/env python
2 # encoding: utf-8
3 # WARNING! Do not edit! https://waf.io/book/index.html#_obtaining_the_waf_file
4
5 #!/usr/bin/env python
6 # encoding: utf-8
7 # Thomas Nagy, 2005-2016 (ita)
8
9 """
10 logging, colors, terminal width and pretty-print
11 """
12
13 import os, re, traceback, sys
14 from waflib import Utils, ansiterm
15
16 if not os.environ.get('NOSYNC', False):
17         # synchronized output is nearly mandatory to prevent garbled output
18         if sys.stdout.isatty() and id(sys.stdout) == id(sys.__stdout__):
19                 sys.stdout = ansiterm.AnsiTerm(sys.stdout)
20         if sys.stderr.isatty() and id(sys.stderr) == id(sys.__stderr__):
21                 sys.stderr = ansiterm.AnsiTerm(sys.stderr)
22
23 # import the logging module after since it holds a reference on sys.stderr
24 # in case someone uses the root logger
25 import logging
26
27 LOG_FORMAT = os.environ.get('WAF_LOG_FORMAT', '%(asctime)s %(c1)s%(zone)s%(c2)s %(message)s')
28 HOUR_FORMAT = os.environ.get('WAF_HOUR_FORMAT', '%H:%M:%S')
29
30 zones = []
31 """
32 See :py:class:`waflib.Logs.log_filter`
33 """
34
35 verbose = 0
36 """
37 Global verbosity level, see :py:func:`waflib.Logs.debug` and :py:func:`waflib.Logs.error`
38 """
39
40 colors_lst = {
41 'USE' : True,
42 'BOLD'  :'\x1b[01;1m',
43 'RED'   :'\x1b[01;31m',
44 'GREEN' :'\x1b[32m',
45 'YELLOW':'\x1b[33m',
46 'PINK'  :'\x1b[35m',
47 'BLUE'  :'\x1b[01;34m',
48 'CYAN'  :'\x1b[36m',
49 'GREY'  :'\x1b[37m',
50 'NORMAL':'\x1b[0m',
51 'cursor_on'  :'\x1b[?25h',
52 'cursor_off' :'\x1b[?25l',
53 }
54
55 indicator = '\r\x1b[K%s%s%s'
56
57 try:
58         unicode
59 except NameError:
60         unicode = None
61
62 def enable_colors(use):
63         """
64         If *1* is given, then the system will perform a few verifications
65         before enabling colors, such as checking whether the interpreter
66         is running in a terminal. A value of zero will disable colors,
67         and a value above *1* will force colors.
68
69         :param use: whether to enable colors or not
70         :type use: integer
71         """
72         if use == 1:
73                 if not (sys.stderr.isatty() or sys.stdout.isatty()):
74                         use = 0
75                 if Utils.is_win32 and os.name != 'java':
76                         term = os.environ.get('TERM', '') # has ansiterm
77                 else:
78                         term = os.environ.get('TERM', 'dumb')
79
80                 if term in ('dumb', 'emacs'):
81                         use = 0
82
83         if use >= 1:
84                 os.environ['TERM'] = 'vt100'
85
86         colors_lst['USE'] = use
87
88 # If console packages are available, replace the dummy function with a real
89 # implementation
90 try:
91         get_term_cols = ansiterm.get_term_cols
92 except AttributeError:
93         def get_term_cols():
94                 return 80
95
96 get_term_cols.__doc__ = """
97         Returns the console width in characters.
98
99         :return: the number of characters per line
100         :rtype: int
101         """
102
103 def get_color(cl):
104         """
105         Returns the ansi sequence corresponding to the given color name.
106         An empty string is returned when coloring is globally disabled.
107
108         :param cl: color name in capital letters
109         :type cl: string
110         """
111         if colors_lst['USE']:
112                 return colors_lst.get(cl, '')
113         return ''
114
115 class color_dict(object):
116         """attribute-based color access, eg: colors.PINK"""
117         def __getattr__(self, a):
118                 return get_color(a)
119         def __call__(self, a):
120                 return get_color(a)
121
122 colors = color_dict()
123
124 re_log = re.compile(r'(\w+): (.*)', re.M)
125 class log_filter(logging.Filter):
126         """
127         Waf logs are of the form 'name: message', and can be filtered by 'waf --zones=name'.
128         For example, the following::
129
130                 from waflib import Logs
131                 Logs.debug('test: here is a message')
132
133         Will be displayed only when executing::
134
135                 $ waf --zones=test
136         """
137         def __init__(self, name=''):
138                 logging.Filter.__init__(self, name)
139
140         def filter(self, rec):
141                 """
142                 Filters log records by zone and by logging level
143
144                 :param rec: log entry
145                 """
146                 global verbose
147                 rec.zone = rec.module
148                 if rec.levelno >= logging.INFO:
149                         return True
150
151                 m = re_log.match(rec.msg)
152                 if m:
153                         rec.zone = m.group(1)
154                         rec.msg = m.group(2)
155
156                 if zones:
157                         return getattr(rec, 'zone', '') in zones or '*' in zones
158                 elif not verbose > 2:
159                         return False
160                 return True
161
162 class log_handler(logging.StreamHandler):
163         """Dispatches messages to stderr/stdout depending on the severity level"""
164         def emit(self, record):
165                 """
166                 Delegates the functionality to :py:meth:`waflib.Log.log_handler.emit_override`
167                 """
168                 # default implementation
169                 try:
170                         try:
171                                 self.stream = record.stream
172                         except AttributeError:
173                                 if record.levelno >= logging.WARNING:
174                                         record.stream = self.stream = sys.stderr
175                                 else:
176                                         record.stream = self.stream = sys.stdout
177                         self.emit_override(record)
178                         self.flush()
179                 except (KeyboardInterrupt, SystemExit):
180                         raise
181                 except: # from the python library -_-
182                         self.handleError(record)
183
184         def emit_override(self, record, **kw):
185                 """
186                 Writes the log record to the desired stream (stderr/stdout)
187                 """
188                 self.terminator = getattr(record, 'terminator', '\n')
189                 stream = self.stream
190                 if unicode:
191                         # python2
192                         msg = self.formatter.format(record)
193                         fs = '%s' + self.terminator
194                         try:
195                                 if (isinstance(msg, unicode) and getattr(stream, 'encoding', None)):
196                                         fs = fs.decode(stream.encoding)
197                                         try:
198                                                 stream.write(fs % msg)
199                                         except UnicodeEncodeError:
200                                                 stream.write((fs % msg).encode(stream.encoding))
201                                 else:
202                                         stream.write(fs % msg)
203                         except UnicodeError:
204                                 stream.write((fs % msg).encode('utf-8'))
205                 else:
206                         logging.StreamHandler.emit(self, record)
207
208 class formatter(logging.Formatter):
209         """Simple log formatter which handles colors"""
210         def __init__(self):
211                 logging.Formatter.__init__(self, LOG_FORMAT, HOUR_FORMAT)
212
213         def format(self, rec):
214                 """
215                 Formats records and adds colors as needed. The records do not get
216                 a leading hour format if the logging level is above *INFO*.
217                 """
218                 try:
219                         msg = rec.msg.decode('utf-8')
220                 except Exception:
221                         msg = rec.msg
222
223                 use = colors_lst['USE']
224                 if (use == 1 and rec.stream.isatty()) or use == 2:
225
226                         c1 = getattr(rec, 'c1', None)
227                         if c1 is None:
228                                 c1 = ''
229                                 if rec.levelno >= logging.ERROR:
230                                         c1 = colors.RED
231                                 elif rec.levelno >= logging.WARNING:
232                                         c1 = colors.YELLOW
233                                 elif rec.levelno >= logging.INFO:
234                                         c1 = colors.GREEN
235                         c2 = getattr(rec, 'c2', colors.NORMAL)
236                         msg = '%s%s%s' % (c1, msg, c2)
237                 else:
238                         # remove single \r that make long lines in text files
239                         # and other terminal commands
240                         msg = re.sub(r'\r(?!\n)|\x1B\[(K|.*?(m|h|l))', '', msg)
241
242                 if rec.levelno >= logging.INFO:
243                         # the goal of this is to format without the leading "Logs, hour" prefix
244                         if rec.args:
245                                 return msg % rec.args
246                         return msg
247
248                 rec.msg = msg
249                 rec.c1 = colors.PINK
250                 rec.c2 = colors.NORMAL
251                 return logging.Formatter.format(self, rec)
252
253 log = None
254 """global logger for Logs.debug, Logs.error, etc"""
255
256 def debug(*k, **kw):
257         """
258         Wraps logging.debug and discards messages if the verbosity level :py:attr:`waflib.Logs.verbose` ≤ 0
259         """
260         global verbose
261         if verbose:
262                 k = list(k)
263                 k[0] = k[0].replace('\n', ' ')
264                 global log
265                 log.debug(*k, **kw)
266
267 def error(*k, **kw):
268         """
269         Wrap logging.errors, adds the stack trace when the verbosity level :py:attr:`waflib.Logs.verbose` ≥ 2
270         """
271         global log, verbose
272         log.error(*k, **kw)
273         if verbose > 2:
274                 st = traceback.extract_stack()
275                 if st:
276                         st = st[:-1]
277                         buf = []
278                         for filename, lineno, name, line in st:
279                                 buf.append('  File %r, line %d, in %s' % (filename, lineno, name))
280                                 if line:
281                                         buf.append('    %s' % line.strip())
282                         if buf: log.error('\n'.join(buf))
283
284 def warn(*k, **kw):
285         """
286         Wraps logging.warn
287         """
288         global log
289         log.warn(*k, **kw)
290
291 def info(*k, **kw):
292         """
293         Wraps logging.info
294         """
295         global log
296         log.info(*k, **kw)
297
298 def init_log():
299         """
300         Initializes the logger :py:attr:`waflib.Logs.log`
301         """
302         global log
303         log = logging.getLogger('waflib')
304         log.handlers = []
305         log.filters = []
306         hdlr = log_handler()
307         hdlr.setFormatter(formatter())
308         log.addHandler(hdlr)
309         log.addFilter(log_filter())
310         log.setLevel(logging.DEBUG)
311
312 def make_logger(path, name):
313         """
314         Creates a simple logger, which is often used to redirect the context command output::
315
316                 from waflib import Logs
317                 bld.logger = Logs.make_logger('test.log', 'build')
318                 bld.check(header_name='sadlib.h', features='cxx cprogram', mandatory=False)
319
320                 # have the file closed immediately
321                 Logs.free_logger(bld.logger)
322
323                 # stop logging
324                 bld.logger = None
325
326         The method finalize() of the command will try to free the logger, if any
327
328         :param path: file name to write the log output to
329         :type path: string
330         :param name: logger name (loggers are reused)
331         :type name: string
332         """
333         logger = logging.getLogger(name)
334         hdlr = logging.FileHandler(path, 'w')
335         formatter = logging.Formatter('%(message)s')
336         hdlr.setFormatter(formatter)
337         logger.addHandler(hdlr)
338         logger.setLevel(logging.DEBUG)
339         return logger
340
341 def make_mem_logger(name, to_log, size=8192):
342         """
343         Creates a memory logger to avoid writing concurrently to the main logger
344         """
345         from logging.handlers import MemoryHandler
346         logger = logging.getLogger(name)
347         hdlr = MemoryHandler(size, target=to_log)
348         formatter = logging.Formatter('%(message)s')
349         hdlr.setFormatter(formatter)
350         logger.addHandler(hdlr)
351         logger.memhandler = hdlr
352         logger.setLevel(logging.DEBUG)
353         return logger
354
355 def free_logger(logger):
356         """
357         Frees the resources held by the loggers created through make_logger or make_mem_logger.
358         This is used for file cleanup and for handler removal (logger objects are re-used).
359         """
360         try:
361                 for x in logger.handlers:
362                         x.close()
363                         logger.removeHandler(x)
364         except Exception:
365                 pass
366
367 def pprint(col, msg, label='', sep='\n'):
368         """
369         Prints messages in color immediately on stderr::
370
371                 from waflib import Logs
372                 Logs.pprint('RED', 'Something bad just happened')
373
374         :param col: color name to use in :py:const:`Logs.colors_lst`
375         :type col: string
376         :param msg: message to display
377         :type msg: string or a value that can be printed by %s
378         :param label: a message to add after the colored output
379         :type label: string
380         :param sep: a string to append at the end (line separator)
381         :type sep: string
382         """
383         global info
384         info('%s%s%s %s', colors(col), msg, colors.NORMAL, label, extra={'terminator':sep})