Cache the file only if not yet cached !
[confparser-old] / basicvalidator.py
1 # -*- coding: iso-8859-1 -*-
2
3 #
4 # Basic validator
5 # Copyright (C) 2005  Frédéric Jolliton <frederic@jolliton.com>
6 #
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
11 #
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
20 #
21
22 #
23 # Base module to check structure validity of a configuration file.
24 #
25
26 class Error( Exception ) : pass
27
28 def error( what ) :
29
30         raise Error( what )
31
32 class Validator :
33
34         def __init__( self , name ) :
35
36                 self.name = name
37
38         def descend( self , item ) :
39
40                 '''Return a validator for the contents
41                 of the node 'item', or throw an exception.'''
42
43                 error( 'Invalid keyword `%r\' in %r.' % ( item , self.name ) )
44
45         def check( self , values ) :
46
47                 '''Check node values.'''
48
49                 if values :
50                         error( 'Unexpected values %r for %r.' % ( values , self.name ) )
51
52         def valid( self ) :
53
54                 '''Called once node contents is valided.'''
55
56                 pass
57
58 def validate( node , validator ) :
59
60         '''Validate tree from node 'node' with validator 'validator'.'''
61
62         validate.lastNode = node
63
64         def _checkConf( node , syntaxNode ) :
65
66                 validate.lastNode = node
67                 name , values , contents , meta = node
68                 r = syntaxNode.descend( name )
69                 r.check( values )
70                 for item in contents :
71                         _checkConf( item , r )
72                 r.valid()
73
74         name , values , contents , meta = node
75         root = validator( '__root__' )
76         try :
77                 for item in contents :
78                         _checkConf( item , root )
79         except Error , e :
80                 meta = validate.lastNode[ 3 ]
81                 raise Error( 'at line %d, column %d, %s' 
82                         % ( meta[ 0 ] , meta[ 1 ] , str( e ) ) )