Add function to help parsing .ini files

Change-Id: I4bb4341414ba031741f51b3912cafdc9804ff18d
This commit is contained in:
Federico Ressi 2022-06-14 09:43:12 +02:00
parent b1ffb9b182
commit 13d7ba66cc
2 changed files with 40 additions and 0 deletions

View File

@ -22,6 +22,7 @@ from tobiko.common import _deprecation
from tobiko.common import _detail
from tobiko.common import _exception
from tobiko.common import _fixture
from tobiko.common import _ini
from tobiko.common import _loader
from tobiko.common import _logging
from tobiko.common import _operation
@ -82,6 +83,8 @@ SharedFixture = _fixture.SharedFixture
FixtureManager = _fixture.FixtureManager
RequiredFixture = _fixture.RequiredFixture
parse_ini_file = _ini.parse_ini_file
CaptureLogFixture = _logging.CaptureLogFixture
load_object = _loader.load_object

37
tobiko/common/_ini.py Normal file
View File

@ -0,0 +1,37 @@
# Copyright 2022 Red Hat
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from __future__ import absolute_import
import typing
IniFileStreamType = typing.Union[str]
def parse_ini_file(text: str, section='DEFAULT') \
-> typing.Dict[typing.Tuple[str, str], typing.Any]:
content: typing.Dict[typing.Tuple[str, str], typing.Any] = {}
for line in text.splitlines():
line = line.rsplit('#', 1)[0] # Remove comments
line = line.strip() # strip whitespaces
if not line:
# skip empty line
continue
if line.startswith('['):
# parse section name
section = line[1:-1].strip()
continue
if '=' in line:
left, right = line.split('=', 1)
content[section, left.strip()] = right.strip()
return content