~azzar1/unity/add-show-desktop-key

« back to all changes in this revision

Viewing changes to ivle/util.py

  • Committer: Matt Giuca
  • Date: 2009-05-19 02:54:08 UTC
  • mfrom: (1258 trunk)
  • mto: This revision was merged to the branch mainline in revision 1322.
  • Revision ID: matt.giuca@gmail.com-20090519025408-19c7cjl7w6ot6frm
MergedĀ fromĀ trunk.

Show diffs side-by-side

added added

removed removed

Lines of Context:
20
20
# Date: 12/12/2007
21
21
 
22
22
# Contains common utility functions.
23
 
# Also initialises mime types library. You must import util before using
24
 
# Python's builtin mimetypes module to make sure local settings are applied.
25
23
 
26
24
import os
27
 
import mimetypes
28
 
import datetime
29
 
 
30
 
import ivle.conf
31
 
import ivle.conf.mimetypes
 
25
import sys
 
26
import stat
32
27
 
33
28
class IVLEError(Exception):
34
 
    """
35
 
    This is the "standard" exception class for IVLE errors.
36
 
    It is the ONLY exception which should propagate to the top - it will then
37
 
    be displayed to the user as an HTTP error with the given code.
38
 
 
39
 
    All other exceptions are considered IVLE bugs and should not occur
40
 
    (they will display a traceback).
41
 
 
42
 
    This error should not be raised directly. Call req.throw_error.
 
29
    """Legacy general IVLE exception.
 
30
 
 
31
    This is the old "standard" exception class for IVLE errors. It is only
 
32
    used in fileservice, and should not be used in any new code.
43
33
    """
44
34
    def __init__(self, httpcode, message=None):
45
35
        self.httpcode = httpcode
47
37
        self.args = (httpcode, message)
48
38
 
49
39
class IVLEJailError(Exception):
50
 
    """
 
40
    """Exception proxying an in-jail error.
 
41
 
51
42
    This exception indicates an error that occurred inside an IVLE CGI script
52
43
    inside the jail. It should never be raised directly - only by the 
53
44
    interpreter.
70
61
    def __repr__(self):
71
62
        return "<Fake %s %s>"%(self.type, self.name)
72
63
 
73
 
 
74
 
def make_path(path):
75
 
    """Given a path relative to the IVLE root, makes the path relative to the
76
 
    site root using ivle.conf.root_dir. This path can be used in URLs sent to
77
 
    the client."""
78
 
    return os.path.join(ivle.conf.root_dir, path)
79
 
 
80
 
def make_local_path(path):
81
 
    """Given a path relative to the IVLE root, on the local file system, makes
82
 
    the path relative to the root using ivle.conf.share_path. This path can
83
 
    be used in reading files from the local file system."""
84
 
    return os.path.join(ivle.conf.share_path, 'www', path)
85
 
 
86
 
def unmake_path(path):
87
 
    """Given a path relative to the site root, makes the path relative to the
88
 
    IVLE root by removing ivle.conf.root_dir if it appears at the beginning. If
89
 
    it does not appear at the beginning, returns path unchanged. Also
90
 
    normalises the path."""
91
 
    path = os.path.normpath(path)
92
 
    root = os.path.normpath(ivle.conf.root_dir)
93
 
 
94
 
    if path.startswith(root):
95
 
        path = path[len(root):]
96
 
        # Take out the slash as well
97
 
        if len(path) > 0 and path[0] == os.sep:
98
 
            path = path[1:]
99
 
 
100
 
    return path
101
 
 
102
64
def split_path(path):
103
65
    """Given a path, returns a tuple consisting of the top-level directory in
104
66
    the path, and the rest of the path. Note that both items in the tuple will
134
96
    else:
135
97
        return tuple(splitpath)
136
98
 
137
 
def open_exercise_file(exercisename):
138
 
    """Given an exercise name, opens the corresponding XML file for reading.
139
 
    Returns None if the exercise file was not found.
140
 
    (For tutorials / worksheets).
141
 
    """
142
 
    # First normalise the path
143
 
    exercisename = os.path.normpath(exercisename)
144
 
    # Now if it begins with ".." or separator, then it's illegal
145
 
    if exercisename.startswith("..") or exercisename.startswith(os.sep):
146
 
        exercisefile = None
147
 
    else:
148
 
        exercisefile = os.path.join(ivle.conf.exercises_base, exercisename)
149
 
 
150
 
    try:
151
 
        return open(exercisefile)
152
 
    except (TypeError, IOError):    # TypeError if exercisefile == None
153
 
        return None
154
 
 
155
 
# Initialise mime types library
156
 
mimetypes.init()
157
 
for (ext, mimetype) in ivle.conf.mimetypes.additional_mime_types.items():
158
 
    mimetypes.add_type(mimetype, ext)
159
 
 
160
 
def nice_filetype(filename):
161
 
    """Given a filename or basename, returns a "friendly" name for that
162
 
    file's type.
163
 
    eg. nice_mimetype("file.py") == "Python source code".
164
 
        nice_filetype("file.bzg") == "BZG file".
165
 
        nice_filetype("directory/") == "Directory".
166
 
    """
167
 
    if filename[-1] == os.sep:
168
 
        return "Directory"
169
 
    else:
170
 
        try:
171
 
            return ivle.conf.mimetypes.nice_mimetypes[
172
 
                mimetypes.guess_type(filename)[0]]
173
 
        except KeyError:
174
 
            filename = os.path.basename(filename)
175
 
            try:
176
 
                return filename[filename.rindex('.')+1:].upper() + " file"
177
 
            except ValueError:
178
 
                return "File"
179
 
 
180
 
def get_terms_of_service():
181
 
    """
182
 
    Sends the Terms of Service document to the req object.
183
 
    This consults conf to find out where the TOS is located on disk, and sends
184
 
    that. If it isn't found, it sends a generic message explaining to admins
185
 
    how to create a real one.
186
 
    """
187
 
    try:
188
 
        return open(ivle.conf.tos_path).read()
189
 
    except IOError:
190
 
        return """\
191
 
<p><b>*** SAMPLE ONLY ***</b></p>
192
 
<p>This is the text of the IVLE Terms of Service.</p>
193
 
<p>The administrator should create a license file with an appropriate
194
 
"Terms of Service" license for your organisation.</p>
195
 
<h2>Instructions for Administrators</h2>
196
 
<p>You are seeing this message because you have not configured a Terms of
197
 
Service document.</p>
198
 
<p>When you configured IVLE, you specified a path to the Terms of Service
199
 
document (this is found in <b><tt>ivle/conf/conf.py</tt></b> under
200
 
"<tt>tos_path</tt>").</p>
201
 
<p>Create a file at this location; an HTML file with the appropriately-worded
202
 
license.</p>
203
 
<p>This should be a normal XHTML file, except it should not contain
204
 
<tt>html</tt>, <tt>head</tt> or <tt>body</tt> elements - it should
205
 
just be the contents of a body element (IVLE will wrap it accordingly).</p>
206
 
<p>This will automatically be used as the license text instead of this
207
 
placeholder text.</p>
208
 
"""
209
 
 
210
 
def parse_iso8601(str):
211
 
    """Parses ISO8601 string into a datetime object."""
212
 
    # FIXME: Terrific hack that means we only accept the format that is 
213
 
    # produced by json.js module when it encodes date objects.
214
 
    return datetime.datetime.strptime(str, "%Y-%m-%dT%H:%M:%SZ")
 
99
def relpath(path, start=os.path.curdir):
 
100
    """Return a relative version of a path.
 
101
    XXX Backported from Python 2.6 posixpath.py.
 
102
    """
 
103
 
 
104
    if not path:
 
105
        raise ValueError("no path specified")
 
106
 
 
107
    start_list = os.path.abspath(start).split(os.path.sep)
 
108
    path_list = os.path.abspath(path).split(os.path.sep)
 
109
 
 
110
    # Work out how much of the filepath is shared by start and path.
 
111
    i = len(os.path.commonprefix([start_list, path_list]))
 
112
 
 
113
    rel_list = [os.path.pardir] * (len(start_list)-i) + path_list[i:]
 
114
    if not rel_list:
 
115
        return os.path.curdir
 
116
    return os.path.join(*rel_list)
215
117
 
216
118
def incomplete_utf8_sequence(byteseq):
217
 
    """
218
 
    str -> int
 
119
    """Calculate the completeness of a UTF-8 encoded string.
 
120
 
219
121
    Given a UTF-8-encoded byte sequence (str), returns the number of bytes at
220
122
    the end of the string which comprise an incomplete UTF-8 character
221
123
    sequence.
293
195
        return count
294
196
 
295
197
def object_to_dict(attrnames, obj):
296
 
    """
297
 
    Convert an object into a dictionary. This takes a shallow copy of the
298
 
    object.
299
 
    attrnames: Set (or iterable) of names of attributes to be copied into the
300
 
        dictionary. (We don't auto-lookup, because this function needs to be
301
 
        used on magical objects).
 
198
    """Convert an object into a dictionary.
 
199
 
 
200
    This takes a shallow copy of the object.
 
201
 
 
202
    @param attrnames: Set (or iterable) of names of attributes to be copied
 
203
                      into the dictionary. (We don't auto-lookup, because this
 
204
                      function needs to be used on magical objects).
302
205
    """
303
206
    return dict((k, getattr(obj, k))
304
207
        for k in attrnames if not k.startswith('_'))
 
208
 
 
209
def safe_rmtree(path, ignore_errors=False, onerror=None):
 
210
    """Recursively delete a directory tree.
 
211
 
 
212
    Copied from shutil.rmtree from Python 2.6, which does not follow symbolic
 
213
    links (it is otherwise unsafe to call as root on untrusted directories; do
 
214
    not use shutil.rmtree in this case, as you may be running Python 2.5).
 
215
 
 
216
    If ignore_errors is set, errors are ignored; otherwise, if onerror
 
217
    is set, it is called to handle the error with arguments (func,
 
218
    path, exc_info) where func is os.listdir, os.remove, or os.rmdir;
 
219
    path is the argument to that function that caused it to fail; and
 
220
    exc_info is a tuple returned by sys.exc_info().  If ignore_errors
 
221
    is false and onerror is None, an exception is raised.
 
222
 
 
223
    """
 
224
    if ignore_errors:
 
225
        def onerror(*args):
 
226
            pass
 
227
    elif onerror is None:
 
228
        def onerror(*args):
 
229
            raise
 
230
    try:
 
231
        if os.path.islink(path):
 
232
            # symlinks to directories are forbidden, see bug #1669
 
233
            raise OSError("Cannot call safe_rmtree on a symbolic link")
 
234
    except OSError:
 
235
        onerror(os.path.islink, path, sys.exc_info())
 
236
        # can't continue even if onerror hook returns
 
237
        return
 
238
    names = []
 
239
    try:
 
240
        names = os.listdir(path)
 
241
    except os.error, err:
 
242
        onerror(os.listdir, path, sys.exc_info())
 
243
    for name in names:
 
244
        fullname = os.path.join(path, name)
 
245
        try:
 
246
            mode = os.lstat(fullname).st_mode
 
247
        except os.error:
 
248
            mode = 0
 
249
        if stat.S_ISDIR(mode):
 
250
            safe_rmtree(fullname, ignore_errors, onerror)
 
251
        else:
 
252
            try:
 
253
                os.remove(fullname)
 
254
            except os.error, err:
 
255
                onerror(os.remove, fullname, sys.exc_info())
 
256
    try:
 
257
        os.rmdir(path)
 
258
    except os.error:
 
259
        onerror(os.rmdir, path, sys.exc_info())