Skip to content

Commit 3f74663

Browse files
committed
feat(common): improve config
1 parent 098613b commit 3f74663

File tree

5 files changed

+90
-45
lines changed

5 files changed

+90
-45
lines changed

package.py

Lines changed: 18 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -5,21 +5,26 @@
55
import zipapp
66

77

8-
def archiver() -> None:
9-
def archive_filter(path: Path):
10-
return path in map(Path, [
11-
'archiver.py',
12-
'common.py'
13-
])
8+
def _create_archive(name: str, files: list[str]) -> None:
9+
def file_filter(path: Path):
10+
return path in map(Path, files)
1411

1512
zipapp.create_archive(
16-
source='scripts',
17-
target='archiver.pyz',
18-
interpreter='/usr/bin/env python3',
19-
main='archiver:main',
20-
filter=archive_filter
13+
source="scripts",
14+
target=f"{name}.pyz",
15+
interpreter="/usr/bin/env python3",
16+
main=f"{name}:main",
17+
filter=file_filter,
2118
)
2219

2320

24-
if __name__ == '__main__':
25-
globals()[sys.argv[1]]()
21+
def archiver() -> None:
22+
_create_archive("archiver", ["archiver.py", "common.py"])
23+
24+
25+
if __name__ == "__main__":
26+
if len(sys.argv) > 1:
27+
globals()[sys.argv[1]]()
28+
else:
29+
# TODO Make generic # pylint: disable=fixme
30+
archiver()

scripts/archiver.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,7 +110,7 @@ def _create_argument_parser() -> ArgumentParser:
110110

111111
parent_parser = ArgumentParser(add_help=False)
112112
parent_parser.add_argument('-p', '--password', type=str, help='password')
113-
parent_parser.add_argument('-v', '--verbose', type=str, help='verbose')
113+
parent_parser.add_argument('-v', '--verbose', action='store_true', help='verbose')
114114

115115
a_parser = subparsers.add_parser(
116116
'a', parents=[parent_parser], help='create archive')

scripts/common.py

Lines changed: 47 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,33 +1,64 @@
11
#!/usr/bin/env python3
22

33
import json
4+
import logging
45
import os
56
from typing import Any
67

78

89
class Config: # pylint: disable=too-few-public-methods
9-
_HOME = os.path.expanduser('~')
10-
_XDG_CONFIG_HOME = os.environ.get('XDG_CONFIG_HOME') or \
11-
os.path.join(_HOME, '.config')
12-
_CONFIG_PATH = os.path.join(_XDG_CONFIG_HOME, 'scripts')
10+
_HOME = os.path.expanduser("~")
11+
_XDG_CONFIG_HOME = os.environ.get("XDG_CONFIG_HOME") or os.path.join(
12+
_HOME, ".config"
13+
)
14+
_CONFIG_PATH = os.path.join(_XDG_CONFIG_HOME, "scripts")
1315

1416
def __init__(self, config_file: str):
15-
self._config_file = config_file
16-
self._config = None
17+
self._config: dict[str, Any] | None = None
18+
if os.path.isfile(config_file):
19+
self._config_file = config_file
20+
elif os.path.isfile(os.path.join(self._CONFIG_PATH, config_file)):
21+
self._config_file = os.path.join(self._CONFIG_PATH, config_file)
22+
else:
23+
self._config_file = None
1724

18-
def get_value(self, key: str) -> Any | None:
25+
def get_config(self) -> dict[str, Any]:
1926
if self._config is None:
2027
self._config = self._read_config()
21-
if key in self._config:
22-
return self._config[key]
23-
return None
28+
return self._config
29+
30+
def set_config(self, config: dict[str, Any]) -> None:
31+
self._config = config
32+
with open(self._config_file, "w", encoding="utf-8") as file:
33+
return json.dump(config, file)
34+
35+
def get_value(self, key: str) -> Any | None:
36+
return self.get_config().get(key, None)
2437

2538
def _read_config(self) -> dict[str, Any]:
26-
if os.path.isfile(self._config_file):
27-
config_path = self._config_file
28-
elif os.path.isfile(os.path.join(self._CONFIG_PATH, self._config_file)):
29-
config_path = os.path.join(self._CONFIG_PATH, self._config_file)
39+
if self._config_file:
40+
with open(self._config_file, "r", encoding="utf-8") as file:
41+
return json.load(file)
3042
else:
3143
return {}
32-
with open(config_path, 'r', encoding='utf-8') as config:
33-
return json.load(config)
44+
45+
46+
class Logger:
47+
def __init__(self) -> None:
48+
logging.basicConfig(level=logging.INFO, format="%(message)s")
49+
self._logger = logging.getLogger("scripts")
50+
51+
def verbose(self):
52+
self._logger.setLevel(logging.DEBUG)
53+
54+
def debug(self, msg, *args, **kwargs) -> None:
55+
self._logger.debug(msg, *args, **kwargs)
56+
57+
def info(self, msg, *args, **kwargs) -> None:
58+
self._logger.info(msg, *args, **kwargs)
59+
60+
def warning(self, msg, *args, **kwargs) -> None:
61+
self._logger.warning(msg, *args, **kwargs)
62+
63+
def error(self, msg, *args, **kwargs) -> None:
64+
self._logger.error(msg, *args, **kwargs)

tests/test_archiver.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,7 @@ def test_archiving_with_config():
3939
with open(f"{TEST_PATH}/archiver.json", 'w', encoding='utf-8') as file:
4040
json.dump({'defaultPassword': 'test'}, file)
4141

42-
config = Config('archiver.json')
43-
config._CONFIG_PATH = os.path.join( # pylint: disable=protected-access
44-
os.getcwd(), TEST_PATH)
42+
config = Config(f"{TEST_PATH}/archiver.json")
4543

4644
archiver = Archiver()
4745
archiver._config = config # pylint: disable=protected-access

tests/test_common.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,38 @@
77
from scripts.common import Config
88

99

10-
TEST_PATH = './out'
11-
TARGET_DIR = f"{TEST_PATH}/test"
12-
TEST_ARCHIVE = f"{TEST_PATH}/test.7z"
13-
PASSWORD = 'test'
10+
TEST_PATH = "./out"
11+
TARGET_DIR = f"{TEST_PATH}/scripts"
12+
PASSWORD = "test"
1413

1514

1615
@pytest.fixture(autouse=True)
1716
def prepare():
1817
if os.path.exists(TEST_PATH):
1918
shutil.rmtree(TEST_PATH)
20-
Path(TEST_PATH).mkdir(parents=True, exist_ok=True)
19+
Path(TARGET_DIR).mkdir(parents=True, exist_ok=True)
2120

2221

2322
def test_config():
24-
with open(f"{TEST_PATH}/test.json", 'w', encoding='utf-8') as config:
25-
json.dump({'testKey': 'testValue'}, config)
23+
with open(f"{TEST_PATH}/test.json", "w", encoding="utf-8") as file:
24+
json.dump({"testKey": "testValue"}, file)
2625

27-
config = Config('test.json')
28-
config._CONFIG_PATH = os.path.join( # pylint: disable=protected-access
29-
os.getcwd(), TEST_PATH)
26+
config = Config(f"{TEST_PATH}/test.json")
3027

31-
value = config.get_value('testKey')
28+
value = config.get_value("testKey")
3229

33-
assert value == 'testValue'
30+
assert value == "testValue"
31+
32+
33+
@pytest.mark.skip(reason="Static variables are initialized on import")
34+
def test_config_with_config_home(monkeypatch: pytest.MonkeyPatch):
35+
monkeypatch.setenv("XDG_CONFIG_HOME", TEST_PATH)
36+
37+
with open(f"{TARGET_DIR}/test.json", "w", encoding="utf-8") as file:
38+
json.dump({"testKey": "testValue"}, file)
39+
40+
config = Config("test.json")
41+
42+
value = config.get_value("testKey")
43+
44+
assert value == "testValue"

0 commit comments

Comments
 (0)