Daniel Vizcaya / Mbed OS 04_RTOS_Embebidos
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers term.py Source File

term.py

00001 # mbed SDK
00002 # Copyright (c) 2011-2013 ARM Limited
00003 #
00004 # Licensed under the Apache License, Version 2.0 (the "License");
00005 # you may not use this file except in compliance with the License.
00006 # You may obtain a copy of the License at
00007 #
00008 #     http://www.apache.org/licenses/LICENSE-2.0
00009 #
00010 # Unless required by applicable law or agreed to in writing, software
00011 # distributed under the License is distributed on an "AS IS" BASIS,
00012 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
00013 # See the License for the specific language governing permissions and
00014 # limitations under the License.
00015 
00016 from __future__ import print_function, division, absolute_import
00017 
00018 import re
00019 import sys
00020 from os import getcwd
00021 from os.path import basename
00022 
00023 from . import Notifier
00024 from ..settings import (PRINT_COMPILER_OUTPUT_AS_LINK,
00025                         CLI_COLOR_MAP, COLOR)
00026 
00027 class TerminalNotifier (Notifier):
00028     """
00029     Writes notifications to a terminal based on silent, verbose and color flags.
00030     """
00031 
00032     def __init__(self, verbose=False, silent=False, color=False):
00033         self.verbose  = verbose
00034         self.silent  = silent
00035         self.output  = ""
00036         self.color  = color or COLOR
00037         if self.color :
00038             from colorama import init, Fore, Back, Style
00039             init()
00040             self.COLORS  = {
00041                 'none' : "",
00042                 'default' : Style.RESET_ALL,
00043 
00044                 'black'   : Fore.BLACK,
00045                 'red'     : Fore.RED,
00046                 'green'   : Fore.GREEN,
00047                 'yellow'  : Fore.YELLOW,
00048                 'blue'    : Fore.BLUE,
00049                 'magenta' : Fore.MAGENTA,
00050                 'cyan'    : Fore.CYAN,
00051                 'white'   : Fore.WHITE,
00052 
00053                 'on_black'   : Back.BLACK,
00054                 'on_red'     : Back.RED,
00055                 'on_green'   : Back.GREEN,
00056                 'on_yellow'  : Back.YELLOW,
00057                 'on_blue'    : Back.BLUE,
00058                 'on_magenta' : Back.MAGENTA,
00059                 'on_cyan'    : Back.CYAN,
00060                 'on_white'   : Back.WHITE,
00061             }
00062 
00063     def get_output(self):
00064         return self.output 
00065 
00066     def notify(self, event):
00067         if self.verbose :
00068             msg = self.print_notify_verbose (event)
00069         else:
00070             msg = self.print_notify (event)
00071         if msg:
00072             if not self.silent :
00073                 if self.color :
00074                     self.print_in_color (event, msg)
00075                 else:
00076                     print(msg)
00077             self.output  += msg + "\n"
00078 
00079     def print_notify (self, event):
00080         """ Command line notification
00081         """
00082         if event['type'] in ('tool_error', 'info'):
00083             return event['message']
00084 
00085         elif event['type'] == 'cc' and event['severity'] != 'verbose':
00086             event['severity'] = event['severity'].title()
00087 
00088             if PRINT_COMPILER_OUTPUT_AS_LINK:
00089                 event['file'] = getcwd() + event['file'].strip('.')
00090                 return '[{severity}] {file}:{line}:{col}: {message}'.format(
00091                     **event)
00092             else:
00093                 event['file'] = basename(event['file'])
00094                 return '[{severity}] {file}@{line},{col}: {message}'.format(
00095                     **event)
00096 
00097         elif event['type'] == 'progress':
00098             event['action'] = event['action'].title()
00099             event['file'] = basename(event['file'])
00100             if 'percent' in event:
00101                 format_string = '{action} [{percent:>5.1f}%]: {file}'
00102             else:
00103                 format_string = '{action}: {file}'
00104             return format_string.format(**event)
00105 
00106     def print_notify_verbose (self, event):
00107         """ Command line notification with more verbose mode
00108         """
00109         if event['type'] == 'info' or (event['type'] == 'cc' and
00110                                        event['severity'] == 'verbose'):
00111             return event['message']
00112         elif event['type'] == 'debug':
00113             return "[DEBUG] {message}".format(**event)
00114         elif event['type'] in ('progress', 'cc'):
00115             return self.print_notify (event)
00116 
00117     COLOR_MATCHER = re.compile(r"(\w+)(\W+on\W+\w+)?")
00118     def colorstring_to_escapecode (self, color_string):
00119         """ Convert a color string from a string into an ascii escape code that
00120         will print that color on the terminal.
00121 
00122         Positional arguments:
00123         color_string - the string to parse
00124         """
00125         match = re.match(self.COLOR_MATCHER , color_string)
00126         if match:
00127             return self.COLORS [match.group(1)] + \
00128                 (self.COLORS [match.group(2).strip().replace(" ", "_")]
00129                  if match.group(2) else "")
00130         else:
00131             return self.COLORS ['default']
00132 
00133     def print_in_color (self, event, msg):
00134         """ Wrap a toolchain notifier in a colorizer. This colorizer will wrap
00135         notifications in a color if the severity matches a color in the
00136         CLI_COLOR_MAP.
00137         """
00138         """The notification function inself"""
00139         if sys.stdout.isatty() and event.get('severity', None) in CLI_COLOR_MAP:
00140             sys.stdout.write(self.colorstring_to_escapecode (
00141                 CLI_COLOR_MAP[event['severity']]))
00142             print(msg)
00143             sys.stdout.write(self.colorstring_to_escapecode ('default'))
00144         else:
00145             print(msg)