Source code for libka.ironhand.ka_iron_hand_conf
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# pylint: disable=line-too-long
# kate: space-indent on; indent-width 4; replace-tabs on; indent-mode python; remove-trailing-space modified;
# pylint: enable=line-too-long
# vim: expandtab ts=4
############################################################################
# Copyright © 2015-2020 José Manuel Santamaría Lema <panfaust@gmail.com> #
# #
# 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; either version 2 of the License, or #
# (at your option) any later version. #
############################################################################
"""
This module just provides the get_ka_iron_hand_config_parser() function.
"""
import os
import configparser
# pylint: disable=protected-access
[docs]
def get_ka_iron_hand_config_parser(create_template=False):
"""
Returns a config parser with the ka-iron-hand configuration.
"""
#If we already got the configuration just return the current parser
if hasattr(get_ka_iron_hand_config_parser, '_config'):
return get_ka_iron_hand_config_parser._config
#Init config parser
get_ka_iron_hand_config_parser._config = configparser.RawConfigParser(
inline_comment_prefixes=('#', ';'))
#Default config #1
cwd = os.path.dirname(os.path.realpath(__file__))
defaultconfig1 = os.path.join(cwd, '/../conf/ironhand_defaultrc')
get_ka_iron_hand_config_parser._config.read(defaultconfig1)
#Default config #2
defaultconfig2 = os.path.join(cwd, 'defaultconfig/ironhand_defaultrc')
get_ka_iron_hand_config_parser._config.read(defaultconfig2)
#Default config #3 - System wide /etc file
defaultconfig3 = os.path.join(cwd, '/etc/ka/ka-iron-hand.conf')
get_ka_iron_hand_config_parser._config.read(defaultconfig3)
#User config
userconfig = '~/.ka-iron-hand.conf'
userconfig = os.path.expanduser(userconfig)
get_ka_iron_hand_config_parser._config.read(userconfig)
#If the user config file doesn't exist, just dump a template there
if create_template:
if not os.path.exists(userconfig):
defaultconfig_file = ""
if os.path.exists(defaultconfig1):
defaultconfig_file = defaultconfig1
elif os.path.exists(defaultconfig2):
defaultconfig_file = defaultconfig2
if defaultconfig_file != "":
in_file = open(defaultconfig_file, 'r')
out_file = open(userconfig, 'w')
lines = in_file.readlines()
try: #Pop the first 2 lines
lines.pop(0)
lines.pop(0)
except: #pylint: disable=bare-except
pass
for line in lines:
if line.startswith('#') or line.startswith('[') or line.strip() == "":
out_file.write(line)
else:
out_file.write('#' + line)
in_file.close()
out_file.close()
#Return the config parser
return get_ka_iron_hand_config_parser._config
# pylint: enable=protected-access