system_messages.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  1. # Copyright (C) 2011 Internet Systems Consortium, Inc. ("ISC")
  2. #
  3. # Permission to use, copy, modify, and/or distribute this software for any
  4. # purpose with or without fee is hereby granted, provided that the above
  5. # copyright notice and this permission notice appear in all copies.
  6. #
  7. # THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH
  8. # REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
  9. # AND FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT,
  10. # INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
  11. # LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
  12. # OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
  13. # PERFORMANCE OF THIS SOFTWARE.
  14. # Produce System Messages Manual
  15. #
  16. # This tool reads all the .mes files in the directory tree whose root is given
  17. # on the command line and interprets them as message files. It pulls
  18. # all the messages and description out, sorts them by message ID, and writes
  19. # them out as a single (formatted) file.
  20. #
  21. # Invocation:
  22. # The code is invoked using the command line:
  23. #
  24. # python system_messages.py [-o <output-file>] <top-source-directory>
  25. #
  26. # If no output file is specified, output is written to stdout.
  27. import re
  28. import os
  29. import sys
  30. from optparse import OptionParser
  31. # Main dictionary holding all the messages. The messages are accumulated here
  32. # before being printed in alphabetical order.
  33. dictionary = {}
  34. # The structure of the output page is:
  35. #
  36. # header
  37. # message
  38. # separator
  39. # message
  40. # separator
  41. # :
  42. # separator
  43. # message
  44. # trailer
  45. #
  46. # (Indentation is not relevant - it has only been added to the above
  47. # illustration to make the structure clearer.) The text of these section is:
  48. # Header - this is output before anything else.
  49. SEC_HEADER="""<?xml version="1.0" encoding="UTF-8"?>
  50. <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.2//EN"
  51. "http://www.oasis-open.org/docbook/xml/4.2/docbookx.dtd" [
  52. <!ENTITY mdash "&#x2014;" >
  53. <!ENTITY % version SYSTEM "version.ent">
  54. %version;
  55. ]>
  56. <!--
  57. This XML document is generated using the system_messages.py tool
  58. based on the .mes message files.
  59. Do not edit this file.
  60. -->
  61. <book>
  62. <?xml-stylesheet href="kea-guide.css" type="text/css"?>
  63. <bookinfo>
  64. <title>Kea Messages Manual</title>
  65. <copyright>
  66. <year>2011-2015</year><holder>Internet Systems Consortium, Inc.</holder>
  67. </copyright>
  68. <abstract>
  69. <para>
  70. This is the messages manual for Kea version &__VERSION__;.
  71. The most up-to-date version of this document, along with
  72. other documents for Kea, can be found at
  73. <ulink url="http://kea.isc.org/docs"/>.
  74. </para>
  75. </abstract>
  76. <releaseinfo>This is the messages manual for Kea version
  77. &__VERSION__;.</releaseinfo>
  78. </bookinfo>
  79. <chapter id="intro">
  80. <title>Introduction</title>
  81. <para>
  82. This document lists each message that can be logged by the
  83. programs in the Kea package. Each entry in this manual
  84. is of the form:
  85. <screen>IDENTIFICATION message-text</screen>
  86. ... where "IDENTIFICATION" is the message identification included
  87. in each message logged and "message-text" is the accompanying
  88. message text. The "message-text" may include placeholders of the
  89. form "%1", "%2" etc.; these parameters are replaced by relevant
  90. values when the message is logged.
  91. </para>
  92. <para>
  93. Each entry is also accompanied by a description giving more
  94. information about the circumstances that result in the message
  95. being logged.
  96. </para>
  97. <para>
  98. For information on configuring and using Kea logging,
  99. refer to the <ulink url="kea-guide.html">Kea Guide</ulink>.
  100. </para>
  101. </chapter>
  102. <chapter id="messages">
  103. <title>Kea Log Messages</title>
  104. <para>
  105. <variablelist>
  106. """
  107. # This is output once for each message. The string contains substitution
  108. # tokens: $I is replaced by the message identification, $T by the message text,
  109. # and $D by the message description.
  110. SEC_MESSAGE = """<varlistentry id="$I">
  111. <term>$I $T</term>
  112. <listitem><para>
  113. $D
  114. </para></listitem>
  115. </varlistentry>"""
  116. # A description may contain blank lines intended to separate paragraphs. If so,
  117. # each blank line is replaced by the following.
  118. SEC_BLANK = "</para><para>"
  119. # The separator is copied to the output verbatim after each message except
  120. # the last.
  121. SEC_SEPARATOR = ""
  122. # The trailier is copied to the output verbatim after the last message.
  123. SEC_TRAILER = """ </variablelist>
  124. </para>
  125. </chapter>
  126. </book>"""
  127. def reportError(filename, what):
  128. """Report an error and exit"""
  129. print("*** ERROR in ", filename, file=sys.stderr)
  130. print("*** REASON: ", what, file=sys.stderr)
  131. print("*** System message generator terminating", file=sys.stderr)
  132. sys.exit(1)
  133. def replaceTag(string):
  134. """Replaces the '<' and '>' in text about to be inserted into the template
  135. sections above with &lt; and &gt; to avoid problems with message text
  136. being interpreted as XML text.
  137. """
  138. string1 = string.replace("<", "&lt;")
  139. string2 = string1.replace(">", "&gt;")
  140. return string2
  141. def replaceBlankLines(lines):
  142. """Replaces blank lines in an array with the contents of the 'blank'
  143. section.
  144. """
  145. result = []
  146. for l in lines:
  147. if len(l) == 0:
  148. result.append(SEC_BLANK)
  149. else:
  150. result.append(l)
  151. return result
  152. # Printing functions
  153. def printHeader():
  154. print(SEC_HEADER)
  155. def printSeparator():
  156. print(SEC_SEPARATOR)
  157. def printMessage(msgid):
  158. # In the message ID, replace "<" and ">" with XML-safe versions and
  159. # substitute into the data.
  160. m1 = SEC_MESSAGE.replace("$I", replaceTag(msgid))
  161. # Do the same for the message text.
  162. m2 = m1.replace("$T", replaceTag(dictionary[msgid]['text']))
  163. # Do the same for the description then replace blank lines with the
  164. # specified separator. (We do this in that order to avoid replacing
  165. # the "<" and ">" in the XML tags in the separator.)
  166. desc1 = [replaceTag(l) for l in dictionary[msgid]['description']]
  167. desc2 = replaceBlankLines(desc1)
  168. # Join the lines together to form a single string and insert into
  169. # current text.
  170. m3 = m2.replace("$D", "\n".join(desc2))
  171. print(m3)
  172. def printTrailer():
  173. print(SEC_TRAILER)
  174. def removeEmptyLeadingTrailing(lines):
  175. """Removes leading and trailing empty lines.
  176. A list of strings is passed as argument, some of which may be empty.
  177. This function removes from the start and end of list a contiguous
  178. sequence of empty lines and returns the result. Embedded sequence of
  179. empty lines are not touched.
  180. Parameters:
  181. lines List of strings to be modified.
  182. Return:
  183. Input list of strings with leading/trailing blank line sequences
  184. removed.
  185. """
  186. retlines = []
  187. # Dispose of degenerate case of empty array
  188. if len(lines) == 0:
  189. return retlines
  190. # Search for first non-blank line
  191. start = 0
  192. while start < len(lines):
  193. if len(lines[start]) > 0:
  194. break
  195. start = start + 1
  196. # Handle case when entire list is empty
  197. if start >= len(lines):
  198. return retlines
  199. # Search for last non-blank line
  200. finish = len(lines) - 1
  201. while finish >= 0:
  202. if len(lines[finish]) > 0:
  203. break
  204. finish = finish - 1
  205. retlines = lines[start:finish + 1]
  206. return retlines
  207. def addToDictionary(msgid, msgtext, desc, filename):
  208. """Add the current message ID and associated information to the global
  209. dictionary. If a message with that ID already exists, loop appending
  210. suffixes of the form "(n)" to it until one is found that doesn't.
  211. Parameters:
  212. msgid Message ID
  213. msgtext Message text
  214. desc Message description
  215. filename File from which the message came. Currently this is
  216. not used, but a future enhancement may wish to include the
  217. name of the message file in the messages manual.
  218. """
  219. # If the ID is in the dictionary, append a "(n)" to the name - this will
  220. # flag that there are multiple instances. (However, this is an error -
  221. # each ID should be unique in the code.)
  222. if msgid in dictionary:
  223. i = 1
  224. while msgid + " (" + str(i) + ")" in dictionary:
  225. i = i + 1
  226. msgid = msgid + " (" + str(i) + ")"
  227. # Remove leading and trailing blank lines in the description, then
  228. # add everything into a subdictionary which is then added to the main
  229. # one.
  230. details = {}
  231. details['text'] = msgtext
  232. details['description'] = removeEmptyLeadingTrailing(desc)
  233. details['filename'] = filename
  234. dictionary[msgid] = details
  235. def processFileContent(filename, lines):
  236. """Processes file content. Messages and descriptions are identified and
  237. added to a dictionary (keyed by message ID). If the key already exists,
  238. a numeric suffix is added to it.
  239. Parameters:
  240. filename Name of the message file being processed
  241. lines Lines read from the file
  242. """
  243. prefix = "" # Last prefix encountered
  244. msgid = "" # Last message ID encountered
  245. msgtext = "" # Text of the message
  246. description = [] # Description
  247. for l in lines:
  248. if l.startswith("$"):
  249. # Starts with "$". Ignore anything other than $PREFIX
  250. words = re.split("\s+", l)
  251. if words[0].upper() == "$PREFIX":
  252. if len(words) == 1:
  253. prefix = ""
  254. else:
  255. prefix = words[1]
  256. elif l.startswith("%"):
  257. # Start of a message. Add the message we were processing to the
  258. # dictionary and clear everything apart from the file name.
  259. if msgid != "":
  260. addToDictionary(msgid, msgtext, description, filename)
  261. msgid = ""
  262. msgtext = ""
  263. description = []
  264. # Start of a message
  265. l = l[1:].strip() # Remove "%" and trim leading spaces
  266. if len(l) == 0:
  267. printError(filename, "Line with single % found")
  268. next
  269. # Split into words. The first word is the message ID
  270. words = re.split("\s+", l)
  271. msgid = (prefix + words[0]).upper()
  272. msgtext = l[len(words[0]):].strip()
  273. else:
  274. # Part of a description, so add to the current description array
  275. description.append(l)
  276. # All done, add the last message to the global dictionaty.
  277. if msgid != "":
  278. addToDictionary(msgid, msgtext, description, filename)
  279. def processFile(filename):
  280. """Processes a file by reading it in and stripping out all comments and
  281. and directives. Leading and trailing blank lines in the file are removed
  282. and the remainder passed for message processing.
  283. Parameters:
  284. filename Name of the message file to process
  285. """
  286. lines = open(filename).readlines();
  287. # Trim leading and trailing spaces from each line, and remove comments.
  288. lines = [l.strip() for l in lines]
  289. lines = [l for l in lines if not l.startswith("#")]
  290. # Remove leading/trailing empty line sequences from the result
  291. lines = removeEmptyLeadingTrailing(lines)
  292. # Interpret content
  293. processFileContent(filename, lines)
  294. def processAllFiles(root):
  295. """Iterates through all files in the tree starting at the given root and
  296. calls processFile for all .mes files found.
  297. Parameters:
  298. root Directory that is the root of the source tree
  299. """
  300. for (path, dirs, files) in os.walk(root):
  301. # Identify message files
  302. mes_files = [f for f in files if f.endswith(".mes")]
  303. # ... and process each file in the list
  304. for m in mes_files:
  305. processFile(path + os.sep + m)
  306. # Main program
  307. if __name__ == "__main__":
  308. parser = OptionParser(usage="Usage: %prog [--help | options] root")
  309. parser.add_option("-o", "--output", dest="output", default=None,
  310. metavar="FILE",
  311. help="output file name (default to stdout)")
  312. (options, args) = parser.parse_args()
  313. if len(args) == 0:
  314. parser.error("Must supply directory at which to begin search")
  315. elif len(args) > 1:
  316. parser.error("Only a single root directory can be given")
  317. # Redirect output if specified (errors are written to stderr)
  318. if options.output is not None:
  319. sys.stdout = open(options.output, 'w')
  320. # Read the files and load the data
  321. processAllFiles(args[0])
  322. # Now just print out everything we've read (in alphabetical order).
  323. count = 1
  324. printHeader()
  325. for msgid in sorted(dictionary):
  326. if count > 1:
  327. printSeparator()
  328. count = count + 1
  329. printMessage(msgid)
  330. printTrailer()