summaryrefslogtreecommitdiff
path: root/pystache/loader.py
blob: f069d00b94e8aaddf7c68193c371e70047d1cfff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# coding: utf-8

"""
This module provides a Reader class to read a template given a path.

"""

from __future__ import with_statement

import os
import sys


DEFAULT_DECODE_ERRORS = 'strict'


class Reader(object):

    def __init__(self, encoding=None, decode_errors=None):
        """
        Construct a template reader.

        Arguments:

          encoding: the file encoding.  This is the name of the encoding to
            use when converting file contents to unicode.  This name is
            passed as the encoding argument to Python's built-in function
            unicode().  Defaults to the encoding name returned by
            sys.getdefaultencoding().

          decode_errors: the string to pass as the errors argument to the
            built-in function unicode() when converting file contents to
            unicode.  Defaults to "strict".

        """
        if decode_errors is None:
            decode_errors = DEFAULT_DECODE_ERRORS

        if encoding is None:
            encoding = sys.getdefaultencoding()

        self.decode_errors = decode_errors
        self.encoding = encoding

    def unicode(self, s, encoding=None):
        """
        Call Python's built-in function unicode(), and return the result.

        For unicode strings (or unicode subclasses), this function calls
        Python's unicode() without the encoding and errors arguments.
        Thus, unlike Python's built-in unicode(), it is okay to pass unicode
        strings to this function.  (Passing a unicode string to Python's
        unicode() with the encoding argument throws the following
        error: "TypeError: decoding Unicode is not supported.")

        """
        if isinstance(s, unicode):
            return unicode(s)

        if encoding is None:
            encoding = self.encoding

        return unicode(s, encoding, self.decode_errors)

    def read(self, path, encoding=None):
        """
        Read the template at the given path, and return it as a unicode string.

        """
        with open(path, 'r') as f:
            text = f.read()

        return self.unicode(text, encoding)