rc.py 45.7 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
"""CarbonTracker Data Assimilation Shell (CTDAS) Copyright (C) 2017 Wouter Peters. 
Users are recommended to contact the developers (wouter.peters@wur.nl) to receive
updates of the code. See also: http://www.carbontracker.eu. 

This program is free software: you can redistribute it and/or modify it under the
terms of the GNU General Public License as published by the Free Software Foundation, 
version 3. This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. 

You should have received a copy of the GNU General Public License along with this 
program. If not, see <http://www.gnu.org/licenses/>."""
Peters, Wouter's avatar
Peters, Wouter committed
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
#! /usr/bin/env python
# rc.py


# ------------------------------------------------
# help
# ------------------------------------------------

"""
Deal with model settings in `rc` format.

RCFILES

    A rcfile is a text file with key/value pairs seperated by a ':', e.g.

      my.flag    :  T
      my.answer  :  42

    The following functionality is supported:

     * Empty lines are ignored.

     * Comment lines are introduced by a '!' as first character.

     * Long values could be continued at the next line after a '\' as last character.

     * Include the key/value pairs from another file:

         #include an/other.rc

     * Substitute environment variables when available:

         tm.dir : ${HOME}/TM5/cy3

     * Substitute values of other keys in a line:

         build.dir            :  ${tm.dir}/build
         grid                 :  glb300x200
         input.${grid}.path   :  /data/input/${grid}

       Substitions are allowed in both key names as well as values.
       The substitutions are performed in a loop until nothing
       has to be substituted anymore, or some substitutions could
       not be applied at al; for the later an error is raised.
       Values to be substituted could therefore be set before and
       after they are used.

       Note that if a key has the same name as an environment variable,
       the new value will be assigned to the key instead of the value
       retrieved from the environment:

         HOME      :  /some/other/dir/

     * Substitude some specials:

         ${pid}     # evaluates to the current process id; 
                    # useful for names of log files etc
         ${script}  # evaluates to the base name of the calling script, 
                    # thus without .py etc
                    
     * Instead of variables of the form '${..}' other patterns could be
       specified with the optional 'marks' tupple (see below).

     * Old-style '#eval' lines are still supported:

         #eval RUNDIR = /path/to/mydir
         tmdir : ${RUNDIR}/TM5/cy3

       In this example, the value of RUNDIR will be evaluated and substituted 
       in all {key,value} pairs. This feature is obsolete and a warning will 
       be issued. The proper way to use this is with {key,value} pairs too:

         run.dir   : /path/to/mydir
         tmdir     : ${run.dir}/TM5/cy3
         
     * Comment starting with '!' is stripped from the values.
       To have a value including exclamation marks, use '\!' but do
       not expect that the rest of the value is scanned for comment too:
       
           my.value      :   -999    ! just an integer value
           my.message    :   This value has 64 characters \! Count if you don't believe it ...

     * If you trust yourself you might try to use conditional expressions:
     
           #if ${my.number} == 1
           message    : Welcome
           #else
           message    : Whatever ...
           #endif
           
       The conditions should be valid python expressions that evaluate to a boolean;
       value substitutions are performed before evaluation. Examples:

                ${my.runmode} == 4
                "${my.tracer}" == "CH4"

       Keep it simple! Very complicated and nested if-statements might not be
       resolved correctly, and are in any case not easy to understand for other users!
       
       In the example above, an exception could be raised by the special error expression;
       everything behind the '#error' mark is displayed as an error message:
       
            #error No settings provided for value : ${my.value}


USAGE AS SCRIPT

    Called in script form, the following syntaxis is supported:
    
       rc.py [options] <rcfile> <key>
       rc.py -h|--help
       
    The <rcfile> is read and the value defined by <key> is printed
    to the standard output.

    Use the --help option for more documentation.

    
USAGE AS PYTHON MODULE

    Import the module with:
    
        import rc

    Initialiase by reading all settings in a rcfile,
    supporting the functionality described in the 'RCFILES' section.

        rcf = RcFile( 'settings.rc' )

    The initialisation accepts some optional arguments.
    Set the silent flag to True to ignore warnings.

        rcf = RcFile( 'settings.rc', silent=False )

    Use the optional 'marks' tupple to define that variables to be expanded
    are marked other than '${..}' but rather '<mark1>..<mark2>' :

        rcf = RcFile( 'settings.rc', marks=('${','}') )

    Test to see if a key is defined:

        if rcf.has_key('my.flag') :
            print 'value of my flag is : ', rcf['my.flag']
    
    Extract a list with all keys:
    
        rcf.keys()

    A 'get' function is provided to extract values:

     * by default, the 'get' function returns the value as a str type:

         s = rcf.get('my.value')
    
     * a second argument is the name of the python type to which
       the value is converted to:
    
         i = rcf.get('my.flag','int')

     * if the return value should be a 'bool', the result is
         True  for values     : 'True' , 'T', 'yes', or '1' ,
         and False for value  : 'False', 'F', 'no' , or '0' ;
       for other values an error is raised;
     
     * return a default value if the key is not found:

            rcf.get( 'my.flag', default=False )
    
     * print a debug message to the logging system for each extracted key:
     
            rcf.get( 'my.flag', verbose=True ) 

    Add a new value, comment is optional:

        rcf.add( 'my.iter', 2, comment='iteration number for restart' )

    Assign a new value to an existing key:

        rcf.replace( 'my.flag', True )

    Scan a character line for all occurances of ${<key>} and subsitute for
    the rc value assigned to <key> :

        line = rcf.substitute( line )

    Write the dictionary (with all variables expanded and included files included)
    to new file:

         rcf.write('newfile.rc')

         
USAGE AS PYTHON MODULE - BACKWARDS COMPATIBILITY

    For backwards compatibility with older implementations of the rc.py module,
    two extra routines are available.
    
    To read rc-file by making an instance of the RcFile class, 
    and to returns a dictionary of values only, use:
            
        rcdict = read( 'test.rc' [,silent=False] )
        
    Create a new rcfile and fill with key/values from a dictionary:

        write( 'test.rc', rcdict )
        

HISTORY

    2008? Andy Jacobson, NOAA
      Translation to python of original shell script 'go_readrc' .
    2009-06 Wouter Peters, WUR
      Support substitution of previously defined variables.
    2009-06 Arjo Segers, TNO
      Support include files.
    2009-09 Arjo Segers, TNO
      Re-coded into class.
      Implemented substitution loop.
    2009-11 Arjo Segers, JRC
      Added main program to run this file as a shell script.
      Added replace and substitute routines.
    2010-03 Arjo Segers, JRC
      Support simple if-statements.
      Support comment in values.
    2010-07 Wouter Peters, WUR
      Downgraded to work for python 2.4.3 too.
      Added read/write routines for backwards compatibility.
    2010-07-27 Arjo Segers, JRC
      Maintain list with rcfile names and line numbers to be displayed
      with error messages to identify where problematic lines are found.
    2010-07-28 Andy Jacobson, NOAA
      Add second dictionary of key,linetrace values to help track the 
      provenance of #included keys (to debug multiple key instances).
      Identify duplicate keys by checking on different source lines
      instead of checking if the values are different.
"""
import re
import os
import sys
import logging
        

# ------------------------------------------------
# classes
# ------------------------------------------------


class RcFile(object) :

    """
    Class to store settings read from a rcfile.
    """   

265
    def __init__(self, filename, silent=False, marks=('${', '}'), do_eval=True):
Peters, Wouter's avatar
Peters, Wouter committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286

        """ 
        
        Usage:
        
          rcf = RcFile( 'settings.rc' [,silent=False] [marks=('${','}')] )

        Read an rc-file and expand all the keys and values into a dictionary.
        Do not shout messages if silent is set to True. 
        The 2-item tupple (mark1,mark2) could be used to re-define the default
        key pattern '${..}' into something else:
          <mark1>...<mark2>

        """

        # info ...
        logging.debug('reading rcfile %s ...' % filename)

        # check ...
        if not os.path.exists(filename) :
            msg = 'rcfile not found : %s' % filename ; logging.error(msg)
brunner's avatar
brunner committed
287
            raise IOError(msg)
Peters, Wouter's avatar
Peters, Wouter committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
        #endif
        
        # store file name:
        self.filename = filename
        # store rc-file root directory:
        self.rootdir = os.path.split(filename)[0]
        
        # storage for processed rcfile:
        self.outfile = []
        
        # storage for key/value pairs:
        self.values = {}

        # storage for key/source file pairs:
        self.sources = {}
        
        # open the specified rc-file:
        f = open(filename, 'r')
        # store all lines in a list:
        inpfile = f.readlines()
        # close:
        f.close()
        
        # create traceback info:
        inptrace = []
        for jline in range(len(inpfile)) :
            inptrace.append('"%s", line %-10s' % (filename, str(jline + 1)))
        #endfor

        # flags:
        warned_for_eval = False
        
        # pass counter:
        ipass = 1
        
        # loop until all substitutions and inclusions are done:
        while True :
        
            # start again with empty output file:
            self.outfile = []
            # also empty traceback info:
            self.trace = []
            # init current line:
            line = ''
            # assume nothing has to be done after this loop:
            something_done = False
            something_to_be_done = False
            # maintain list with unresolved lines (with keys that could not be evaluated yet):
            unresolved_lines = []
            # maintain list with keys from which the value could not be resolved yet:
            keys_with_unresolved_value = []
            # maintain list with undefined keys; 
            # some might be part of the keys_with_unresolved_value list:
            undefined_keys = []
                        
            # stack for conditional evaluation;
            # each element is a tuple with elements:
            #   resolved (boolean) true if the if-statement is evaluated
            #   flag     (boolean) true if the lines below the statement 
            #              are to be included
            #   anyflag    (boolean) used to check if any of the 'if' or 'elif' conditions
            #              in this sequence evaluated to True
            #   line     (char) description of the line for messages
            ifstack = []

            #print ''
            #print '---[pass %i]-------------------------------------' % ipass
            #for line in inpfile : print line.strip()
            
            # loop over lines in input file:
            iline = -1
            for inpline in inpfile :
            
                # line counter:
                iline = iline + 1
                
                # cut current traceback info from list:
                linetrace_curr = inptrace.pop(0)
                
                # set full traceback info:
                if line.endswith('\\') :
                    # current input line is a continuation; combine:
                    qfile, qlinenrs = linetrace.split(',')
                    qnrs = qlinenrs.replace('lines', '').replace('line', '')
                    if '-' in qnrs :
                        qnr1, qnr2 = qnrs.split('-')
                    else :
                        qnr1, qnr2 = qnrs, qnrs
                    #endif
                    linetrace = '%s, lines %-9s' % (qfile, '%i-%i' % (int(qnr1), int(qnr2) + 1))
                else :
                    # just copy:
                    linetrace = linetrace_curr
                #endif
                    
                # remove end-of-line character:
                inpline = inpline.strip()
                
                ## DEBUG: display current line ...
                #print '%4i | %s' % (iline,inpline)
                #print '%4i | %s     %s' % (iline,inpline,linetrace)
                
                #
                # empty lines
                #

                # skip empty lines:
                if len(inpline) == 0 :
                    # add empty line to output:
                    self.outfile.append('\n')
                    # add traceback info:
                    self.trace.append(linetrace)
                    # next will be a new line:
                    line = ''
                    # next input line:
                    continue
                #endif
                
                #
                # comment lines
                #

                # skip comment:
                if inpline.startswith('!') :
                    # add copy to output file:
                    self.outfile.append('%s\n' % inpline)
                    # add traceback info:
                    self.trace.append(linetrace)
                    # next will be a new line:
                    line = ''
                    # next input line:
                    continue
                #endif
                
                #
                # continuation lines
                #

                # current line has continuation mark '\' at the end ?
                # then add this input line:
                if line.endswith('\\') :
                    # remove continuation character, add input line:
                    line = line[:-1] + inpline
                else :
                    # bright new line:
                    line = inpline
                #endif

                # continuation mark ? then next line of input file:
                if line.endswith('\\') : continue
                
                #
                # conditional settings (1)
                #

                ## debug ...
                #print 'xxx0 ', ifstack
                
                # is this the begin of a new condition ?
                mark = '#if'
                if line.startswith(mark) :
                    # push temporary flag to stack, will be replaced after evaluation of condition:
                    ifstack.append((False, True, False, linetrace))
                    # debug ...
                    #print 'xxx1 ', ifstack
                #endif

                mark = '#elif'
                if line.startswith(mark) :
                    # check ...
                    if len(ifstack) == 0 :
                        logging.error('found orphin "%s" in %s' % (mark, linetrace))
                        raise Exception
                    #endif
                    # remove current top from stack:
                    resolved, flag, anyflag, msg = ifstack.pop()
                    # did one of the previous #if/#elif evaluate to True already ?
                    if resolved and anyflag :
                        # push to stack that this line resolved to False :
                        ifstack.append((True, False, anyflag, linetrace))
                        # copy to output:
                        self.outfile.append('%s\n' % line)
                        # add traceback info:
                        self.trace.append(linetrace)
                        # next input line:
                        continue
                    else :
                        # push temporary flag to stack, will be replaced after evaluation of condition:
                        ifstack.append((False, True, anyflag, linetrace))
                    #endif
                    ## debug ...
                    #print 'xxx2 ', ifstack
                #endif

                mark = '#else'
                if line.startswith(mark) :
                    # check ...
                    if len(ifstack) == 0 :
                        logging.error('found orphin "%s" in %s' % (mark, linetrace))
                        raise Exception
                    #endif
                    # remove current top from stack:
                    resolved, flag, anyflag, msg = ifstack.pop()
                    # get higher level settings:
                    if len(ifstack) > 0 :
                        resolved_prev, flag_prev, anyflag_prev, msg_prev = ifstack[-1]
                    else :
                        flag_prev = True
                    #endif
                    # should next lines be included ? 
                    # reverse flag, take into acount higher level:
                    new_flag = (not flag) and (not anyflag) and flag_prev
                    # push to stack:
                    ifstack.append((resolved, new_flag, False, linetrace))
                    # debug ...
                    #print 'xxx3 ', ifstack
                    # copy to output:
                    self.outfile.append('%s\n' % line)
                    # add traceback info:
                    self.trace.append(linetrace)
                    # next input line:
                    continue
                #endif

                # is this the end of a condition ?
                mark = '#endif'
                if line.startswith(mark) :
                    # check ...
                    if len(ifstack) == 0 :
                        logging.error('found orphin "%s" in %s' % (mark, linetrace))
                        raise Exception
                    #endif
                    # remove top from stack:
                    top = ifstack.pop()
                    # copy to output:
                    self.outfile.append('%s\n' % line)
                    # add traceback info:
                    self.trace.append(linetrace)
                    # next input line:
                    continue
                #endif

                # within if-statements ?
                if len(ifstack) > 0 :
                    # extract current top:
                    resolved, flag, anyflag, msg = ifstack[-1]
                    # already resolved ? then check if this line should be skipped:
                    if resolved and (not flag) :
                        # skip this line, but include commented version in output:
                        self.outfile.append('!%s\n' % line)
                        # add traceback info:
                        self.trace.append(linetrace)
                        # read the next input line:
                        continue
                    #endif
                #endif
                
                #
                # handle '#eval' lines
                #

                mark = '#eval'        
                if line.startswith(mark):
                    # info ..
                    if not warned_for_eval :
                        if not silent: logging.warning('the #eval statements in rc-files are deprecated, use {key:value} pairs instead')
                        warned_for_eval = True
                    #endif
                    # add commented copy to output:
                    self.outfile.append('!evaluated>>> ' + line)
                    # add traceback info:
                    self.trace.append(linetrace)
                    # remove leading mark:
                    line = line.lstrip(mark)
                    # multiple settings are seperated by ';' :
                    evals = line.split(';')
                    # insert in output file:
                    for k in range(len(evals)) :
                        # split in key and value:
                        key, value = evals[k].split('=')
                        # insert:
                        self.outfile.append('%s : %s' % (key, value))
                        # add traceback info:
                        self.trace.append(linetrace)
                    #endfor
                    # next input line:
                    continue
                #endif

                #
                # replace ${..} values
                #
                
                # ensure that common marks are evaluated correctly:
                start_mark = marks[0].replace('{', '\{').replace('<', '\<').replace('$', '\$')
                close_mark = marks[1].replace('}', '\}').replace('>', '\>')
        
                # set syntax of keywords to be matched, e.g. '${...}' :
                pattern = start_mark + '[A-Za-z0-9_.]+' + close_mark

                # make a regular expression that matches all variables:
                rc_varpat = re.compile(pattern)

                # search all matching paterns:
                pats = re.findall(rc_varpat, line)
                # counter for unexpanded substitutions:
                ntobedone = 0
                # loop over matches:
                for pat in pats :
                    # remove enclosing characters:
                    key = pat.lstrip(start_mark).rstrip(close_mark)
                    # test some dictionaries for matching key:
brunner's avatar
brunner committed
600
                    if key in self.values:
Peters, Wouter's avatar
Peters, Wouter committed
601
602
603
604
605
606
                        # get previously defined value:
                        val = self.values[key]
                        # substitute value:
                        line = line.replace(pat, val)
                        # set flag:
                        something_done = True
brunner's avatar
brunner committed
607
                    elif key in os.environ:
Peters, Wouter's avatar
Peters, Wouter committed
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
                        # get value from environment:
                        val = os.environ[key]
                        # substitute value:
                        line = line.replace(pat, val)
                        # set flag:
                        something_done = True
                    elif key == 'pid' :
                        # special value: process id; convert to character:
                        val = '%i' % os.getpid()
                        # substitute value:
                        line = line.replace(pat, val)
                        # set flag:
                        something_done = True
                    elif key == 'script' :
                        # special value: base name of the calling script, without extension:
                        script, ext = os.path.splitext(os.path.basename(sys.argv[0]))
                        # substitute value:
                        line = line.replace(pat, script)
                        # set flag:
                        something_done = True
                    else :
                        # could not substitute yet; set flag:
                        ntobedone = ntobedone + 1
                        # add to list with unresolved keys:
                        if key not in undefined_keys : undefined_keys.append(key)
                        # continue with next substitution:
                        continue
                    #endif
                #endfor  # matched patterns
                # not all substituted ?
                if ntobedone > 0 :
                    # add line to output:
                    self.outfile.append(line)
                    # add traceback info:
                    self.trace.append(linetrace)
                    # a new pass is needed:
                    something_to_be_done = True
                    # store for info messages:
                    unresolved_lines.append('%s | %s' % (linetrace, line))
                    # could this be a 'key : value' line ?
                    if ':' in line :
                        # split, remove leading and end space:
                        qkey, qvalue = line.split(':', 1)
                        qkey = qkey.strip()
                        # assume it is indeed a key if it does not contain whitespace,
                        # no start mark, and does not start wiht '#' :
                        if (' ' not in qkey) and (start_mark not in qkey) and (not qkey.startswith('#')) :
                            # add to list:
                            if qkey not in keys_with_unresolved_value : keys_with_unresolved_value.append(qkey)
                        #endif
                    # next input line:
                    continue
                #endif

                #
                # handle '#include' lines
                #

                mark = '#include'
                if line.startswith(mark) :
                    # remove leading mark, what remains is file to be included:
                    inc_file = line.lstrip(mark).strip()
                    # check ...
                    if not os.path.exists(inc_file) :
                        inc_file = os.path.join(self.rootdir, inc_file)
                        logging.debug('Added rootdir to requested include: %s' % inc_file)
                    #endif
                    if not os.path.exists(inc_file) :
                        logging.error('include file not found : %s' % inc_file)
                        logging.error(linetrace)
brunner's avatar
brunner committed
678
                        raise IOError('include file not found : %s' % inc_file)
Peters, Wouter's avatar
Peters, Wouter committed
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
                    #endif
                    # read content:
                    inc_f = open(inc_file, 'r')
                    inc_rc = inc_f.readlines()
                    inc_f.close()
                    # add extra comment for output file:
                    self.outfile.append('! >>> %s >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n' % inc_file)
                    self.outfile.extend(inc_rc)
                    self.outfile.append('! <<< %s <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n' % inc_file)
                    # add traceback info:
                    self.trace.append(linetrace)
                    for jline in range(len(inc_rc)) :
                        self.trace.append('"%s", line %-10s' % (inc_file, str(jline + 1)))
                    #endfor
                    self.trace.append(linetrace)
                    # set flag:
                    something_done = True
                    # a new pass is needed:
                    something_to_be_done = True
                    # next input line:
                    continue
                #endif


                #
                # conditional settings (2)
                #

                # evaluate conditional expressions:
                mark1 = '#if'
                mark2 = '#elif'
                if line.startswith(mark1) or line.startswith(mark2) :
                    # remove leading mark, what remains is logical expression:
                    expression = line.lstrip(mark1).strip()
                    expression = line.lstrip(mark2).strip()
                    # common mistake is to add a ':' as in python; remove this:
                    if expression.endswith(':') : expression = expression.rstrip(':').strip()
                    # evaluate:
                    try :
                        flag = eval(expression)
                    except :
                        logging.error('could not evaluate expression:')
                        logging.error('    %s' % expression)
                        logging.error('in %s' % linetrace)
                        raise Exception
                    #endtry
                    # remove temporary top added before during this pass:
                    tmp_statement, tmp_flag, tmp_anyflag, tmp_msg = ifstack.pop()
                    # extract current top if necessary:
                    if len(ifstack) > 0 :
                        dummy_statement, prev_flag, dummy_anyflag, dummy_msg = ifstack[-1]
                    else :
                        prev_flag = True
                    #endif
                    # should next lines be included ?
                    new_flag = prev_flag and tmp_flag and flag
                    # any if/elif evaluated to true in this sequence ?
                    new_anyflag = tmp_anyflag or new_flag
                    # add to stack, now resolved, take into accout current flag:
                    ifstack.append((True, new_flag, new_anyflag, linetrace))
                    # debug ...
                    #print 'xxx2 ', ifstack
                    # copy to output:
                    self.outfile.append('%s\n' % line)
                    # add traceback info:
                    self.trace.append(linetrace)
                    # next input line:
                    continue
                #endif

                #
                # error message
                #
                
                # special command to rais an exception:
                mark = '#error'
                if line.startswith(mark) :
                    # remove leading mark, what remains is error message:
                    msg = line.lstrip(mark).strip()
                    # display:
                    logging.error(msg)
                    # add info:
                    logging.error('error message in %s' % linetrace)
                    # stop:
                    raise Exception
                #endif

                #
                # checks
                #

                # common mistake ...
                if line.startswith('#') :
                    logging.error('line in rcfile starts with "#" but is not an "#include" or other special line;')
                    logging.error('if it is supposed to be comment, please start with "!" ...')
                    logging.error('  %s' % line)
                    logging.error('%s' % linetrace)
                    raise IOError
                #endif

                # check ...
                if ':' not in line :
                    logging.error('key/value line should contain a ":"')
                    logging.error('%s' % linetrace)
                    raise IOError
                #endif

                #
                # add to output
                #

                # add line to output:
                self.outfile.append('%s\n' % line)
                # add traceback info:
                self.trace.append(linetrace)

                #
                # add key/value pair
                #
                
                # not if inside an unresolved if-statement ...
                if len(ifstack) > 0 :
                    # get top values:
                    resolved, flag, anyflag, msg = ifstack[-1]
                    # not resolved yet ? then continue:
                    if not resolved : continue
                #endif
                
                # split in key and value; 
                # value might contain ':' too, so at maximum 1 split:
                key, val = line.split(':', 1)
                
                # remove comment from value:
                if '!' in val :
                    # not if '\!' is in the value ...
                    if not '\!' in val : val, comment = val.split('!')
                    # replace all slash-comments:
                    val = val.replace('\!', '!')
                #endif

                # remove spaces:
                key = key.strip()
                val = val.strip()

                # already defined ?
brunner's avatar
brunner committed
824
                if key in self.values:
Peters, Wouter's avatar
Peters, Wouter committed
825
826
827
828
829
830
831
832
833
834
835
836
837
                    # this will occure often after the first pass since
                    # the keys are resolved again and again ;
                    # therefore, only complain if this definition is read
                    # from a different line :
                    if linetrace != self.sources[key] :
                        logging.error('duplicated key \"%s\" found:' % key)
                        logging.error('first definition in %s is:' % self.sources[key])
                        logging.error('  %s  : %s' % (key, str(self.values[key])))
                        logging.error('second definition in %s is:' % linetrace.strip())
                        logging.error('  %s  : %s' % (key, str(val)))
                        raise Exception
                    #endif
                else :
838
839
840
841
842
                    if do_eval:
                        if isinstance(val, str):
                            if any(operator in val for operator in '+-*/'):
                                try: val = eval(val)
                                except: pass
Peters, Wouter's avatar
Peters, Wouter committed
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
                    # store new value:
                    self.values[key] = val
                    self.sources[key] = linetrace
                    # set flag:
                    something_done = True
                #endif

                # display key and value ...
                #print '                                --> %s : %s, from %s' % (key,val, linetrace)

            #endfor  # loop over lines in text
            
            ## info ...
            #print '~~~ outfile ~~~~~~~~~~~~~~~~~~~~~~~'
            #for line in self.outfile : print line.strip()
            #print '~~~ key/values ~~~~~~~~~~~~~~~~~~~~'
brunner's avatar
brunner committed
859
            #for k,v in self.items() :
Peters, Wouter's avatar
Peters, Wouter committed
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
            #    print '%s  :  %s' % (k,v)
            ##endfor
            #print '-------------------------------------------------'
            #print ''
            
            # check ...
            if len(ifstack) > 0 :
                logging.error('unterminated if-statement ; current stack:')
                for resolved, flag, anyflag, msg in ifstack : logging.error(msg)
                logging.error('please fix the rcfile or debug this script ...')
                raise Exception
            #endif

            # check ...
            if something_to_be_done :
                # check for unterminated loop ...
                if not something_done :
                    # list all unresolved lines:
                    logging.error('Could not resolve the following lines in rcfile(s):')
                    logging.error('')
                    for uline in unresolved_lines :
                        logging.error('    %s' % uline)
                    #endfor
                    logging.error('')
                    # list all undefined keys:
                    logging.error('  Undefined key(s):')
                    logging.error('')
                    for ukey in undefined_keys :
                        # do not list them if they are undefined because the value
                        # depends on other undefined keys:
                        if ukey not in keys_with_unresolved_value :
                            # display:
                            logging.error('    %s' % ukey)
                            # loop over unresolved lines to see in which the key is used:
                            for uline in unresolved_lines :
                                # search for  '${key}' pattern:
                                if marks[0] + ukey + marks[1] in uline :
                                    logging.error('      %s' % uline)
                                #endif
                            #endfor
                            logging.error('')
                        #endif
                    #endfor
                    logging.error('please fix the rcfile(s) or debug this script ...')
                    raise Exception
                #endif
            else :
                # finished ...
                break
            #endif
            
            # for safety ...
            if ipass == 100 :
                logging.error('resolving rc file has reached pass %i ; something wrong ?' % ipass)
                raise Exception
            #endif
            
            # new pass:
            ipass = ipass + 1
            # renew input:
            inpfile = self.outfile
            # renew traceback:
            inptrace = self.trace
            
        #endwhile   # something to be done
        
    #enddef  # __init__
    
    
    # ***
    
    
    def has_key(self, key) :
    
        # from dictionairy:
brunner's avatar
brunner committed
935
        return key in self.values
Peters, Wouter's avatar
Peters, Wouter committed
936
937
938
939
940
941
942
943
944
945
        
    #enddef
    
    
    # ***
    
    
    def keys(self) :
    
        # from dictionairy:
946
        return list(self.values.keys())
Peters, Wouter's avatar
Peters, Wouter committed
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
        
    #enddef
    
    
    # ***


    def get(self, key, totype='', default=None, verbose=False) :
    
        """
        rcf.get( 'my.value' [,default=None] )
        Return element 'key' from the dictionairy.
        If the element is not present but a default is specified, than return
        the default value.
        If 'verbose' is set to True, then print debug messages to the logging
        about which values is returned for the given key.
        The option argument 'totype' defines the conversion to a Python type.
        If 'totype' is set to 'bool', the return value is the
        boolean True for values 'T', 'True', 'yes', and '1',
        and False for 'F', 'False', 'no', or '0' ;
        for other values, an exception will be raised.
        """
        
        # element found ?
brunner's avatar
brunner committed
971
        if key in self.values:
Peters, Wouter's avatar
Peters, Wouter committed
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
            # copy value:
            value = self.values[key]
            # convert ?
            if totype == 'bool' :
                # convert to boolean:
                if value in ['T', 'True', 'yes', '1'] :
                    value = True
                elif value in ['F', 'False', 'no', '0'] :
                    value = False
                else :
                    logging.error("value of key '%s' is not a boolean : %s" % (key, str(value)))
                    raise Exception
                #endif
            elif len(totype) > 0 :
                # convert to other type ...
                value = eval('%s(%s)' % (totype, value))
            #endif
            # for debugging ...
            if verbose : logging.debug('rc setting "%s" : "%s"' % (key, str(value)))
        else :
            # default value specified ?
            if default != None :
                # copy default:
                value = default
                # for debugging ...
                if verbose : logging.debug('rc setting "%s" : "%s" (deault)' % (key, str(value)))
            else :
                # something wrong ...
                logging.error("key '%s' not found in '%s' and no default specified" % (key, self.filename))
For faster browsing, not all history is shown. View entire blame