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