Package cssutils :: Module parse' |
[hide private]
[frames] | no frames]

# Source Code for Module cssutils.parse'

      1  #!/usr/bin/env python
      2  """a validating CSSParser
      3  """
      4  __all__ = ['CSSParser']
      5  __docformat__ = 'restructuredtext'
      6  __version__ = '$Id: parse.py 1418 2008-08-09 19:27:50Z cthedot $'
      7
      8  import codecs
      9  import os
     10  import urllib
     11  from helper import Deprecated
     12  import tokenize2
     13  import cssutils
     14
     15 -class CSSParser(object):
     16      """
     17      parses a CSS StyleSheet string or file and
     18      returns a DOM Level 2 CSS StyleSheet object
     19
     20      Usage::
     21
     22          parser = CSSParser()
     23
     24          # optionally
     25          parser.setFetcher(fetcher)
     26
     27          sheet = parser.parseFile('test1.css', 'ascii')
     28
     29          print sheet.cssText
     30      """
     31 -    def __init__(self, log=None, loglevel=None, raiseExceptions=None,
     32                   fetcher=None):
     33          """
     34          log
     35              logging object
     36          loglevel
     37              logging loglevel
     38          raiseExceptions
     39              if log should simply log (default) or raise errors during
     40              parsing. Later while working with the resulting sheets
     41              the setting used in cssutils.log.raiseExeptions is used
     42          fetcher
     43              see ``setFetchUrl(fetcher)``
     44          """
     45          if log is not None:
     46              cssutils.log.setLog(log)
     47          if loglevel is not None:
     48              cssutils.log.setLevel(loglevel)
     49
     50          # remember global setting
     51          self.__globalRaising = cssutils.log.raiseExceptions
     52          if raiseExceptions:
     53              self.__parseRaising = raiseExceptions
     54          else:
     55              # DEFAULT during parse
     56              self.__parseRaising = False
     57
     58          self.__tokenizer = tokenize2.Tokenizer()
     59          self.setFetcher(fetcher)
     60
     61 -    def __parseSetting(self, parse):
     62          """during parse exceptions may be handled differently depending on
     63          init parameter ``raiseExceptions``
     64          """
     65          if parse:
     66              cssutils.log.raiseExceptions = self.__parseRaising
     67          else:
     68              cssutils.log.raiseExceptions = self.__globalRaising
     69
     70 -    def parseString(self, cssText, encoding=None, href=None, media=None,
     71                      title=None):
     72          """Return parsed CSSStyleSheet from given string cssText.
     73          Raises errors during retrieving (e.g. UnicodeDecodeError).
     74
     75          cssText
     76              CSS string to parse
     77          encoding
     78              If ``None`` the encoding will be read from BOM or an @charset
     79              rule or defaults to UTF-8.
     80              If given overrides any found encoding including the ones for
     81              imported sheets.
     82              It also will be used to decode ``cssText`` if given as a (byte)
     83              string.
     84          href
     85              The href attribute to assign to the parsed style sheet.
     86              Used to resolve other urls in the parsed sheet like @import hrefs
     87          media
     88              The media attribute to assign to the parsed style sheet
     89              (may be a MediaList, list or a string)
     90          title
     91              The title attribute to assign to the parsed style sheet
     92          """
     93          self.__parseSetting(True)
     94          if isinstance(cssText, str):
     95              cssText = codecs.getdecoder('css')(cssText, encoding=encoding)[0]
     96
     97          sheet = cssutils.css.CSSStyleSheet(href=href,
     98                                             media=cssutils.stylesheets.MediaList(media),
     99                                             title=title)
    100          sheet._setFetcher(self.__fetcher)
    101          # tokenizing this ways closes open constructs and adds EOF
    102          sheet._setCssTextWithEncodingOverride(self.__tokenizer.tokenize(cssText,
    103                                                                          fullsheet=True),
    104                                                encodingOverride=encoding)
    105          self.__parseSetting(False)
    106          return sheet
    107
    108 -    def parseFile(self, filename, encoding=None,
    109                    href=None, media=None, title=None):
    110          """Retrieve and return a CSSStyleSheet from given filename.
    111          Raises errors during retrieving (e.g. IOError).
    112
    113          filename
    114              of the CSS file to parse, if no ``href`` is given filename is
    115              converted to a (file:) URL and set as ``href`` of resulting
    116              stylesheet.
    117              If href is given it is set as ``sheet.href``. Either way
    118              ``sheet.href`` is used to resolve e.g. stylesheet imports via
    119              @import rules.
    120          encoding
    121              Value ``None`` defaults to encoding detection via BOM or an
    122              @charset rule.
    123              Other values override detected encoding for the sheet at
    124              ``filename`` including any imported sheets.
    125
    126          for other parameters see ``parseString``
    127          """
    128          if not href:
    129              # prepend // for file URL, urllib does not do this?
    130              href = u'file:' + urllib.pathname2url(os.path.abspath(filename))
    131
    132          return self.parseString(open(filename, 'rb').read(),
    133                                  encoding=encoding, # read returns a str
    134                                  href=href, media=media, title=title)
    135
    136 -    def parseUrl(self, href, encoding=None, media=None, title=None):
    137          """Retrieve and return a CSSStyleSheet from given href (an URL).
    138          In case of any errors while reading the URL returns None.
    139
    140          href
    141              URL of the CSS file to parse, will also be set as ``href`` of
    142              resulting stylesheet
    143          encoding
    144              Value ``None`` defaults to encoding detection via HTTP, BOM or an
    145              @charset rule.
    146              A value overrides detected encoding for the sheet at ``href``
    147              including any imported sheets.
    148
    149          for other parameters see ``parseString``
    150          """
    151          encoding, enctype, text = cssutils.util._readUrl(href,
    152                                                           overrideEncoding=encoding)
    153          if enctype == 5:
    154              # do not used if defaulting to UTF-8
    155              encoding = None
    156
    157          if text is not None:
    158              return self.parseString(text, encoding=encoding,
    159                                      href=href, media=media, title=title)
    160
    161 -    def setFetcher(self, fetcher=None):
    162          """Replace the default URL fetch function with a custom one.
    163          The fetcher function gets a single parameter
    164
    165          ``url``
    166              the URL to read
    167
    168          and returns ``(encoding, content)`` where ``encoding`` is the HTTP
    169          charset normally given via the Content-Type header (which may simply
    170          omit the charset) and ``content`` being the (byte) string content.
    171          The Mimetype should be 'text/css' but this has to be checked by the
    172          fetcher itself (the default fetcher emits a warning if encountering
    173          a different mimetype).
    174
    175          Calling ``setFetcher`` with ``fetcher=None`` resets cssutils
    176          to use its default function.
    177          """
    178          self.__fetcher = fetcher
    179
    180      @Deprecated('Use cssutils.CSSParser().parseFile() instead.')
    181 -    def parse(self, filename, encoding=None,
    182                href=None, media=None, title=None):
    183          self.parseFile(filename, encoding, href, media, title)
    184