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

« back to all changes in this revision

Viewing changes to ivle/fileservice_lib/action.py

  • Committer: Matt Giuca
  • Date: 2010-07-22 02:12:36 UTC
  • mfrom: (1812.1.13 late-submit)
  • Revision ID: matt.giuca@gmail.com-20100722021236-k8kt4cqdtywzpk24
Merge from trunk late-submit.
Students may now submit projects after the deadline, but they are warned that the submission is late.
Lecturers are now given data on which submissions were made late, and how many days.
(LP: #598346)

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# IVLE
 
2
# Copyright (C) 2007-2008 The University of Melbourne
 
3
#
 
4
# This program is free software; you can redistribute it and/or modify
 
5
# it under the terms of the GNU General Public License as published by
 
6
# the Free Software Foundation; either version 2 of the License, or
 
7
# (at your option) any later version.
 
8
#
 
9
# This program is distributed in the hope that it will be useful,
 
10
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
11
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
12
# GNU General Public License for more details.
 
13
#
 
14
# You should have received a copy of the GNU General Public License
 
15
# along with this program; if not, write to the Free Software
 
16
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 
17
 
 
18
# Module: File Service / Action
 
19
# Author: Matt Giuca
 
20
# Date: 10/1/2008
 
21
 
 
22
# Handles actions requested by the client as part of the 2-stage process of
 
23
# fileservice (the second part being the return listing).
 
24
 
 
25
### Actions ###
 
26
 
 
27
# The most important argument is "action". This determines which action is
 
28
# taken. Note that action, and all other arguments, are ignored unless the
 
29
# request is a POST request. The other arguments depend upon the action.
 
30
# Note that paths are often specified as arguments. Paths that begin with a
 
31
# slash are taken relative to the user's home directory (the top-level
 
32
# directory seen when fileservice has no arguments or path). Paths without a
 
33
# slash are taken relative to the specified path.
 
34
 
 
35
# action=remove: Delete a file(s) or directory(s) (recursively).
 
36
#       path:   The path to the file or directory to delete. Can be specified
 
37
#               multiple times.
 
38
#
 
39
# action=move: Move or rename a file or directory.
 
40
#       from:   The path to the file or directory to be renamed.
 
41
#       to:     The path of the target filename. Error if the file already
 
42
#               exists.
 
43
#
 
44
# action=putfile: Upload a file to the student workspace.
 
45
#       path:   The path to the file to be written. Error if the target
 
46
#               file is a directory.
 
47
#       data:   Bytes to be written to the file verbatim. May either be
 
48
#               a string variable or a file upload.
 
49
#       overwrite: Optional. If supplied, the file will be overwritten.
 
50
#               Otherwise, error if path already exists.
 
51
#
 
52
# action=putfiles: Upload multiple files to the student workspace, and
 
53
#                 optionally accept zip files which will be unpacked.
 
54
#       path:   The path to the DIRECTORY to place files in. Must not be a
 
55
#               file.
 
56
#       data:   A file upload (may not be a simple string). The filename
 
57
#               will be used to determine the target filename within
 
58
#               the given path.
 
59
#       unpack: Optional. If supplied, if any data is a valid ZIP file,
 
60
#               will create a directory instead and unpack the ZIP file
 
61
#               into it.
 
62
#
 
63
# action=mkdir: Create a directory. The parent dir must exist.
 
64
#       path:   The path to a file which does not exist, but whose parent
 
65
#               does. The dir will be made with this name.
 
66
#
 
67
# The differences between putfile and putfiles are:
 
68
# * putfile can only accept a single file, and can't unpack zipfiles.
 
69
# * putfile can accept string data, doesn't have to be a file upload.
 
70
# * putfile ignores the upload filename, the entire filename is specified on
 
71
#       path. putfiles calls files after the name on the user's machine.
 
72
#
 
73
# action=paste: Copy or move the files to a specified dir.
 
74
#       src:    The path to the DIRECTORY to get the files from (relative).
 
75
#       dst:    The path to the DIRECTORY to paste the files to. Must not
 
76
#               be a file.
 
77
#       mode:   'copy' or 'move'
 
78
#       file:   File to be copied or moved, relative to src, to a destination
 
79
#               relative to dst. Can be specified multiple times.
 
80
#
 
81
# Subversion actions.
 
82
# action=svnadd: Add an existing file(s) to version control.
 
83
#       path:   The path to the file to be added. Can be specified multiple
 
84
#               times.
 
85
#
 
86
# action=svnrevert: Revert a file(s) to its state as of the current revision
 
87
#               / undo local edits.
 
88
#       path:   The path to the file to be reverted. Can be specified multiple
 
89
#               times.
 
90
#
 
91
# action=svnupdate: Bring a file up to date with the head revision.
 
92
#       path:   The path to the file to be updated. Only one file may be
 
93
#               specified.
 
94
#       revision: The revision number to update to. If not provided this
 
95
#               defaults to HEAD.
 
96
#
 
97
# action=svncommit: Commit a file(s) or directory(s) to the repository.
 
98
#       path:   The path to the file or directory to be committed. Can be
 
99
#               specified multiple times. Directories are committed
 
100
#               recursively.
 
101
#       logmsg: Text of the log message. Optional. There is a default log
 
102
#               message if unspecified.
 
103
# action=svncheckout: Checkout a file/directory from the repository.
 
104
#       path:   The [repository] path to the file or directory to be
 
105
#               checked out.
 
106
 
107
# action=svnrepomkdir: Create a directory in a repository (not WC).
 
108
#       path:   The path to the directory to be created (under the IVLE
 
109
#               repository base).
 
110
#       logmsg: Text of the log message.
 
111
 
112
# action=svnrepostat: Check if a path exists in a repository (not WC).
 
113
#       path:   The path to the directory to be checked (under the IVLE
 
114
#               repository base).
 
115
#
 
116
# action=svncleanup: Recursively clean up the working copy, removing locks,
 
117
#   resuming unfinished operations, etc.
 
118
#       path:   The path to the directory to be cleaned
 
119
#
 
120
# TODO: Implement the following actions:
 
121
#   svnupdate (done?)
 
122
# TODO: Implement ZIP unpacking in putfiles (done?).
 
123
# TODO: svnupdate needs a digest to tell the user the files that were updated.
 
124
#   This can be implemented by some message passing between action and
 
125
#   listing, and having the digest included in the listing. (Problem if
 
126
#   the listing is not a directory, but we could make it an error to do an
 
127
#   update if the path is not a directory).
 
128
 
 
129
import os
 
130
import cStringIO
 
131
import shutil
 
132
import urllib
 
133
 
 
134
import pysvn
 
135
 
 
136
from ivle import (util, studpath, zip)
 
137
from ivle.fileservice_lib.exceptions import WillNotOverwrite
 
138
import ivle.conf
 
139
import ivle.svn
 
140
 
 
141
# Make a Subversion client object (which will log in with this user's
 
142
# credentials, upon request)
 
143
svnclient = ivle.svn.create_auth_svn_client(username=ivle.conf.login,
 
144
                                            password=ivle.conf.svn_pass)
 
145
svnclient.exception_style = 0               # Simple (string) exceptions
 
146
 
 
147
DEFAULT_LOGMESSAGE = "No log message supplied."
 
148
 
 
149
# Mime types
 
150
# application/json is the "best" content type but is not good for
 
151
# debugging because Firefox just tries to download it
 
152
mime_dirlisting = "text/html"
 
153
#mime_dirlisting = "application/json"
 
154
 
 
155
class ActionError(Exception):
 
156
    """Represents an error processing an action. This can be
 
157
    raised by any of the action functions, and will be caught
 
158
    by the top-level handler, put into the HTTP response field,
 
159
    and continue.
 
160
 
 
161
    Important Security Consideration: The message passed to this
 
162
    exception will be relayed to the client.
 
163
    """
 
164
    pass
 
165
 
 
166
def handle_action(req, action, fields):
 
167
    """Perform the "action" part of the response.
 
168
    This function should only be called if the response is a POST.
 
169
    This performs the action's side-effect on the server. If unsuccessful,
 
170
    writes the X-IVLE-Action-Error header to the request object. Otherwise,
 
171
    does not touch the request object. Does NOT write any bytes in response.
 
172
 
 
173
    May throw an ActionError. The caller should put this string into the
 
174
    X-IVLE-Action-Error header, and then continue normally.
 
175
 
 
176
    action: String, the action requested. Not sanitised.
 
177
    fields: FieldStorage object containing all arguments passed.
 
178
    """
 
179
    global actions_table        # Table of function objects
 
180
    try:
 
181
        action = actions_table[action]
 
182
    except KeyError:
 
183
        # Default, just send an error but then continue
 
184
        raise ActionError("Unknown action")
 
185
    return action(req, fields)
 
186
 
 
187
def actionpath_to_urlpath(req, path):
 
188
    """Determines the URL path (relative to the student home) upon which the
 
189
    action is intended to act. See actionpath_to_local.
 
190
    """
 
191
    if path is None:
 
192
        return req.path
 
193
    elif len(path) > 0 and path[0] == os.sep:
 
194
        # Relative to student home
 
195
        return path[1:]
 
196
    else:
 
197
        # Relative to req.path
 
198
        return os.path.join(req.path, path)
 
199
 
 
200
def actionpath_to_local(req, path):
 
201
    """Determines the local path upon which an action is intended to act.
 
202
    Note that fileservice actions accept two paths: the request path,
 
203
    and the "path" argument given to the action.
 
204
    According to the rules, if the "path" argument begins with a '/' it is
 
205
    relative to the user's home; if it does not, it is relative to the
 
206
    supplied path.
 
207
 
 
208
    This resolves the path, given the request and path argument.
 
209
 
 
210
    May raise an ActionError("Invalid path"). The caller is expected to
 
211
    let this fall through to the top-level handler, where it will be
 
212
    put into the HTTP response field. Never returns None.
 
213
 
 
214
    Does not mutate req.
 
215
    """
 
216
    r = studpath.to_home_path(actionpath_to_urlpath(req, path))
 
217
    if r is None:
 
218
        raise ActionError("Invalid path")
 
219
    return r
 
220
 
 
221
def movefile(req, frompath, topath, copy=False):
 
222
    """Performs a file move, resolving filenames, checking for any errors,
 
223
    and throwing ActionErrors if necessary. Can also be used to do a copy
 
224
    operation instead.
 
225
 
 
226
    frompath and topath are straight paths from the client. Will be checked.
 
227
    """
 
228
    # TODO: Do an SVN mv if the file is versioned.
 
229
    # TODO: Disallow tampering with student's home directory
 
230
    if frompath is None or topath is None:
 
231
        raise ActionError("Required field missing")
 
232
    frompath = actionpath_to_local(req, frompath)
 
233
    topath = actionpath_to_local(req, topath)
 
234
    if not os.path.exists(frompath):
 
235
        raise ActionError("The source file does not exist")
 
236
    if os.path.exists(topath):
 
237
        if frompath == topath:
 
238
            raise ActionError("Source and destination are the same")
 
239
        raise ActionError("A file already exists with that name")
 
240
 
 
241
    try:
 
242
        if copy:
 
243
            if os.path.isdir(frompath):
 
244
                shutil.copytree(frompath, topath)
 
245
            else:
 
246
                shutil.copy2(frompath, topath)
 
247
        else:
 
248
            shutil.move(frompath, topath)
 
249
    except OSError:
 
250
        raise ActionError("Could not move the file specified")
 
251
    except shutil.Error:
 
252
        raise ActionError("Could not move the file specified")
 
253
 
 
254
def svn_movefile(req, frompath, topath, copy=False):
 
255
    """Performs an svn move, resolving filenames, checking for any errors,
 
256
    and throwing ActionErrors if necessary. Can also be used to do a copy
 
257
    operation instead.
 
258
 
 
259
    frompath and topath are straight paths from the client. Will be checked.
 
260
    """
 
261
    if frompath is None or topath is None:
 
262
        raise ActionError("Required field missing")
 
263
    frompath = actionpath_to_local(req, frompath)
 
264
    topath = actionpath_to_local(req, topath)
 
265
    if not os.path.exists(frompath):
 
266
        raise ActionError("The source file does not exist")
 
267
    if os.path.exists(topath):
 
268
        if frompath == topath:
 
269
            raise ActionError("Source and destination are the same")
 
270
        raise ActionError("A file already exists with that name")
 
271
 
 
272
    try:
 
273
        if copy:
 
274
            svnclient.copy(frompath, topath)
 
275
        else:
 
276
            svnclient.move(frompath, topath)
 
277
    except OSError:
 
278
        raise ActionError("Could not move the file specified")
 
279
    except pysvn.ClientError:
 
280
        raise ActionError("Could not move the file specified")  
 
281
 
 
282
 
 
283
### ACTIONS ###
 
284
 
 
285
def action_delete(req, fields):
 
286
    # TODO: Disallow removal of student's home directory
 
287
    """Removes a list of files or directories.
 
288
 
 
289
    Reads fields: 'path' (multiple)
 
290
    """
 
291
    paths = fields.getlist('path')
 
292
    goterror = False
 
293
    for path in paths:
 
294
        path = actionpath_to_local(req, path)
 
295
        try:
 
296
            if os.path.isdir(path):
 
297
                shutil.rmtree(path)
 
298
            else:
 
299
                os.remove(path)
 
300
        except OSError:
 
301
            goterror = True
 
302
        except shutil.Error:
 
303
            goterror = True
 
304
    if goterror:
 
305
        if len(paths) == 1:
 
306
            raise ActionError("Could not delete the file specified")
 
307
        else:
 
308
            raise ActionError(
 
309
                "Could not delete one or more of the files specified")
 
310
 
 
311
def action_move(req, fields):
 
312
    # TODO: Do an SVN mv if the file is versioned.
 
313
    # TODO: Disallow tampering with student's home directory
 
314
    """Removes a list of files or directories.
 
315
 
 
316
    Reads fields: 'from', 'to'
 
317
    """
 
318
    frompath = fields.getfirst('from')
 
319
    topath = fields.getfirst('to')
 
320
    svn = fields.getfirst('svn')
 
321
    if svn:
 
322
        svn_movefile(req, frompath, topath)
 
323
    else:
 
324
        movefile(req, frompath, topath)
 
325
 
 
326
def action_mkdir(req, fields):
 
327
    """Creates a directory with the given path.
 
328
    Reads fields: 'path'
 
329
    """
 
330
    path = fields.getfirst('path')
 
331
    if path is None:
 
332
        raise ActionError("Required field missing")
 
333
    path = actionpath_to_local(req, path)
 
334
 
 
335
    if os.path.exists(path):
 
336
        raise ActionError("A file already exists with that name")
 
337
 
 
338
    # Create the directory
 
339
    try:
 
340
        os.mkdir(path)
 
341
    except OSError:
 
342
        raise ActionError("Could not create directory")
 
343
 
 
344
def action_putfile(req, fields):
 
345
    """Writes data to a file, overwriting it if it exists and creating it if
 
346
    it doesn't.
 
347
 
 
348
    Reads fields: 'path', 'data' (file upload), 'overwrite'
 
349
    """
 
350
    # TODO: Read field "unpack".
 
351
    # Important: Data is "None" if the file submitted is empty.
 
352
    path = fields.getfirst('path')
 
353
    data = fields.getfirst('data')
 
354
    if path is None:
 
355
        raise ActionError("Required field missing")
 
356
    if data is None:
 
357
        # Workaround - field reader treats "" as None, so this is the only
 
358
        # way to allow blank file uploads
 
359
        data = ""
 
360
    path = actionpath_to_local(req, path)
 
361
 
 
362
    if data is not None:
 
363
        data = cStringIO.StringIO(data)
 
364
 
 
365
    overwrite = fields.getfirst('overwrite')
 
366
    if overwrite is None:
 
367
        overwrite = False
 
368
    else:
 
369
        overwrite = True
 
370
 
 
371
    if overwrite:
 
372
        # Overwrite files; but can't if it's a directory
 
373
        if os.path.isdir(path):
 
374
            raise ActionError("A directory already exists "
 
375
                    + "with that name")
 
376
    else:
 
377
        if os.path.exists(path):
 
378
            raise ActionError("A file already exists with that name")
 
379
 
 
380
    # Copy the contents of file object 'data' to the path 'path'
 
381
    try:
 
382
        dest = open(path, 'wb')
 
383
        if data is not None:
 
384
            shutil.copyfileobj(data, dest)
 
385
    except (IOError, OSError), e:
 
386
        raise ActionError("Could not write to target file: %s" % e.strerror)
 
387
 
 
388
def action_putfiles(req, fields):
 
389
    """Writes data to one or more files in a directory, overwriting them if
 
390
    it they exist.
 
391
 
 
392
    Reads fields: 'path', 'data' (file upload, multiple), 'unpack'
 
393
    """
 
394
    # Important: Data is "None" if the file submitted is empty.
 
395
    path = fields.getfirst('path')
 
396
    data = fields['data']
 
397
    if type(data) != type([]):
 
398
        data = [data]
 
399
    unpack = fields.getfirst('unpack')
 
400
    if unpack is None:
 
401
        unpack = False
 
402
    else:
 
403
        unpack = True
 
404
    if path is None:
 
405
        raise ActionError("Required field missing")
 
406
    path = actionpath_to_urlpath(req, path)
 
407
    goterror = False
 
408
 
 
409
    for datum in data:
 
410
        # Each of the uploaded files
 
411
        filepath = os.path.join(path, datum.filename)
 
412
        filepath_local = studpath.to_home_path(filepath)
 
413
        if os.path.isdir(filepath_local):
 
414
            raise ActionError("A directory already exists "
 
415
                    + "with that name")
 
416
        else:
 
417
            if os.path.exists(filepath_local):
 
418
                raise ActionError("A file already exists with that name")
 
419
        filedata = datum.file
 
420
 
 
421
        if unpack and datum.filename.lower().endswith(".zip"):
 
422
            # A zip file - unpack it instead of just copying
 
423
            # TODO: Use the magic number instead of file extension
 
424
            # Note: Just unzip into the current directory (ignore the
 
425
            # filename)
 
426
            try:
 
427
                # First get the entire path (within jail)
 
428
                abspath = studpath.to_home_path(path)
 
429
                abspath = os.path.join(os.sep, abspath)
 
430
                zip.unzip(abspath, filedata)
 
431
            except (OSError, IOError):
 
432
                goterror = True
 
433
            except WillNotOverwrite, e:
 
434
                raise ActionError("File '" + e.filename + "' already exists.")
 
435
        else:
 
436
            # Not a zip file
 
437
            filepath_local = studpath.to_home_path(filepath)
 
438
            if filepath_local is None:
 
439
                raise ActionError("Invalid path")
 
440
 
 
441
            # Copy the contents of file object 'data' to the path 'path'
 
442
            try:
 
443
                dest = open(filepath_local, 'wb')
 
444
                if data is not None:
 
445
                    shutil.copyfileobj(filedata, dest)
 
446
            except (OSError, IOError):
 
447
                # TODO: Be more descriptive.
 
448
                goterror = True
 
449
 
 
450
    if goterror:
 
451
        if len(data) == 1:
 
452
            raise ActionError("Could not write to target file")
 
453
        else:
 
454
            raise ActionError(
 
455
                "Could not write to one or more of the target files")
 
456
 
 
457
def action_paste(req, fields):
 
458
    """Performs the copy or move action with the files specified.
 
459
    Copies/moves the files to the specified directory.
 
460
 
 
461
    Reads fields: 'src', 'dst', 'mode', 'file' (multiple).
 
462
    src: Base path that all the files are relative to (source).
 
463
    dst: Destination path to paste into.
 
464
    mode: 'copy' or 'move'.
 
465
    file: (Multiple) Files relative to base, which will be copied
 
466
        or moved to new locations relative to path.
 
467
    """
 
468
    errormsg = None
 
469
 
 
470
    dst = fields.getfirst('dst')
 
471
    src = fields.getfirst('src')
 
472
    mode = fields.getfirst('mode')
 
473
    files = fields.getlist('file')
 
474
    if dst is None or src is None or mode is None:
 
475
        raise ActionError("Required field missing")
 
476
 
 
477
    dst_local = actionpath_to_local(req, dst)
 
478
    if not os.path.isdir(dst_local):
 
479
        raise ActionError("dst is not a directory")
 
480
 
 
481
    errorfiles = []
 
482
    for file in files:
 
483
        # The source must not be interpreted as relative to req.path
 
484
        # Add a slash (relative to top-level)
 
485
        if src[:1] != '/':
 
486
            src = '/' + src
 
487
        frompath = os.path.join(src, file)
 
488
        # The destination is found by taking just the basename of the file
 
489
        topath = os.path.join(dst, os.path.basename(file))
 
490
        try:
 
491
            if mode == "copy":
 
492
                movefile(req, frompath, topath, True)
 
493
            elif mode == "move":
 
494
                movefile(req, frompath, topath, False)
 
495
            elif mode == "svncopy":
 
496
                svn_movefile(req, frompath, topath, True)
 
497
            elif mode == "svnmove":
 
498
                svn_movefile(req, frompath, topath, False)
 
499
            else:
 
500
                raise ActionError("Invalid mode (must be '(svn)copy' or '(svn)move')")
 
501
        except ActionError, message:
 
502
            # Store the error for later; we want to copy as many as possible
 
503
            if errormsg is None:
 
504
                errormsg = message
 
505
            else:
 
506
                # Multiple errors; generic message
 
507
                errormsg = "One or more files could not be pasted"
 
508
            # Add this file to errorfiles; it will be put back on the
 
509
            # clipboard for possible future pasting.
 
510
            errorfiles.append(file)
 
511
    if errormsg is not None:
 
512
        raise ActionError(errormsg)
 
513
 
 
514
    # XXX errorfiles contains a list of files that couldn't be pasted.
 
515
    # we currently do nothing with this.
 
516
 
 
517
def action_publish(req,fields):
 
518
    """Marks the folder as published by adding a '.published' file to the 
 
519
    directory and ensuring that the parent directory permissions are correct
 
520
 
 
521
    Reads fields: 'path'
 
522
    """
 
523
    paths = fields.getlist('path')
 
524
    user = util.split_path(req.path)[0]
 
525
    homedir = "/home/%s" % user
 
526
    if len(paths):
 
527
        paths = map(lambda path: actionpath_to_local(req, path), paths)
 
528
    else:
 
529
        paths = [studpath.to_home_path(req.path)]
 
530
 
 
531
    # Set all the dirs in home dir world browsable (o+r,o+x)
 
532
    #FIXME: Should really only do those in the direct path not all of the 
 
533
    # folders in a students home directory
 
534
    for root,dirs,files in os.walk(homedir):
 
535
        os.chmod(root, os.stat(root).st_mode|0005)
 
536
 
 
537
    try:
 
538
        for path in paths:
 
539
            if os.path.isdir(path):
 
540
                pubfile = open(os.path.join(path,'.published'),'w')
 
541
                pubfile.write("This directory is published\n")
 
542
                pubfile.close()
 
543
            else:
 
544
                raise ActionError("Can only publish directories")
 
545
    except OSError, e:
 
546
        raise ActionError("Directory could not be published")
 
547
 
 
548
def action_unpublish(req,fields):
 
549
    """Marks the folder as unpublished by removing a '.published' file in the 
 
550
    directory (if it exits). It does not change the permissions of the parent 
 
551
    directories.
 
552
 
 
553
    Reads fields: 'path'
 
554
    """
 
555
    paths = fields.getlist('path')
 
556
    if len(paths):
 
557
        paths = map(lambda path: actionpath_to_local(req, path), paths)
 
558
    else:
 
559
        paths = [studpath.to_home_path(req.path)]
 
560
 
 
561
    try:
 
562
        for path in paths:
 
563
            if os.path.isdir(path):
 
564
                pubfile = os.path.join(path,'.published')
 
565
                if os.path.isfile(pubfile):
 
566
                    os.remove(pubfile)
 
567
            else:
 
568
                raise ActionError("Can only unpublish directories")
 
569
    except OSError, e:
 
570
        raise ActionError("Directory could not be unpublished")
 
571
 
 
572
 
 
573
def action_svnadd(req, fields):
 
574
    """Performs a "svn add" to each file specified.
 
575
 
 
576
    Reads fields: 'path' (multiple)
 
577
    """
 
578
    paths = fields.getlist('path')
 
579
    paths = map(lambda path: actionpath_to_local(req, path).decode('utf-8'),
 
580
                paths)
 
581
 
 
582
    try:
 
583
        svnclient.add(paths, recurse=True, force=True)
 
584
    except pysvn.ClientError, e:
 
585
        raise ActionError(str(e))
 
586
 
 
587
def action_svnremove(req, fields):
 
588
    """Performs a "svn remove" on each file specified.
 
589
 
 
590
    Reads fields: 'path' (multiple)
 
591
    """
 
592
    paths = fields.getlist('path')
 
593
    paths = map(lambda path: actionpath_to_local(req, path).decode('utf-8'),
 
594
                paths)
 
595
 
 
596
    try:
 
597
        svnclient.remove(paths, force=True)
 
598
    except pysvn.ClientError, e:
 
599
        raise ActionError(str(e))
 
600
 
 
601
def action_svnupdate(req, fields):
 
602
    """Performs a "svn update" to each file specified.
 
603
 
 
604
    Reads fields: 'path' and 'revision'
 
605
    """
 
606
    path = fields.getfirst('path')
 
607
    revision = fields.getfirst('revision')
 
608
    if path is None:
 
609
        raise ActionError("Required field missing")
 
610
    if revision is None:
 
611
        revision = pysvn.Revision( pysvn.opt_revision_kind.head )
 
612
    else:
 
613
        try:
 
614
            revision = pysvn.Revision(pysvn.opt_revision_kind.number,
 
615
                    int(revision))
 
616
        except ValueError, e:
 
617
            raise ActionError("Bad revision number: '%s'"%revision,)
 
618
    path = actionpath_to_local(req, path).decode('utf-8')
 
619
 
 
620
    try:
 
621
        svnclient.update(path, recurse=True, revision=revision)
 
622
    except pysvn.ClientError, e:
 
623
        raise ActionError(str(e))
 
624
 
 
625
def action_svnresolved(req, fields):
 
626
    """Performs a "svn resolved" to each file specified.
 
627
 
 
628
    Reads fields: 'path'
 
629
    """
 
630
    path = fields.getfirst('path')
 
631
    if path is None:
 
632
        raise ActionError("Required field missing")
 
633
    path = actionpath_to_local(req, path).decode('utf-8')
 
634
 
 
635
    try:
 
636
        svnclient.resolved(path, recurse=True)
 
637
    except pysvn.ClientError, e:
 
638
        raise ActionError(str(e))
 
639
 
 
640
def action_svnrevert(req, fields):
 
641
    """Performs a "svn revert" to each file specified.
 
642
 
 
643
    Reads fields: 'path' (multiple)
 
644
    """
 
645
    paths = fields.getlist('path')
 
646
    paths = map(lambda path: actionpath_to_local(req, path).decode('utf-8'),
 
647
                paths)
 
648
 
 
649
    try:
 
650
        svnclient.revert(paths, recurse=True)
 
651
    except pysvn.ClientError, e:
 
652
        raise ActionError(str(e))
 
653
 
 
654
def action_svncommit(req, fields):
 
655
    """Performs a "svn commit" to each file specified.
 
656
 
 
657
    Reads fields: 'path' (multiple), 'logmsg' (optional)
 
658
    """
 
659
    paths = fields.getlist('path')
 
660
    if len(paths):
 
661
        paths = map(lambda path:actionpath_to_local(req,path).decode('utf-8'),
 
662
                    paths)
 
663
    else:
 
664
        paths = [studpath.to_home_path(req.path).decode('utf-8')]
 
665
    logmsg = str(fields.getfirst('logmsg',
 
666
                 DEFAULT_LOGMESSAGE)).decode('utf-8')
 
667
    if logmsg == '': logmsg = DEFAULT_LOGMESSAGE
 
668
 
 
669
    try:
 
670
        svnclient.checkin(paths, logmsg, recurse=True)
 
671
    except pysvn.ClientError, e:
 
672
        raise ActionError(str(e))
 
673
 
 
674
def action_svncheckout(req, fields):
 
675
    """Performs a "svn checkout" of the first path into the second path.
 
676
 
 
677
    Reads fields: 'path'    (multiple)
 
678
    """
 
679
    paths = fields.getlist('path')
 
680
    if len(paths) != 2:
 
681
        raise ActionError("usage: svncheckout url local-path")
 
682
    url = ivle.conf.svn_addr + "/" + urllib.quote(paths[0])
 
683
    local_path = actionpath_to_local(req, str(paths[1]))
 
684
    url = url.decode('utf-8')
 
685
    local_path = local_path.decode('utf-8')
 
686
    try:
 
687
        svnclient.checkout(url, local_path, recurse=True)
 
688
    except pysvn.ClientError, e:
 
689
        raise ActionError(str(e))
 
690
 
 
691
def action_svnrepomkdir(req, fields):
 
692
    """Performs a "svn mkdir" on a path under the IVLE SVN root.
 
693
 
 
694
    Reads fields: 'path'
 
695
    """
 
696
    path = fields.getfirst('path')
 
697
    logmsg = fields.getfirst('logmsg')
 
698
    url = (ivle.conf.svn_addr + "/" + urllib.quote(path)).decode('utf-8')
 
699
    try:
 
700
        svnclient.mkdir(url, log_message=logmsg)
 
701
    except pysvn.ClientError, e:
 
702
        raise ActionError(str(e))
 
703
 
 
704
def action_svnrepostat(req, fields):
 
705
    """Discovers whether a path exists in a repo under the IVLE SVN root.
 
706
 
 
707
    If it does exist, returns a dict containing its metadata.
 
708
 
 
709
    Reads fields: 'path'
 
710
    """
 
711
    path = fields.getfirst('path')
 
712
    url = (ivle.conf.svn_addr + "/" + urllib.quote(path)).decode('utf-8')
 
713
    svnclient.exception_style = 1
 
714
 
 
715
    try:
 
716
        info = svnclient.info2(url,
 
717
            revision=pysvn.Revision(pysvn.opt_revision_kind.head))[0][1]
 
718
        return {'svnrevision': info['rev'].number
 
719
                  if info['rev'] and
 
720
                     info['rev'].kind == pysvn.opt_revision_kind.number
 
721
                  else None}
 
722
    except pysvn.ClientError, e:
 
723
        # Error code 170000 means ENOENT in this revision.
 
724
        if e[1][0][1] == 170000:
 
725
            req.status = 404
 
726
            raise ActionError('The specified repository path does not exist')
 
727
        else:
 
728
            raise ActionError(str(e[0]))
 
729
 
 
730
 
 
731
def action_svncleanup(req, fields):
 
732
    """Recursively clean up the working copy, removing locks, resuming 
 
733
    unfinished operations, etc.
 
734
        path:   The path to be cleaned"""
 
735
 
 
736
    path = fields.getfirst('path')
 
737
    if path is None:
 
738
        raise ActionError("Required field missing")
 
739
    path = actionpath_to_local(req, path).decode('utf-8')
 
740
 
 
741
    try:
 
742
        svnclient.cleanup(path)
 
743
    except pysvn.ClientError, e:
 
744
        raise ActionError(str(e))
 
745
 
 
746
 
 
747
# Table of all action functions #
 
748
# Each function has the interface f(req, fields).
 
749
 
 
750
actions_table = {
 
751
    "delete" : action_delete,
 
752
    "move" : action_move,
 
753
    "mkdir" : action_mkdir,
 
754
    "putfile" : action_putfile,
 
755
    "putfiles" : action_putfiles,
 
756
    "paste" : action_paste,
 
757
    "publish" : action_publish,
 
758
    "unpublish" : action_unpublish,
 
759
 
 
760
    "svnadd" : action_svnadd,
 
761
    "svnremove" : action_svnremove,
 
762
    "svnupdate" : action_svnupdate,
 
763
    "svnresolved" : action_svnresolved,
 
764
    "svnrevert" : action_svnrevert,
 
765
    "svncommit" : action_svncommit,
 
766
    "svncheckout" : action_svncheckout,
 
767
    "svnrepomkdir" : action_svnrepomkdir,
 
768
    "svnrepostat" : action_svnrepostat,
 
769
    "svncleanup" : action_svncleanup,
 
770
}