项目作者: etingof

项目描述 :
Apache / Config::General configuration file parser
高级语言: Python
项目地址: git://github.com/etingof/apacheconfig.git
创建时间: 2018-03-10T12:00:23Z
项目社区:https://github.com/etingof/apacheconfig

开源协议:BSD 2-Clause "Simplified" License

下载


Apache-style config parser

PyPI
Python Versions
Build status
Coverage Status
GitHub license

This is a pure-Python implementation of Apache-like configuration file parser into Python built-in
types. Similar file format is utilized by Perl’s Config::General
module.

How to use apacheconfig

With apacheconfig you can build a tree of Python objects from Apache configuration
file.

For example, the following Apache configuration:

  1. <cops>
  2. name stein
  3. age 25
  4. <colors>
  5. color \#000000
  6. </colors>
  7. </cops>

Would be transformed by apacheconfig into:

  1. {
  2. 'cops': {
  3. 'name': 'stein',
  4. 'age': '25',
  5. 'colors': {
  6. 'color': '#000000'
  7. }
  8. }

By running the following code:

  1. from apacheconfig import *
  2. with make_loader() as loader:
  3. config = loader.load('httpd.conf')
  4. print(config)

You can also dump the config dict back into Apache configuration file form
by calling dump or dumps method:

  1. from apacheconfig import *
  2. with make_loader() as loader:
  3. config = loader.load('httpd.conf')
  4. # ...potentially modify the `config` dict anyhow...
  5. print(loader.dumps(config))

Please, note that dumped config file might differ in its representation from the original
because dict form does not contain all pieces of the original file (like comments),
some items may get modified on load (like variable expansion) and included files
rendered into the single dict.

Parsing options

Parser behavior can be modified by passing it one or more options. The options are passed as a dictionary:

  1. from apacheconfig import *
  2. options = {
  3. 'lowercasenames': True
  4. }
  5. with make_loader(**options) as loader:
  6. config = loader.load('httpd.conf')
  7. print(config)

The options are largely patterned after Perl’s Config::General module, documentation for the options is also
borrowed there.

The following options are currently supported:

allowmultioptions

If the value is False, then multiple identical options are disallowed. The default is True in which
case values of the identical options are collected into a list.

forcearray

You may force a single config line to get parsed into a list by turning on the option forcearray and by
surrounding the value of the config entry by [].

Example:

  1. hostlist = [foo.bar]

Will result in a single value array entry if the forcearray option is turned on.

lowercasenames

If set to True, then all options found in the config will be converted to lowercase. This allows you to
provide case-in-sensitive configs. The values of the options will not lowercased.

nostripvalues

If set to False, then each value found in the config will not be right-stripped. This allows you to gather the options as long as their trailing whitespaces.

useapacheinclude

If set to True, the parser will consider “include …” as valid include statement (just like the well known
Apache include statement).

It also supports apache’s “IncludeOptional” statement with the same behavior, that is, if the include file
doesn’t exist no error will be thrown.

includeagain

If set to True, you will be able to include a sub-configfile multiple times. With the default, False, duplicate
includes are silently ignored and only the first include will succeed.

Reincluding a configfile can be useful if it contains data that you want to be present in multiple places in the
data tree.

Note, however, that there is currently no check for include recursion.

includerelative

If set to True, included files with a relative path (i.e. “cfg/blah.conf”) will be opened from within the location
of the configfile instead from within the location of the script ($0). This works only if the configfile has a
absolute pathname (i.e. “/etc/main.conf”).

If the configpath option has been set and if the file to be included could not be found in the location relative
to the current config file, the module will search within configpath for the file.

includedirectories

If set to True, you may specify include a directory, in which case all files inside the directory will be loaded
in ASCII order. Directory includes will not recurse into subdirectories. This is comparable to including a directory
in Apache-style config files.

includeglob

If set to True, you may specify a glob pattern for an include to include all matching files
(e.g. <>).

An include option will not cause a parser error if the glob didn’t return anything.

configpath

You can use this variable to specify a search path for relative config files which have to be included.
The apacheconfig tool will search within this path for the file if it cannot find the file at the location
relative to the current config file.

To provide multiple search paths you can specify an array reference for the path. For example:

  1. options = {
  2. 'configpath': ['dira', 'dirb']
  3. }

mergeduplicateblocks

If set to True, then duplicate blocks, that means blocks and named blocks, will be merged into a single one
The default behavior is to create an array if some junk in a config appears more than once.

mergeduplicateoptions

If set to True, then duplicate options will be merged. That means, if the same option occurs more than once, the
last one will be used in the resulting config dictionary.

autotrue

If set to True, then options in your config file, whose values are set to true or false values, will be
normalised to 1 or 0 respectively.

The following values will be considered as true:

  • yes
  • on
  • 1
  • true

The following values will be considered as false:

  • no
  • off
  • 0
  • false

This effect is case-insensitive, i.e. both Yes or No will result in 1.

namedblocks

This option enables tag splitting by the first whitespace and turning the trailing
piece into a nested block. True by default.

flagbits

This option takes one required parameter, which must be a dictionary defining variables for which you want to preset
values. Each variable you have defined in this dictionary and which occurs in your config file, will cause this
variable being set to the preset values to which the value in the config file refers to.

Multiple flags can be used, separated by the pipe character |.

For example, this option:

  1. options = {
  2. 'flagbits': {
  3. 'mode': {
  4. 'CLEAR': '1',
  5. 'STRONG': '1',
  6. 'UNSECURE': '32bit'
  7. }
  8. }
  9. }

In this example we are defining a variable named mode which may contain one or more of CLEAR, STRONG and
UNSECURE as value.

The appropriate config entry may look like this:

  1. mode = CLEAR | UNSECURE

The parser will create a dictionary which will be the value of the key mode. This dictionary will contain all
flags which you have pre-defined, but only those which were set in the config will contain the pre-defined value,
the other ones will be undefined.

The resulting config structure would look like this after parsing:

  1. config = {
  2. 'mode': {
  3. 'CLEAR': '1',
  4. 'UNSECURE': '32bit',
  5. 'STRONG': None
  6. }
  7. }

This method allows the user to set multiple pre-defined values for one option.

Please beware, that all occurrences of those variables will be handled this way, there is no way to distinguish between
variables in different scopes. That means, if mode would also occur inside a named block, it would also parsed this
way.

Values which are not defined in the dictionary supplied to the parameter flagbits and used in the corresponding
variable in the config will be ignored.

defaultconfig

The value of this option should be a dictionary holding default options-values. This causes the module to populate
the resulting config dictionary with the given values, which allows you to set default values for particular config
options directly.

Note that you probably want to use this with mergeduplicateoptions, otherwise a default value already in the
configuration file will produce an array of two values.

interpolatevars

If set to True, variable interpolation will be done on your config input.

Variables can be defined everywhere in the config and can be used afterwards as the value of an option. Variables
cannot be used as keys or as part of keys.

If you define a variable inside a block or a named block then it is only visible within this block or within blocks
which are defined inside this block.

For example:

  1. # sample config which uses variables
  2. basedir = /opt/ora
  3. user = t_space
  4. sys = unix
  5. <table intern>
  6. instance = INTERN
  7. owner = $user # "t_space"
  8. logdir = $basedir/log # "/opt/ora/log"
  9. sys = macos
  10. <procs>
  11. misc1 = ${sys}_${instance} # macos_INTERN
  12. misc2 = $user # "t_space"
  13. </procs>
  14. </table>

This will result in the following structure:

  1. {
  2. 'basedir': '/opt/ora',
  3. 'user': 't_space'
  4. 'sys': 'unix',
  5. 'table': {
  6. 'intern': {
  7. 'sys': 'macos',
  8. 'logdir': '/opt/ora/log',
  9. 'instance': 'INTERN',
  10. 'owner': 't_space',
  11. 'procs': {
  12. 'misc1': 'macos_INTERN',
  13. 'misc2': 't_space'
  14. }
  15. }
  16. }
  17. }

As you can see, the variable sys has been defined twice. Inside the block a variable ${sys} has been
used, which then were interpolated into the value of sys defined inside the

block, not the sys variable
one level above. If sys were not defined inside the
block then the “global” variable sys would have
been used instead with the value of unix.

Variables inside double quotes will be interpolated, but variables inside single quotes will not interpolated unless
allowsinglequoteinterpolation option is set.

In addition you can surround variable names with curly braces to avoid misinterpretation by the parser.

interpolateenv

If set to True, environment variables can be referenced in configs, their values will be substituted in place of
their reference in the value.

This option enables interpolatevars.

allowsinglequoteinterpolation

By default variables inside single quotes will not be interpolated. If you turn on this option, they will be
interpolated as well.

strictvars

By default this is set to True, which causes parser to fail if an undefined variable with interpolatevars turned
on occurs in a config. Set to False to avoid such error messages.

ccomments

The parser will process C-style comments as well as hash-style comments. By default C-style comments are processed,
you can disable that by setting ccomments option to False.

noescape

If you want to preserve escaping special characters ($\”#) in the configuration data, turn this parameter on. It is
set to False by default.

preservewhitespace

When this option is enabled, the parser would collect insignificant whitespaces
into AST. This information could then be used for code generation. The default
is False.

multilinehashcomments

Escaped newlines at the end of hash comments add the following line to the comment. Apache’s native config parser processes hash comments this way. Set to False by default.

disableemptyelementtags

When this option is enabled, the parser does not recognize empty element tags
such as <block name></block>. The former, for instance, would be re-interpreted
as opening tag with tag name block, and argument name/.
The default is False.

Parser plugins

You can alter the behavior of the parser by supplying callables which will be invoked on certain hooks during
config file processing and parsing.

The general approach works like this:

  1. def pre_open_hook(file, base):
  2. print('trying to open %s... ' % file)
  3. if 'blah' in file:
  4. print('ignored')
  5. return False, file, base
  6. else:
  7. print('allowed')
  8. return True, file, base
  9. options = {
  10. 'plug': {
  11. 'pre_open': pre_open_hook
  12. }
  13. }

Output:

  1. trying to open cfg ... allowed
  2. trying to open x/*.conf ... allowed
  3. trying to open x/1.conf ... allowed
  4. trying to open x/2.conf ... allowed
  5. trying to open x/blah.conf ... ignored

As you can see, we wrote a little function which takes a filename and a base directory as parameters. We tell
the parser via the plug option to call this sub every time before it attempts to open a file.

General processing continues as usual if the first value of the returned array is True. The second value of that
tuple depends on the kind of hook being called.

The following hooks are available so far:

pre_open

Takes two parameters: filename and basedirectory.

Has to return a tuple consisting of 3 values:

  • True or False (continue processing or not)
  • filename
  • base directory

The returned basedirectory and filename will be used for opening the file.

pre_read

Takes two parameters: the source of the contents read from and a string containing the raw contents.
This hook gets the unaltered, original contents as it’s read from a file (or some other source).

Has to return an array of 3 values:

  • True or False (continue processing or not)
  • the source of the contents or None if loads() is invoked rather than load()
  • a string that replaces the read contents

You can use this hook to apply your own normalizations or whatever.

Command-line tool

The library comes with a simple command-line tool apacheconfigtool which can convert Apache-style
config files into JSON. The tool is also useful for playing with config file formats and parser
options.

  1. $ apacheconfigtool --help
  2. usage: apacheconfigtool [-h] [-v] [--json-input] [--allowmultioptions]
  3. [--forcearray] [--lowercasenames] [--nostripvalues]
  4. [--useapacheinclude] [--includeagain]
  5. [--includerelative] [--includedirectories]
  6. [--includeglob] [--mergeduplicateblocks]
  7. [--mergeduplicateoptions] [--namedblocks] [--autotrue]
  8. [--interpolatevars] [--interpolateenv]
  9. [--allowsinglequoteinterpolation] [--strictvars]
  10. [--noescape] [--ccomments]
  11. [--configpath CONFIGPATH] [--flagbits <JSON>]
  12. [--defaultconfig <JSON>]
  13. file [file ...]
  14. Dump Apache config files into JSON
  15. positional arguments:
  16. file Path to the configuration file to dump
  17. optional arguments:
  18. -h, --help show this help message and exit
  19. -v, --version show program's version number and exit
  20. --json-input Expect JSON file(s) on input, produce Apache
  21. configuration
  22. parsing options:
  23. --allowmultioptions Collect multiple identical options into a list
  24. --forcearray Force a single config line to get parsed into a list
  25. by turning on this option and by surrounding the value
  26. of the config entry by []
  27. --lowercasenames All options found in the config will be converted to
  28. lowercase
  29. --nostripvalues All values found in the config will not be right-
  30. stripped
  31. --useapacheinclude Consider "include ..." as valid include statement
  32. --includeagain Allow including sub-configfiles multiple times
  33. --includerelative Open included config files from within the location of
  34. the configfile instead from within the location of the
  35. script
  36. --includedirectories Include statement may point to a directory, in which
  37. case all files inside the directory will be loaded in
  38. ASCII order
  39. --includeglob Include statement may point to a glob pattern, in
  40. which case all files matching the pattern will be
  41. loaded in ASCII order
  42. --mergeduplicateblocks
  43. Duplicate blocks (blocks and named blocks), will be
  44. merged into a single one
  45. --mergeduplicateoptions
  46. If the same option occurs more than once, the last one
  47. will be used in the resulting config dictionary
  48. --namedblocks Do not split tags by the first whitespace and turn the
  49. trailing part into a nested block
  50. --autotrue Turn various forms of binary values in config into "1"
  51. and "0"
  52. --interpolatevars Enable variable interpolation
  53. --interpolateenv Enable process environment variable interpolation
  54. --allowsinglequoteinterpolation
  55. Perform variable interpolation even when being in
  56. single quotes
  57. --strictvars Do not fail on an undefined variable when performing
  58. interpolation
  59. --noescape Preserve special escape characters left outs in the
  60. configuration values
  61. --ccomments Do not parse C-style comments
  62. --configpath CONFIGPATH
  63. Search path for the configuration files being
  64. included. Can repeat.
  65. --flagbits <JSON> Named bits for an option in form of a JSON object of
  66. the following structure {"OPTION": {"NAME": "VALUE"}}
  67. --defaultconfig <JSON>
  68. Default values for parsed configuration in form of a
  69. JSON object
  70. $ apacheconfigtool --includedirectories include-directory-test.conf
  71. {
  72. "final_include": "true",
  73. "seen_first_config": "true",
  74. "seen_second_config": "true",
  75. "inner": {
  76. "final_include": "true",
  77. "seen_third_config": "true"
  78. },
  79. "seen_third_config": "true"
  80. }

How to get apacheconfig

The apacheconfig package is distributed under terms and conditions of 2-clause
BSD license. Source code is freely
available as a GitHub repo.

You could pip install apacheconfig or download it from PyPI.

If something does not work as expected,
open an issue at GitHub.

Copyright (c) 2018-2020, Ilya Etingof. All rights reserved.