Home | History | Annotate | Download | only in layout_package
      1 #!/usr/bin/env python
      2 # Copyright (C) 2010 Google Inc. All rights reserved.
      3 #
      4 # Redistribution and use in source and binary forms, with or without
      5 # modification, are permitted provided that the following conditions are
      6 # met:
      7 #
      8 #     * Redistributions of source code must retain the above copyright
      9 # notice, this list of conditions and the following disclaimer.
     10 #     * Redistributions in binary form must reproduce the above
     11 # copyright notice, this list of conditions and the following disclaimer
     12 # in the documentation and/or other materials provided with the
     13 # distribution.
     14 #     * Neither the name of Google Inc. nor the names of its
     15 # contributors may be used to endorse or promote products derived from
     16 # this software without specific prior written permission.
     17 #
     18 # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
     19 # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
     20 # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
     21 # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
     22 # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     23 # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
     24 # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
     25 # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
     26 # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
     27 # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
     28 # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
     29 
     30 """
     31 Package that implements a stream wrapper that has 'meters' as well as
     32 regular output. A 'meter' is a single line of text that can be erased
     33 and rewritten repeatedly, without producing multiple lines of output. It
     34 can be used to produce effects like progress bars.
     35 
     36 This package should only be called by the printing module in the layout_tests
     37 package.
     38 """
     39 
     40 import logging
     41 
     42 _log = logging.getLogger("webkitpy.layout_tests.metered_stream")
     43 
     44 
     45 class MeteredStream:
     46     """This class is a wrapper around a stream that allows you to implement
     47     meters (progress bars, etc.).
     48 
     49     It can be used directly as a stream, by calling write(), but provides
     50     two other methods for output, update(), and progress().
     51 
     52     In normal usage, update() will overwrite the output of the immediately
     53     preceding update() (write() also will overwrite update()). So, calling
     54     multiple update()s in a row can provide an updating status bar (note that
     55     if an update string contains newlines, only the text following the last
     56     newline will be overwritten/erased).
     57 
     58     If the MeteredStream is constructed in "verbose" mode (i.e., by passing
     59     verbose=true), then update() no longer overwrite a previous update(), and
     60     instead the call is equivalent to write(), although the text is
     61     actually sent to the logger rather than to the stream passed
     62     to the constructor.
     63 
     64     progress() is just like update(), except that if you are in verbose mode,
     65     progress messages are not output at all (they are dropped). This is
     66     used for things like progress bars which are presumed to be unwanted in
     67     verbose mode.
     68 
     69     Note that the usual usage for this class is as a destination for
     70     a logger that can also be written to directly (i.e., some messages go
     71     through the logger, some don't). We thus have to dance around a
     72     layering inversion in update() for things to work correctly.
     73     """
     74 
     75     def __init__(self, verbose, stream):
     76         """
     77         Args:
     78           verbose: whether progress is a no-op and updates() aren't overwritten
     79           stream: output stream to write to
     80         """
     81         self._dirty = False
     82         self._verbose = verbose
     83         self._stream = stream
     84         self._last_update = ""
     85 
     86     def write(self, txt):
     87         """Write to the stream, overwriting and resetting the meter."""
     88         if self._dirty:
     89             self._write(txt)
     90             self._dirty = False
     91             self._last_update = ''
     92         else:
     93             self._stream.write(txt)
     94 
     95     def flush(self):
     96         """Flush any buffered output."""
     97         self._stream.flush()
     98 
     99     def progress(self, str):
    100         """
    101         Write a message to the stream that will get overwritten.
    102 
    103         This is used for progress updates that don't need to be preserved in
    104         the log. If the MeteredStream was initialized with verbose==True,
    105         then this output is discarded. We have this in case we are logging
    106         lots of output and the update()s will get lost or won't work
    107         properly (typically because verbose streams are redirected to files).
    108 
    109         """
    110         if self._verbose:
    111             return
    112         self._write(str)
    113 
    114     def update(self, str):
    115         """
    116         Write a message that is also included when logging verbosely.
    117 
    118         This routine preserves the same console logging behavior as progress(),
    119         but will also log the message if verbose() was true.
    120 
    121         """
    122         # Note this is a separate routine that calls either into the logger
    123         # or the metering stream. We have to be careful to avoid a layering
    124         # inversion (stream calling back into the logger).
    125         if self._verbose:
    126             _log.info(str)
    127         else:
    128             self._write(str)
    129 
    130     def _write(self, str):
    131         """Actually write the message to the stream."""
    132 
    133         # FIXME: Figure out if there is a way to detect if we're writing
    134         # to a stream that handles CRs correctly (e.g., terminals). That might
    135         # be a cleaner way of handling this.
    136 
    137         # Print the necessary number of backspaces to erase the previous
    138         # message.
    139         if len(self._last_update):
    140             self._stream.write("\b" * len(self._last_update) +
    141                                " " * len(self._last_update) +
    142                                "\b" * len(self._last_update))
    143         self._stream.write(str)
    144         last_newline = str.rfind("\n")
    145         self._last_update = str[(last_newline + 1):]
    146         self._dirty = True
    147