Cleaning. Added copyright notices.
[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                 error( 'Invalid keyword `%r\' in %r.' % ( item , self.name ) )
43
44         def check( self , values ) :
45
46                 # Check node values.
47                 if values :
48                         error( 'Unexpected values %r for %r.' % ( values , self.name ) )
49
50         def valid( self ) :
51
52                 pass
53
54 class MixinNonEmpty :
55
56         children = 0
57
58         def valid( self ) :
59
60                 if not self.children :
61                         error( 'Empty block for %r.' % self.name )
62
63 #-----------------------------------------------------------------------------
64
65 def checkConf( confNode , rootClass ) :
66
67         checkConf.lastNode = confNode
68
69         def _checkConf( confNode , syntaxNode ) :
70
71                 checkConf.lastNode = confNode
72                 name , values , contents , meta = confNode
73                 r = syntaxNode.descend( name )
74                 r.check( values )
75                 for item in contents :
76                         _checkConf( item , r )
77                 r.valid()
78
79         name , values , contents , info = confNode
80         root = rootClass( '__root__' )
81         try :
82                 for item in contents :
83                         _checkConf( item , root )
84         except Error , e :
85                 meta = checkConf.lastNode[ 3 ]
86                 raise Error( 'at line %d, column %d, %s' 
87                         % ( meta[ 0 ] , meta[ 1 ] , str( e ) ) )