2
0
mirror of https://gitlab.isc.org/isc-projects/kea synced 2025-08-22 09:57:41 +00:00
kea/doc/sphinx/mes2doc.py

175 lines
5.0 KiB
Python
Raw Normal View History

#!/usr/bin/env python3
2025-06-20 17:30:19 +02:00
# Copyright (C) 2019-2025 Internet Systems Consortium, Inc. ("ISC")
#
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http:#mozilla.org/MPL/2.0/.
# Produce System Messages Manual
#
# This tool reads all the message files given on the command line.
# It pulls all the messages and description out, sorts them by
# message ID, and writes them out as a single (formatted) file.
#
# Invocation:
# The code is invoked using the command line:
#
# mes2doc.py [-o <output-file>] <files>
#
# If no output file is specified, output is written to stdout.
# The produced format is ReStructuredText.
import argparse
import os
import pathlib
import re
import sys
def parse_args():
parser = argparse.ArgumentParser(description='Convert set of *.mes files to .rst documentation format')
parser.add_argument('-o', '--output', help='Output file name (default to stdout).')
parser.add_argument('files', help='Input .mes files.', nargs='?')
args = parser.parse_args()
return args
def read_input_files(files):
messages = {}
for f in files:
if '/premium/' in f and not pathlib.Path(f).is_file():
# Premium can be missing which is fine for daily development, and CI tasks.
print(f'Ignoring non-existing file {f}')
continue
[#3287] fix pylint warnings - C0115: Missing class docstring (missing-class-docstring) - C0123: Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck) - C0201: Consider iterating the dictionary directly instead of calling .keys() (consider-iterating-dictionary) - C0206: Consider iterating with .items() (consider-using-dict-items) - C0411: standard import "..." should be placed before "..." (wrong-import-order) - C0415: Import outside toplevel (...) (import-outside-toplevel) - C1802: Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty (use-implicit-booleaness-not-len) - E0001: Parsing failed: 'invalid syntax (<unknown>, line 2313)' (syntax-error) - E0401: Unable to import '...' (import-error) - E0602: Undefined variable 'l' (undefined-variable) - R0205: Class 'VagrantEnv' inherits from object, can be safely removed from bases in python3 (useless-object-inheritance) - E1101: Instance of 'NSECBASE' has no 'dump_fixedpart' member (no-member) - E1123: Unexpected keyword argument 'capture' in method call (unexpected-keyword-arg) - R0902: Too many instance attributes (too-many-instance-attributes) - R0913: Too many arguments (too-many-arguments) - R0916: Too many boolean expressions in if statement (6/5) (too-many-boolean-expressions) - R1717: Consider using a dictionary comprehension (consider-using-dict-comprehension) - R1722: Consider using 'sys.exit' instead (consider-using-sys-exit) - R1732: Consider using 'with' for resource-allocating operations (consider-using-with) - R1735: Consider using '{}' instead of a call to 'dict'. (use-dict-literal) - W0102: Dangerous default value sys.argv[1:] (builtins.list) as argument (dangerous-default-value) - W0102: Dangerous default value {} as argument (dangerous-default-value) - W0106: Expression "[f.write('%02x' % x) for x in bin_address]" is assigned to nothing (expression-not-assigned) - W0107: Unnecessary pass statement (unnecessary-pass) - W0201: Attribute 'config' defined outside __init__ (attribute-defined-outside-init) - W0404: Reimport '...' (imported line ...) (reimported) - W0611: Unused import ... (unused-import) - W0612: Unused variable '...' (unused-variable) - W0613: Unused argument '...' (unused-argument) - W0621: Redefining name '...' from outer scope (line 1471) (redefined-outer-name) - W0622: Redefining built-in '...' (redefined-builtin) - W0707: Consider explicitly re-raising using 'raise ... from ...' (raise-missing-from) - W0718: Catching too general exception Exception (broad-exception-caught) - W1202: Use lazy % formatting in logging functions (logging-format-interpolation) - W1203: Use lazy % formatting in logging functions (logging-fstring-interpolation) - W1308: Duplicate string formatting argument 'connection_type', consider passing as named argument (duplicate-string-formatting-argument) - W1401: Anomalous backslash in string: '\/'. String constant might be missing an r prefix. (anomalous-backslash-in-string) - W1406: The u prefix for strings is no longer necessary in Python >=3.0 (redundant-u-string-prefix) - W1514: Using open without explicitly specifying an encoding (unspecified-encoding) - W4901: Deprecated module 'optparse' (deprecated-module) - W4904: Using deprecated class SafeConfigParser of module configparser (deprecated-class)
2024-06-07 11:43:43 +03:00
with open(f, encoding='utf-8') as fp:
print(f'Processing {f}')
msg_descr = None
msg_id = None
msg_text = None
for line in fp.readlines():
line = line.strip()
if not line or line.startswith('#'):
pass
elif line.startswith('//'):
pass
elif line.startswith('$'):
pass
elif line.startswith('%'):
# end previous message
if msg_id is not None:
section = msg_id.split('_')[0]
messages[msg_id] = (section, msg_id, msg_text, msg_descr)
# start next message
[#3287] fix pycodestyle warnings - E111 indentation is not a multiple of 4 - E117 over-indented - E125 continuation line with same indent as next logical line - E127 continuation line over-indented for visual indent - E128 continuation line under-indented for visual indent - E129 visually indented line with same indent as next logical line - E131 continuation line unaligned for hanging indent - E201 whitespace after '[' - E201 whitespace after '{' - E202 whitespace before ')' - E202 whitespace before ']' - E202 whitespace before '}' - E203 whitespace before ' - E203 whitespace before ',' - E222 multiple spaces after operator - E225 missing whitespace around operator - E228 missing whitespace around modulo operator - E231 missing whitespace after ',' - E251 unexpected spaces around keyword / parameter equals - E261 at least two spaces before inline comment - E262 inline comment should start with '# ' - E265 block comment should start with '# ' - E301 expected 1 blank line, found 0 - E302 expected 2 blank lines, found 1 - E303 too many blank lines (2) - E305 expected 2 blank lines after class or function definition, found 1 - E306 expected 1 blank line before a nested definition, found 0 - E401 multiple imports on one line - E402 module level import not at top of file - E501 line too long - E502 the backslash is redundant between brackets - E703 statement ends with a semicolon - E713 test for membership should be 'not in' - E722 do not use bare 'except' - E741 ambiguous variable name 'l' - W605 invalid escape sequence '\/'
2024-06-06 15:41:10 +03:00
m = re.search(r'^%\s?([A-Z0-9_]+)\s+(.*)', line)
msg_id, msg_text = m.groups()
msg_descr = []
else:
msg_descr.append(line)
if msg_id is not None:
2025-05-27 10:38:19 +00:00
section = msg_id.split('_')[0]
messages[msg_id] = (section, msg_id, msg_text, msg_descr)
return messages
def generate_rst(messages):
rst = '..\n'
rst += ' File generated by "doc/sphinx/mes2doc.py" or by "meson compile mes-doc". Do not edit by hand.\n\n'
rst += '''.. _kea-messages:
2021-03-19 20:57:49 +02:00
###################
Kea Messages Manual
###################
Kea is an open source implementation of the Dynamic Host Configuration
Protocol (DHCP) servers, developed and maintained by Internet Systems
Consortium (ISC).
This is the reference guide for Kea version |release|.
Links to the most up-to-date version of this document (in PDF, HTML,
and plain text formats), along with other useful information about
2021-07-16 14:34:18 +03:00
Kea, can be found in ISC's `Knowledgebase <https://kea.readthedocs.io>`_.
Please note that in the messages below, the percent sign (``%``) followed by a number is
used to indicate a placeholder for data that is provided by the Kea code during its operation.
.. toctree::
:numbered:
:maxdepth: 5
'''
prev_section = None
for _, msg in sorted(messages.items()):
section, msg_id, msg_text, msg_descr = msg
if section != prev_section:
prev_section = section
rst += '*' * len(section) + '\n'
rst += section + '\n'
rst += '*' * len(section) + '\n'
rst += '\n'
rst += msg_id + '\n'
rst += '=' * len(msg_id) + '\n'
rst += '\n'
rst += '.. code-block:: text\n'
rst += '\n'
rst += ' ' + msg_text + '\n'
rst += '\n'
rst += ''.join([line + '\n' for line in msg_descr])
rst += '\n'
rst += '''.. _kea-debug-messages:
*******************************
Kea Debug Messages By Log Level
*******************************
'''
rst += '.. include:: debug-messages.rst'
rst += '\n'
return rst
[#3287] fix pycodestyle warnings - E111 indentation is not a multiple of 4 - E117 over-indented - E125 continuation line with same indent as next logical line - E127 continuation line over-indented for visual indent - E128 continuation line under-indented for visual indent - E129 visually indented line with same indent as next logical line - E131 continuation line unaligned for hanging indent - E201 whitespace after '[' - E201 whitespace after '{' - E202 whitespace before ')' - E202 whitespace before ']' - E202 whitespace before '}' - E203 whitespace before ' - E203 whitespace before ',' - E222 multiple spaces after operator - E225 missing whitespace around operator - E228 missing whitespace around modulo operator - E231 missing whitespace after ',' - E251 unexpected spaces around keyword / parameter equals - E261 at least two spaces before inline comment - E262 inline comment should start with '# ' - E265 block comment should start with '# ' - E301 expected 1 blank line, found 0 - E302 expected 2 blank lines, found 1 - E303 too many blank lines (2) - E305 expected 2 blank lines after class or function definition, found 1 - E306 expected 1 blank line before a nested definition, found 0 - E401 multiple imports on one line - E402 module level import not at top of file - E501 line too long - E502 the backslash is redundant between brackets - E703 statement ends with a semicolon - E713 test for membership should be 'not in' - E722 do not use bare 'except' - E741 ambiguous variable name 'l' - W605 invalid escape sequence '\/'
2024-06-06 15:41:10 +03:00
def generate(in_files, out_file):
messages = read_input_files(in_files)
rst = generate_rst(messages)
if out_file:
[#3287] fix pylint warnings - C0115: Missing class docstring (missing-class-docstring) - C0123: Use isinstance() rather than type() for a typecheck. (unidiomatic-typecheck) - C0201: Consider iterating the dictionary directly instead of calling .keys() (consider-iterating-dictionary) - C0206: Consider iterating with .items() (consider-using-dict-items) - C0411: standard import "..." should be placed before "..." (wrong-import-order) - C0415: Import outside toplevel (...) (import-outside-toplevel) - C1802: Do not use `len(SEQUENCE)` without comparison to determine if a sequence is empty (use-implicit-booleaness-not-len) - E0001: Parsing failed: 'invalid syntax (<unknown>, line 2313)' (syntax-error) - E0401: Unable to import '...' (import-error) - E0602: Undefined variable 'l' (undefined-variable) - R0205: Class 'VagrantEnv' inherits from object, can be safely removed from bases in python3 (useless-object-inheritance) - E1101: Instance of 'NSECBASE' has no 'dump_fixedpart' member (no-member) - E1123: Unexpected keyword argument 'capture' in method call (unexpected-keyword-arg) - R0902: Too many instance attributes (too-many-instance-attributes) - R0913: Too many arguments (too-many-arguments) - R0916: Too many boolean expressions in if statement (6/5) (too-many-boolean-expressions) - R1717: Consider using a dictionary comprehension (consider-using-dict-comprehension) - R1722: Consider using 'sys.exit' instead (consider-using-sys-exit) - R1732: Consider using 'with' for resource-allocating operations (consider-using-with) - R1735: Consider using '{}' instead of a call to 'dict'. (use-dict-literal) - W0102: Dangerous default value sys.argv[1:] (builtins.list) as argument (dangerous-default-value) - W0102: Dangerous default value {} as argument (dangerous-default-value) - W0106: Expression "[f.write('%02x' % x) for x in bin_address]" is assigned to nothing (expression-not-assigned) - W0107: Unnecessary pass statement (unnecessary-pass) - W0201: Attribute 'config' defined outside __init__ (attribute-defined-outside-init) - W0404: Reimport '...' (imported line ...) (reimported) - W0611: Unused import ... (unused-import) - W0612: Unused variable '...' (unused-variable) - W0613: Unused argument '...' (unused-argument) - W0621: Redefining name '...' from outer scope (line 1471) (redefined-outer-name) - W0622: Redefining built-in '...' (redefined-builtin) - W0707: Consider explicitly re-raising using 'raise ... from ...' (raise-missing-from) - W0718: Catching too general exception Exception (broad-exception-caught) - W1202: Use lazy % formatting in logging functions (logging-format-interpolation) - W1203: Use lazy % formatting in logging functions (logging-fstring-interpolation) - W1308: Duplicate string formatting argument 'connection_type', consider passing as named argument (duplicate-string-formatting-argument) - W1401: Anomalous backslash in string: '\/'. String constant might be missing an r prefix. (anomalous-backslash-in-string) - W1406: The u prefix for strings is no longer necessary in Python >=3.0 (redundant-u-string-prefix) - W1514: Using open without explicitly specifying an encoding (unspecified-encoding) - W4901: Deprecated module 'optparse' (deprecated-module) - W4904: Using deprecated class SafeConfigParser of module configparser (deprecated-class)
2024-06-07 11:43:43 +03:00
with open(out_file, 'w', encoding='utf-8') as f:
f.write(rst)
print('Wrote generated RST content to: %s' % out_file)
else:
print(rst)
def main():
args = parse_args()
if args.files is None:
parent_dir = os.path.dirname(os.path.realpath(os.path.abspath(sys.argv[0])))
mes_files = sorted(pathlib.Path(f'{parent_dir}/../..').glob('**/*.mes'))
# Convert from Path to str.
mes_files = [str(i) for i in mes_files]
else:
mes_files = args.files
generate(mes_files, args.output)
if __name__ == '__main__':
main()