azfilebackup/azfilebak/backupconfigurationfile.py

59 строки
2.3 KiB
Python
Исходник Обычный вид История

2018-09-03 19:11:17 +03:00
# coding=utf-8
2018-10-25 13:14:10 +03:00
# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
# --------------------------------------------------------------------------
2018-09-10 11:35:06 +03:00
"""BackupConfigurationFile module."""
2018-09-03 19:11:17 +03:00
import re
import os.path
from .backupexception import BackupException
2018-09-10 11:35:06 +03:00
class BackupConfigurationFile(object):
"""Parse the backup configuration file."""
2018-09-03 19:11:17 +03:00
def __init__(self, filename):
if not os.path.isfile(filename):
2018-09-10 11:35:06 +03:00
raise BackupException("Cannot find configuration file {}:".format(filename))
2018-09-03 19:11:17 +03:00
self.filename = filename
try:
2018-10-05 22:36:04 +03:00
BackupConfigurationFile.read_key_value_file(filename=self.filename)
2018-09-27 14:47:52 +03:00
#logging.debug("Configuration %s", str(vals))
2018-09-10 11:35:06 +03:00
except Exception as ex:
raise BackupException("Error parsing config file {}:\n{}".format(filename, ex.message))
2018-09-03 19:11:17 +03:00
def get_value(self, key):
2018-09-10 11:35:06 +03:00
""" Parse a configuration file and return a single value."""
2018-09-03 19:11:17 +03:00
values = BackupConfigurationFile.read_key_value_file(filename=self.filename)
return values[key]
2018-09-11 15:40:31 +03:00
def get_keys_prefix(self, prefix):
"""Retrieve all keys that match a certain prefix."""
values = BackupConfigurationFile.read_key_value_file(filename=self.filename)
return [i for i in values.keys() if re.match(prefix, i)]
2018-09-21 11:18:14 +03:00
def key_exists(self, key):
"""Return True if a key exists in the configuration file."""
values = BackupConfigurationFile.read_key_value_file(filename=self.filename)
return values.has_key(key)
2018-09-03 19:11:17 +03:00
@staticmethod
def read_key_value_file(filename):
"""
2018-09-10 11:35:06 +03:00
Parse a configuration file and return a dictionary of key/values.
2018-09-20 18:07:29 +03:00
>>> values = BackupConfigurationFile.read_key_value_file(filename="sample_backup.conf")
2018-09-13 16:00:53 +03:00
>>> values["local_temp_directory"]
'/tmp'
2018-09-03 19:11:17 +03:00
"""
2018-09-10 11:35:06 +03:00
with open(filename, mode='rt') as config_file:
lines = config_file.readlines()
2018-09-03 19:11:17 +03:00
# skip comments and empty lines
2018-09-10 11:35:06 +03:00
content_lines = [line for line in lines if not re.match(r"^\s*#|^\s*$", line)]
2018-09-21 11:47:25 +03:00
content = dict(re.split(":|=", line, maxsplit=1) for line in content_lines)
2018-09-20 18:07:29 +03:00
return dict([(x[0].strip(), x[1].strip().strip('\"')) for x in content.iteritems()])