rc.py 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250
  1. #! /usr/bin/env python
  2. # rc.py
  3. # ------------------------------------------------
  4. # help
  5. # ------------------------------------------------
  6. """
  7. Deal with model settings in `rc` format.
  8. RCFILES
  9. A rcfile is a text file with key/value pairs seperated by a ':', e.g.
  10. my.flag : T
  11. my.answer : 42
  12. The following functionality is supported:
  13. * Empty lines are ignored.
  14. * Comment lines are introduced by a '!' as first character.
  15. * Long values could be continued at the next line after a '\' as last character.
  16. * Include the key/value pairs from another file:
  17. #include an/other.rc
  18. * Substitute environment variables when available:
  19. tm.dir : ${HOME}/TM5/cy3
  20. * Substitute values of other keys in a line:
  21. build.dir : ${tm.dir}/build
  22. grid : glb300x200
  23. input.${grid}.path : /data/input/${grid}
  24. Substitions are allowed in both key names as well as values.
  25. The substitutions are performed in a loop until nothing
  26. has to be substituted anymore, or some substitutions could
  27. not be applied at al; for the later an error is raised.
  28. Values to be substituted could therefore be set before and
  29. after they are used.
  30. Note that if a key has the same name as an environment variable,
  31. the new value will be assigned to the key instead of the value
  32. retrieved from the environment:
  33. HOME : /some/other/dir/
  34. * Substitude some specials:
  35. ${pid} # evaluates to the current process id;
  36. # useful for names of log files etc
  37. ${script} # evaluates to the base name of the calling script,
  38. # thus without .py etc
  39. * Instead of variables of the form '${..}' other patterns could be
  40. specified with the optional 'marks' tupple (see below).
  41. * Old-style '#eval' lines are still supported:
  42. #eval RUNDIR = /path/to/mydir
  43. tmdir : ${RUNDIR}/TM5/cy3
  44. In this example, the value of RUNDIR will be evaluated and substituted
  45. in all {key,value} pairs. This feature is obsolete and a warning will
  46. be issued. The proper way to use this is with {key,value} pairs too:
  47. run.dir : /path/to/mydir
  48. tmdir : ${run.dir}/TM5/cy3
  49. * Comment starting with '!' is stripped from the values.
  50. To have a value including exclamation marks, use '\!' but do
  51. not expect that the rest of the value is scanned for comment too:
  52. my.value : -999 ! just an integer value
  53. my.message : This value has 64 characters \! Count if you don't believe it ...
  54. * If you trust yourself you might try to use conditional expressions:
  55. #if ${my.number} == 1
  56. message : Welcome
  57. #else
  58. message : Whatever ...
  59. #endif
  60. The conditions should be valid python expressions that evaluate to a boolean;
  61. value substitutions are performed before evaluation. Examples:
  62. ${my.runmode} == 4
  63. "${my.tracer}" == "CH4"
  64. Keep it simple! Very complicated and nested if-statements might not be
  65. resolved correctly, and are in any case not easy to understand for other users!
  66. In the example above, an exception could be raised by the special error expression;
  67. everything behind the '#error' mark is displayed as an error message:
  68. #error No settings provided for value : ${my.value}
  69. USAGE AS SCRIPT
  70. Called in script form, the following syntaxis is supported:
  71. rc.py [options] <rcfile> <key>
  72. rc.py -h|--help
  73. The <rcfile> is read and the value defined by <key> is printed
  74. to the standard output.
  75. Use the --help option for more documentation.
  76. USAGE AS PYTHON MODULE
  77. Import the module with:
  78. import rc
  79. Initialiase by reading all settings in a rcfile,
  80. supporting the functionality described in the 'RCFILES' section.
  81. rcf = RcFile( 'settings.rc' )
  82. The initialisation accepts some optional arguments.
  83. Set the silent flag to True to ignore warnings.
  84. rcf = RcFile( 'settings.rc', silent=False )
  85. Use the optional 'marks' tupple to define that variables to be expanded
  86. are marked other than '${..}' but rather '<mark1>..<mark2>' :
  87. rcf = RcFile( 'settings.rc', marks=('${','}') )
  88. Test to see if a key is defined:
  89. if rcf.has_key('my.flag') :
  90. print 'value of my flag is : ', rcf['my.flag']
  91. Extract a list with all keys:
  92. rcf.keys()
  93. A 'get' function is provided to extract values:
  94. * by default, the 'get' function returns the value as a str type:
  95. s = rcf.get('my.value')
  96. * a second argument is the name of the python type to which
  97. the value is converted to:
  98. i = rcf.get('my.flag','int')
  99. * if the return value should be a 'bool', the result is
  100. True for values : 'True' , 'T', 'yes', or '1' ,
  101. and False for value : 'False', 'F', 'no' , or '0' ;
  102. for other values an error is raised;
  103. * return a default value if the key is not found:
  104. rcf.get( 'my.flag', default=False )
  105. * print a debug message to the logging system for each extracted key:
  106. rcf.get( 'my.flag', verbose=True )
  107. Add a new value, comment is optional:
  108. rcf.add( 'my.iter', 2, comment='iteration number for restart' )
  109. Assign a new value to an existing key:
  110. rcf.replace( 'my.flag', True )
  111. Scan a character line for all occurances of ${<key>} and subsitute for
  112. the rc value assigned to <key> :
  113. line = rcf.substitute( line )
  114. Write the dictionary (with all variables expanded and included files included)
  115. to new file:
  116. rcf.WriteFile('newfile.rc')
  117. USAGE AS PYTHON MODULE - BACKWARDS COMPATIBILITY
  118. For backwards compatibility with older implementations of the rc.py module,
  119. two extra routines are available.
  120. To read rc-file by making an instance of the RcFile class,
  121. and to returns a dictionary of values only, use:
  122. rcdict = read( 'test.rc' [,silent=False] )
  123. Create a new rcfile and fill with key/values from a dictionary:
  124. write( 'test.rc', rcdict )
  125. RAW MODE
  126. In raw mode, the rcfile read into the RcFile object is read 'as it is'.
  127. Thus, no substitution of keys, no evaluation of '#if' statements and
  128. '#include' lines, etc.
  129. This might be useful to create new rcfiles from a template.
  130. Consider the rcfile 'xyz.rc' with content:
  131. my.id : xyz
  132. data.dir : /data/${my.id}
  133. Now try to create a copy 'qqq.rc' of this file with "xyz" replaced by "qqq";
  134. the optional 'raw' argument to the RcFile() routine is 'False' by default :
  135. rcf = RcFile( 'template.rc', raw=False )
  136. rcf.replace( 'my.id', 'qqq' )
  137. rcf.WriteFile( 'qqq.rc' )
  138. In this case, the content of 'qqq.rc' would be:
  139. my.id : qqq
  140. data.dir : /data/xyz
  141. With 'raw=True' passed to the RcFile() routine however, the content will be:
  142. my.id : qqq
  143. data.dir : /data/${my.id}
  144. Note that in raw mode it will often happen that more than one definition of
  145. a key is found, which are normally hidden within '#if' constructions.
  146. The multiple values are collected in a list; the 'replace' value will act on
  147. all definitions of a key.
  148. HISTORY
  149. 2008? Andy Jacobson, NOAA
  150. Translation to python of original shell script 'go_readrc' .
  151. 2009-06 Wouter Peters, WUR
  152. Support substitution of previously defined variables.
  153. 2009-06 Arjo Segers, TNO
  154. Support include files.
  155. 2009-09 Arjo Segers, TNO
  156. Re-coded into class.
  157. Implemented substitution loop.
  158. 2009-11 Arjo Segers, JRC
  159. Added main program to run this file as a shell script.
  160. Added replace and substitute routines.
  161. 2010-03 Arjo Segers, JRC
  162. Support simple if-statements.
  163. Support comment in values.
  164. 2010-07 Wouter Peters, WUR
  165. Downgraded to work for python 2.4.3 too.
  166. Added read/write routines for backwards compatibility.
  167. 2010-07-27 Arjo Segers, JRC
  168. Maintain list with rcfile names and line numbers to be displayed
  169. with error messages to identify where problematic lines are found.
  170. 2010-07-28 Andy Jacobson, NOAA
  171. Add second dictionary of key,linetrace values to help track the
  172. provenance of #included keys (to debug multiple key instances).
  173. Identify duplicate keys by checking on different source lines
  174. instead of checking if the values are different.
  175. 2011-07-21 Andy Jacobson, NOAA
  176. Fixed bug in replace() in which spaces were added before the colon
  177. in the replacement key:val line. This bug caused overly-long
  178. lines which could not be succesfully read, leading to crashes after
  179. 20 or so cycles.
  180. 2010-08026 Arjo Segers, JRC
  181. Added raw option to RcFile class.
  182. """
  183. # ------------------------------------------------
  184. # classes
  185. # ------------------------------------------------
  186. class RcFile( object ) :
  187. """
  188. Class to store settings read from a rcfile.
  189. """
  190. def __init__( self, filename, silent=False, marks=('${','}'), raw=False ) :
  191. """
  192. Usage:
  193. rcf = RcFile( 'settings.rc' [,silent=False] [marks=('${','}')] )
  194. Read an rc-file and expand all the keys and values into a dictionary.
  195. Do not shout messages if silent is set to True.
  196. The 2-item tupple (mark1,mark2) could be used to re-define the default
  197. key pattern '${..}' into something else:
  198. <mark1>...<mark2>
  199. """
  200. # external:
  201. import re
  202. import os
  203. import sys
  204. import logging
  205. # info ...
  206. logging.debug( 'reading rcfile %s ...' % filename )
  207. # check ...
  208. if not os.path.exists(filename) :
  209. msg = 'rcfile not found : %s' % filename ; logging.error(msg)
  210. raise IOError, msg
  211. # store file name:
  212. self.filename = filename
  213. # store rc-file root directory:
  214. self.rootdir = os.path.split(filename)[0]
  215. # store flag:
  216. self.raw = raw
  217. # storage for processed rcfile:
  218. self.outfile = []
  219. # storage for key/value pairs:
  220. self.values = {}
  221. # storage for key/source file pairs:
  222. self.sources = {}
  223. # open the specified rc-file:
  224. f = open(filename,'r')
  225. # store all lines in a list:
  226. inpfile = f.readlines()
  227. # close:
  228. f.close()
  229. # create traceback info:
  230. inptrace = []
  231. for jline in range(len(inpfile)) :
  232. inptrace.append( '"%s", line %-10s' % (filename,str(jline+1)) )
  233. # flags:
  234. warned_for_eval = False
  235. # pass counter:
  236. ipass = 1
  237. # loop until all substitutions and inclusions are done:
  238. while True :
  239. # start again with empty output file:
  240. self.outfile = []
  241. # also empty traceback info:
  242. self.trace = []
  243. # init current line:
  244. line = ''
  245. # assume nothing has to be done after this loop:
  246. something_done = False
  247. something_to_be_done = False
  248. # maintain list with unresolved lines (with keys that could not be evaluated yet):
  249. unresolved_lines = []
  250. # maintain list with keys from which the value could not be resolved yet:
  251. keys_with_unresolved_value = []
  252. # maintain list with undefined keys;
  253. # some might be part of the keys_with_unresolved_value list:
  254. undefined_keys = []
  255. # stack for conditional evaluation;
  256. # each element is a tuple with elements:
  257. # resolved (boolean) true if the if-statement is evaluated
  258. # flag (boolean) true if the lines below the statement
  259. # are to be included
  260. # anyflag (boolean) used to check if any of the 'if' or 'elif' conditions
  261. # in this sequence evaluated to True
  262. # line (char) description of the line for messages
  263. ifstack = []
  264. #print ''
  265. #print '---[pass %i]-------------------------------------' % ipass
  266. #for line in inpfile : print line.strip()
  267. # loop over lines in input file:
  268. iline = -1
  269. for inpline in inpfile :
  270. # line counter:
  271. iline = iline + 1
  272. # cut current traceback info from list:
  273. linetrace_curr = inptrace.pop(0)
  274. # set full traceback info:
  275. if line.endswith('\\') :
  276. # current input line is a continuation; combine:
  277. qfile,qlinenrs = linetrace.split(',')
  278. qnrs = qlinenrs.replace('lines','').replace('line','')
  279. if '-' in qnrs :
  280. qnr1,qnr2 = qnrs.split('-')
  281. else :
  282. qnr1,qnr2 = qnrs,qnrs
  283. #endif
  284. linetrace = '%s, lines %-9s' % ( qfile, '%i-%i' % (int(qnr1),int(qnr2)+1) )
  285. else :
  286. # just copy:
  287. linetrace = linetrace_curr
  288. # remove end-of-line character:
  289. inpline = inpline.strip()
  290. ## DEBUG: display current line ...
  291. #print '%4i | %s' % (iline,inpline)
  292. #print '%4i | %s %s' % (iline,inpline,linetrace)
  293. #
  294. # skip empty lines
  295. #
  296. if len(inpline) == 0 :
  297. # add empty line to output:
  298. self.outfile.append('\n')
  299. # add traceback info:
  300. self.trace.append( linetrace )
  301. # next will be a new line:
  302. line = ''
  303. # next input line:
  304. continue
  305. #
  306. # skip comment lines
  307. #
  308. if inpline.startswith('!') :
  309. # add copy to output file:
  310. self.outfile.append( '%s\n' % inpline )
  311. # add traceback info:
  312. self.trace.append( linetrace )
  313. # next will be a new line:
  314. line = ''
  315. # next input line:
  316. continue
  317. #
  318. # continuation lines (with a continuation mark '\' at the end)
  319. #
  320. # then add this input line:
  321. if line.endswith('\\') :
  322. # remove continuation character, add input line:
  323. line = line[:-1]+inpline
  324. else :
  325. # bright new line:
  326. line = inpline
  327. # continuation mark ? then next line of input file:
  328. if line.endswith('\\') : continue
  329. #
  330. # EVALUATE SPECIALS : #if, #include, etc ONLY if not raw mode
  331. #
  332. if raw :
  333. # treat '#xxx' lines the same as comment:
  334. if inpline.startswith('#') :
  335. # add copy to output file:
  336. self.outfile.append( '%s\n' % inpline )
  337. # add traceback info:
  338. self.trace.append( linetrace )
  339. # next will be a new line:
  340. line = ''
  341. # next input line:
  342. continue
  343. else :
  344. #
  345. # conditional settings (1)
  346. #
  347. mark = '#if'
  348. if line.startswith(mark) :
  349. # push temporary flag to stack, will be replaced after evaluation of condition:
  350. ifstack.append( ( False, True, False, linetrace ) )
  351. mark = '#elif'
  352. if line.startswith(mark) :
  353. # check ...
  354. if len(ifstack) == 0 :
  355. logging.error( 'found orphin "%s" in %s' % (mark,linetrace) )
  356. raise Exception
  357. # remove current top from stack:
  358. resolved,flag,anyflag,msg = ifstack.pop()
  359. # did one of the previous #if/#elif evaluate to True already ?
  360. if resolved and anyflag :
  361. # push to stack that this line resolved to False :
  362. ifstack.append( ( True, False, anyflag, linetrace ) )
  363. # copy to output:
  364. self.outfile.append( '%s\n' % line )
  365. # add traceback info:
  366. self.trace.append( linetrace )
  367. # next input line:
  368. continue
  369. else :
  370. # push temporary flag to stack, will be replaced after evaluation of condition:
  371. ifstack.append( ( False, True, anyflag, linetrace ) )
  372. mark = '#else'
  373. if line.startswith(mark) :
  374. # check ...
  375. if len(ifstack) == 0 :
  376. logging.error( 'found orphin "%s" in %s' % (mark,linetrace) )
  377. raise Exception
  378. # remove current top from stack:
  379. resolved,flag,anyflag,msg = ifstack.pop()
  380. # get higher level settings:
  381. if len(ifstack) > 0 :
  382. resolved_prev,flag_prev,anyflag_prev,msg_prev = ifstack[-1]
  383. else :
  384. flag_prev = True
  385. # should next lines be included ?
  386. # reverse flag, take into acount higher level:
  387. new_flag = (not flag) and (not anyflag) and flag_prev
  388. # push to stack:
  389. ifstack.append( ( resolved, new_flag, False, linetrace ) )
  390. # copy to output:
  391. self.outfile.append( '%s\n' % line )
  392. # add traceback info:
  393. self.trace.append( linetrace )
  394. # next input line:
  395. continue
  396. # is this the end of a condition ?
  397. mark = '#endif'
  398. if line.startswith(mark) :
  399. # check ...
  400. if len(ifstack) == 0 :
  401. logging.error( 'found orphin "%s" in %s' % (mark,linetrace) )
  402. raise Exception
  403. #endif
  404. # remove top from stack:
  405. top = ifstack.pop()
  406. # copy to output:
  407. self.outfile.append( '%s\n' % line )
  408. # add traceback info:
  409. self.trace.append( linetrace )
  410. # next input line:
  411. continue
  412. # within if-statements ?
  413. if len(ifstack) > 0 :
  414. # extract current top:
  415. resolved,flag,anyflag,msg = ifstack[-1]
  416. # already resolved ? then check if this line should be skipped:
  417. if resolved and (not flag) :
  418. # skip this line, but include commented version in output:
  419. self.outfile.append( '!%s\n' % line )
  420. # add traceback info:
  421. self.trace.append( linetrace )
  422. # read the next input line:
  423. continue
  424. #
  425. # handle '#eval' lines
  426. #
  427. mark = '#eval'
  428. if line.startswith(mark):
  429. # info ..
  430. if not warned_for_eval :
  431. if not silent: logging.warning( 'the #eval statements in rc-files are deprecated, use {key:value} pairs instead' )
  432. warned_for_eval = True
  433. # add commented copy to output:
  434. self.outfile.append( '!evaluated>>> '+line )
  435. # add traceback info:
  436. self.trace.append( linetrace )
  437. # remove leading mark:
  438. line = line.lstrip(mark)
  439. # multiple settings are seperated by ';' :
  440. evals = line.split(';')
  441. # insert in output file:
  442. for k in range(len(evals)) :
  443. # split in key and value:
  444. key,value = evals[k].split('=')
  445. # insert:
  446. self.outfile.append( '%s : %s' % (key,value) )
  447. # add traceback info:
  448. self.trace.append( linetrace )
  449. # next input line:
  450. continue
  451. #
  452. # replace ${..} values
  453. #
  454. # ensure that common marks are evaluated correctly:
  455. start_mark = marks[0].replace('{','\{').replace('<','\<').replace('$','\$')
  456. close_mark = marks[1].replace('}','\}').replace('>','\>')
  457. # set syntax of keywords to be matched, e.g. '${...}' :
  458. pattern = start_mark+'[A-Za-z0-9_.]+'+close_mark
  459. # make a regular expression that matches all variables:
  460. rc_varpat = re.compile( pattern )
  461. # search all matching paterns:
  462. pats = re.findall(rc_varpat,line)
  463. # counter for unexpanded substitutions:
  464. ntobedone = 0
  465. # loop over matches:
  466. for pat in pats :
  467. # remove enclosing characters:
  468. key = pat.lstrip(start_mark).rstrip(close_mark)
  469. # test some dictionaries for matching key:
  470. if self.values.has_key(key) :
  471. # get previously defined value:
  472. val = self.values[key]
  473. # substitute value:
  474. line = line.replace(pat,val)
  475. # set flag:
  476. something_done = True
  477. elif os.environ.has_key(key) :
  478. # get value from environment:
  479. val = os.environ[key]
  480. # substitute value:
  481. line = line.replace(pat,val)
  482. # set flag:
  483. something_done = True
  484. elif key == 'pid' :
  485. # special value: process id; convert to character:
  486. val = '%i' % os.getpid()
  487. # substitute value:
  488. line = line.replace(pat,val)
  489. # set flag:
  490. something_done = True
  491. elif key == 'script' :
  492. # special value: base name of the calling script, without extension:
  493. script,ext = os.path.splitext(os.path.basename(sys.argv[0]))
  494. # substitute value:
  495. line = line.replace(pat,script)
  496. # set flag:
  497. something_done = True
  498. else :
  499. # could not substitute yet; set flag:
  500. ntobedone = ntobedone + 1
  501. # add to list with unresolved keys:
  502. if key not in undefined_keys : undefined_keys.append(key)
  503. # continue with next substitution:
  504. continue
  505. # not all substituted ?
  506. if ntobedone > 0 :
  507. # add line to output:
  508. self.outfile.append(line)
  509. # add traceback info:
  510. self.trace.append( linetrace )
  511. # a new pass is needed:
  512. something_to_be_done = True
  513. # store for info messages:
  514. unresolved_lines.append( '%s | %s' % (linetrace,line) )
  515. # could this be a 'key : value' line ?
  516. if ':' in line :
  517. # split, remove leading and end space:
  518. qkey,qvalue = line.split(':',1)
  519. qkey = qkey.strip()
  520. # assume it is indeed a key if it does not contain whitespace,
  521. # no start mark, and does not start wiht '#' :
  522. if (' ' not in qkey) and (start_mark not in qkey) and (not qkey.startswith('#')) :
  523. # add to list:
  524. if qkey not in keys_with_unresolved_value : keys_with_unresolved_value.append(qkey)
  525. # next input line:
  526. continue
  527. #
  528. # handle '#include' lines
  529. #
  530. mark = '#include'
  531. if line.startswith(mark) :
  532. # remove leading mark, what remains is file to be included:
  533. inc_file = line.lstrip(mark).strip()
  534. # check ...
  535. if not os.path.exists(inc_file) :
  536. inc_file = os.path.join(self.rootdir,inc_file)
  537. logging.debug( 'Added rootdir to requested include: %s' % inc_file )
  538. #endif
  539. if not os.path.exists(inc_file) :
  540. logging.error( 'include file not found : %s' % inc_file )
  541. logging.error( linetrace )
  542. raise IOError, 'include file not found : %s' % inc_file
  543. # read content:
  544. inc_f = open( inc_file, 'r' )
  545. inc_rc = inc_f.readlines()
  546. inc_f.close()
  547. # add extra comment for output file:
  548. self.outfile.append( '! >>> %s >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>\n' % inc_file )
  549. self.outfile.extend( inc_rc )
  550. self.outfile.append( '! <<< %s <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<\n' % inc_file )
  551. # add traceback info:
  552. self.trace.append( linetrace )
  553. for jline in range(len(inc_rc)) :
  554. self.trace.append( '"%s", line %-10s' % (inc_file,str(jline+1)) )
  555. self.trace.append( linetrace )
  556. # set flag:
  557. something_done = True
  558. # a new pass is needed:
  559. something_to_be_done = True
  560. # next input line:
  561. continue
  562. #
  563. # conditional settings (2)
  564. #
  565. mark1 = '#if'
  566. mark2 = '#elif'
  567. if line.startswith(mark1) or line.startswith(mark2) :
  568. # remove leading mark, what remains is logical expression:
  569. expression = line.lstrip(mark1).strip()
  570. expression = line.lstrip(mark2).strip()
  571. # common mistake is to add a ':' as in python; remove this:
  572. if expression.endswith(':') : expression = expression.rstrip(':').strip()
  573. # evaluate:
  574. try :
  575. flag = eval( expression )
  576. except :
  577. logging.error( 'could not evaluate expression:' )
  578. logging.error( ' %s' % expression )
  579. logging.error( 'in %s' % linetrace )
  580. raise Exception
  581. # remove temporary top added before during this pass:
  582. tmp_statement,tmp_flag,tmp_anyflag,tmp_msg = ifstack.pop()
  583. # extract current top if necessary:
  584. if len(ifstack) > 0 :
  585. dummy_statement,prev_flag,dummy_anyflag,dummy_msg = ifstack[-1]
  586. else :
  587. prev_flag = True
  588. # should next lines be included ?
  589. new_flag = prev_flag and tmp_flag and flag
  590. # any if/elif evaluated to true in this sequence ?
  591. new_anyflag = tmp_anyflag or new_flag
  592. # add to stack, now resolved, take into accout current flag:
  593. ifstack.append( ( True, new_flag, new_anyflag, linetrace ) )
  594. # copy to output:
  595. self.outfile.append( '%s\n' % line )
  596. # add traceback info:
  597. self.trace.append( linetrace )
  598. # next input line:
  599. continue
  600. #
  601. # error message: special command to raise an exception
  602. #
  603. mark = '#error'
  604. if line.startswith(mark) :
  605. # remove leading mark, what remains is error message:
  606. msg = line.lstrip(mark).strip()
  607. # display:
  608. logging.error( msg )
  609. # add info:
  610. logging.error( 'error message in %s' % linetrace )
  611. # stop:
  612. raise Exception
  613. #
  614. # check for common mistakes
  615. #
  616. if line.startswith('#') :
  617. logging.error( 'line in rcfile starts with "#" but is not an "#include" or other special line;' )
  618. logging.error( 'if it is supposed to be comment, please start with "!" ...' )
  619. logging.error( ' %s' % line )
  620. logging.error( '%s' % linetrace )
  621. raise IOError
  622. if ':' not in line :
  623. logging.error( 'key/value line should contain a ":"' )
  624. logging.error( '%s' % linetrace )
  625. raise IOError
  626. #
  627. # add to output
  628. #
  629. # add line to output:
  630. self.outfile.append( '%s\n' % line )
  631. # add traceback info:
  632. self.trace.append( linetrace )
  633. #
  634. # add key/value pair
  635. #
  636. # not if inside an unresolved if-statement ...
  637. if len(ifstack) > 0 :
  638. # get top values:
  639. resolved,flag,anyflag,msg = ifstack[-1]
  640. # not resolved yet ? then continue:
  641. if not resolved : continue
  642. # split in key and value;
  643. # value might contain ':' too, so at maximum 1 split:
  644. key,val = line.split(':',1)
  645. # remove comment from value:
  646. if '!' in val :
  647. # not if '\!' is in the value ...
  648. if not '\!' in val : val,comment = val.split('!')
  649. # replace all slash-comments:
  650. val = val.replace('\!','!')
  651. # remove spaces:
  652. key = key.strip()
  653. val = val.strip()
  654. # already defined ?
  655. if self.values.has_key(key) :
  656. # in raw mode this happends often due to #if statements ...
  657. if self.raw :
  658. # reset to a lists if not yet:
  659. if not isinstance(self.values[key],list) :
  660. self.values [key] = [self.values [key]]
  661. self.sources[key] = [self.sources[key]]
  662. # add:
  663. self.values [key].append(val)
  664. self.sources[key].append(linetrace)
  665. #logger.warning( 'found double key (ignored in raw mode) : %s' % key )
  666. else :
  667. # this will occure often after the first pass since
  668. # the keys are resolved again and again ;
  669. # therefore, only complain if this definition is read
  670. # from a different line :
  671. if linetrace != self.sources[key] :
  672. logging.error( 'duplicated key \"%s\" found:' % key)
  673. logging.error( 'first definition in %s is:' % self.sources[key])
  674. logging.error( ' %s : %s' % (key,str(self.values[key])) )
  675. logging.error( 'second definition in %s is:' % linetrace.strip() )
  676. logging.error( ' %s : %s' % (key,str(val)) )
  677. raise Exception
  678. else :
  679. # store new value:
  680. self.values[key] = val
  681. self.sources[key] = linetrace
  682. # set flag:
  683. something_done = True
  684. # display key and value ...
  685. #print ' --> %s : %s, from %s' % (key,val, linetrace)
  686. ## info ...
  687. #print '~~~ outfile ~~~~~~~~~~~~~~~~~~~~~~~'
  688. #for line in self.outfile : print line.strip()
  689. #print '~~~ key/values ~~~~~~~~~~~~~~~~~~~~'
  690. #for k,v in self.iteritems() :
  691. # print '%s : %s' % (k,v)
  692. ##endfor
  693. #print '-------------------------------------------------'
  694. #print ''
  695. # check ...
  696. if len(ifstack) > 0 :
  697. logging.error( 'unterminated if-statement ; current stack:' )
  698. for resolved,flag,anyflag,msg in ifstack : logging.error( msg )
  699. logging.error( 'please fix the rcfile or debug this script ...' )
  700. raise Exception
  701. # check ...
  702. if something_to_be_done :
  703. # check for unterminated loop ...
  704. if not something_done :
  705. # list all unresolved lines:
  706. logging.error( 'Could not resolve the following lines in rcfile(s):' )
  707. logging.error( '' )
  708. for uline in unresolved_lines :
  709. logging.error( ' %s' % uline )
  710. #endfor
  711. logging.error( '' )
  712. # list all undefined keys:
  713. logging.error( ' Undefined key(s):' )
  714. logging.error( '' )
  715. for ukey in undefined_keys :
  716. # do not list them if they are undefined because the value
  717. # depends on other undefined keys:
  718. if ukey not in keys_with_unresolved_value :
  719. # display:
  720. logging.error( ' %s' % ukey )
  721. # loop over unresolved lines to see in which the key is used:
  722. for uline in unresolved_lines :
  723. # search for '${key}' pattern:
  724. if marks[0]+ukey+marks[1] in uline :
  725. logging.error( ' %s' % uline )
  726. #endif
  727. #endfor
  728. logging.error( '' )
  729. logging.error( 'please fix the rcfile(s) or debug this script ...' )
  730. raise Exception
  731. else :
  732. # finished ...
  733. break
  734. # for safety ...
  735. if ipass == 100 :
  736. logging.error( 'resolving rc file has reached pass %i ; something wrong ?' % ipass )
  737. raise Exception
  738. # new pass:
  739. ipass = ipass + 1
  740. # renew input:
  741. inpfile = self.outfile
  742. # renew traceback:
  743. inptrace = self.trace
  744. # ***
  745. def has_key( self, key ) :
  746. # from dictionairy:
  747. return self.values.has_key(key)
  748. # ***
  749. def keys( self ) :
  750. # from dictionairy:
  751. return self.values.keys()
  752. # ***
  753. def get( self, key, totype='', default=None, verbose=False ) :
  754. """
  755. rcf.get( 'my.value' [,default=None] )
  756. Return element 'key' from the dictionairy.
  757. If the element is not present but a default is specified, then return
  758. the default value.
  759. If 'verbose' is set to True, then print to the log which values is
  760. returned for the requested key.
  761. The option argument 'totype' defines the conversion to a Python type.
  762. If 'totype' is set to 'bool', the return value is the
  763. boolean True for values 'T', 'True', 'yes', and '1',
  764. and False for 'F', 'False', 'no', or '0' ;
  765. for other values, an exception will be raised.
  766. """
  767. # external:
  768. import logging
  769. # element found ?
  770. if self.values.has_key(key) :
  771. # copy value:
  772. value = self.values[key]
  773. # convert ?
  774. if totype == 'bool' :
  775. # convert to boolean:
  776. if value in [True,'T','True','yes','1'] :
  777. value = True
  778. elif value in [False,'F','False','no','0'] :
  779. value = False
  780. else :
  781. logging.error( "value of key '%s' is not a boolean : %s" % (key,str(value)) )
  782. raise Exception
  783. #endif
  784. elif len(totype) > 0 :
  785. # convert to other type ...
  786. value = eval( '%s(%s)' % (totype,value) )
  787. #endif
  788. # for debugging ...
  789. if verbose : logging.debug( 'rc setting "%s" : "%s"' % (key,str(value)) )
  790. else :
  791. # default value specified ?
  792. if default != None :
  793. # copy default:
  794. value = default
  795. # for debugging ...
  796. if verbose : logging.debug( 'rc setting "%s" : "%s" (deault)' % (key,str(value)) )
  797. else :
  798. # something wrong ...
  799. logging.error( "key '%s' not found in '%s' and no default specified" % (key,self.filename) )
  800. raise KeyError
  801. return value
  802. # ***
  803. def replace( self, key, val ) :
  804. """
  805. Replace a key by a new value.
  806. """
  807. # external:
  808. import logging
  809. # search for a line '<key> : <val>'
  810. # loop over lines in output file:
  811. found = False
  812. for iline in range(len(self.outfile)) :
  813. # extract:
  814. line = self.outfile[iline]
  815. # skip lines that are no key:value pair for sure ...
  816. if ':' not in line : continue
  817. # split once at first ':'
  818. k,v = line.split(':',1)
  819. # match ?
  820. if k.strip() == key :
  821. # replace line in original file:
  822. self.outfile[iline] = '%s : %s\n' % (key,str(val))
  823. # replace value:
  824. self.values[key] = val
  825. # set flag:
  826. found = True
  827. # found, thus no need to continue;
  828. # except in raw mode, since there multiple keys might exist:
  829. if not self.raw : break
  830. # not found ?
  831. if not found :
  832. logging.error( 'could not replace key : %s' % key )
  833. raise Exception
  834. # ok
  835. return
  836. # ***
  837. def add( self, key, val, comment='' ) :
  838. """Add a new key/value pair."""
  839. # add lines:
  840. self.outfile.append( '\n' )
  841. if len(comment) > 0 : self.outfile.append( '! %s\n' % comment )
  842. self.outfile.append( '%s : %s\n' % (key,str(val)) )
  843. # add to dictionairy:
  844. self.values[key] = val
  845. # ok
  846. return
  847. # ***
  848. def substitute( self, line, marks=('${','}') ) :
  849. """
  850. Return a line with all '${..}' parts replaced by the corresponding rcfile values.
  851. The 2-item tupple (mark1,mark2) could be used to re-define the default
  852. key pattern '${..}' into something else:
  853. <mark1>...<mark2>
  854. """
  855. # external:
  856. import re
  857. # ensure that common marks are evaluated correctly:
  858. start_mark = marks[0].replace('{','\{').replace('<','\<').replace('$','\$')
  859. close_mark = marks[1].replace('}','\}').replace('>','\>')
  860. # set syntax of keywords to be matched, e.g. '${...}' :
  861. pattern = start_mark+'[A-Za-z0-9_.]+'+close_mark
  862. # make a regular expression that matches all variables:
  863. rc_varpat = re.compile( pattern )
  864. # search all matching paterns:
  865. pats = re.findall(rc_varpat,line)
  866. # loop over matches:
  867. for pat in pats :
  868. # remove enclosing characters:
  869. key = pat.lstrip(start_mark).rstrip(close_mark)
  870. # test dictionary for matching key:
  871. if self.values.has_key(key) :
  872. # get previously defined value:
  873. val = self.values[key]
  874. # substitute value:
  875. line = line.replace(pat,val)
  876. #endif
  877. #endfor # matched patterns
  878. # ok
  879. return line
  880. # ***
  881. def WriteFile( self, filename ) :
  882. """ write the dictionary to file"""
  883. # open file for writing:
  884. f = open(filename,'w')
  885. ## loop over key/value pairs:
  886. #for k,v in self.iteritems():
  887. # # add line; at least the specified number of characters
  888. # # is used for the key:
  889. # f.write( '%-20s:%s\n' % (k,v) )
  890. ##endfor
  891. # write processed input:
  892. f.writelines( self.outfile )
  893. # close file:
  894. f.close()
  895. # ***
  896. def read( rcfilename, silent=False ) :
  897. """
  898. This method reads an rc-file by making an instance of the RcFile class,
  899. and then returns the dictionary of values only.
  900. This makes it backwards compatible with older implementations of the rc.py module
  901. """
  902. rcdict = RcFile( rcfilename, silent=silent )
  903. return rcdict.values
  904. # ***
  905. def write( filename, rcdict ) :
  906. """
  907. This method writes an rc-file dictionary.
  908. This makes it backwards compatible with older implementations of the rc.py module
  909. """
  910. # open file for writing:
  911. f = open(filename,'w')
  912. # loop over key/value pairs:
  913. for k,v in rcdict.items():
  914. # add line; at least the specified number of characters
  915. # is used for the key:
  916. f.write( '%-20s:%s\n' % (k,v) )
  917. # close file:
  918. f.close()
  919. # ------------------------------------------------
  920. # script
  921. # ------------------------------------------------
  922. if __name__ == '__main__':
  923. # external ...
  924. import sys
  925. import optparse
  926. import logging
  927. import traceback
  928. # extract arguments from sys.argv array:
  929. # 0 = name of calling script, 1: = actual arguments
  930. args = sys.argv[1:]
  931. # set text for 'usage' help line:
  932. usage = "\n %prog <rcfile> <key> [-b|--bool] [--default<=value>]\n %prog <rcfile> -w|--write\n %prog -h|--help\n %prog -d|--doc"
  933. # initialise the option parser:
  934. parser = optparse.OptionParser(usage=usage)
  935. # define options:
  936. parser.add_option( "-d", "--doc",
  937. help="print documentation",
  938. dest="doc", action="store_true", default=False )
  939. parser.add_option( "-v", "--verbose",
  940. help="print information messages",
  941. dest="verbose", action="store_true", default=False )
  942. parser.add_option( "-b", "--bool",
  943. help="return 'True' for values 'T', 'True', 'yes', or '1', and 'False' for 'F', 'False', 'no', or '0'",
  944. dest="boolean", action="store_true", default=False )
  945. parser.add_option( "--default",
  946. help="default value returned if key is not found",
  947. dest="default", action="store" )
  948. parser.add_option( "-w", "--write",
  949. help="write pre-processed rcfile",
  950. dest="write", action="store_true", default=False )
  951. # now parse the actual arguments:
  952. opts,args = parser.parse_args( args=args )
  953. # print documentation ?
  954. if opts.doc :
  955. print __doc__
  956. sys.exit(0)
  957. # recfile argument should be provided:
  958. if len(args) < 1 :
  959. parser.error("no name of rcfile provided\n")
  960. # extract:
  961. rcfile = args[0]
  962. # read rcfile in dictionary:
  963. try :
  964. rcf = RcFile( rcfile, silent=(not opts.verbose) )
  965. except :
  966. if opts.verbose : logging.error( traceback.format_exc() )
  967. sys.exit(1)
  968. # print pre-processed file ?
  969. if opts.write :
  970. for line in rcf.outfile : print line.strip()
  971. sys.exit(0)
  972. # key argument should be provided:
  973. if len(args) < 2 :
  974. parser.error("no name of rckey provided\n")
  975. # extract:
  976. rckey = args[1]
  977. # key present ?
  978. if rcf.has_key(rckey) :
  979. # print requested value:
  980. if opts.boolean :
  981. # extract value:
  982. flag = rcf.get(rckey,'bool')
  983. # print result:
  984. if flag :
  985. print 'True'
  986. else :
  987. print 'False'
  988. else :
  989. # extract value:
  990. value = rcf.get(rckey)
  991. print value
  992. else :
  993. # default value provided ?
  994. if opts.default != None :
  995. print opts.default
  996. else :
  997. print 'ERROR - key "%s" not found in rcfile "%s" and no default specified' % (rckey,rcfile)
  998. sys.exit(1)
  999. # ------------------------------------------------
  1000. # end
  1001. # ------------------------------------------------