Skip to content

Commit 6f521b1

Browse files
authored
Release v2.0.0: Bump python version to 3.12 and small improvements (#27)
## v2.0.0 - 2024-10-11 ### What's Changed **full changelog**: https://github.com/obervinov/messages-package/compare/v1.0.4..v2.0.0 by @ obervinov #27 #### 💥 Breaking Changes * Bump python version to `3.12` #### 📚 Bug Fixes * #25 #### 🚀 Features * Bump workflows to `v2.0.0` * #26
1 parent c94d0f2 commit 6f521b1

File tree

11 files changed

+369
-84
lines changed

11 files changed

+369
-84
lines changed

.github/workflows/pr.yaml

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,14 +9,8 @@ on:
99
- '!main'
1010

1111
jobs:
12-
changelog:
13-
uses: obervinov/_templates/.github/workflows/[email protected]
14-
15-
pylint:
16-
uses: obervinov/_templates/.github/workflows/[email protected]
17-
18-
pytest:
19-
uses: obervinov/_templates/.github/workflows/[email protected]
12+
pr:
13+
uses: obervinov/_templates/.github/workflows/[email protected]
2014

2115
pyproject:
22-
uses: obervinov/_templates/.github/workflows/pyproject.yaml@v1.0.13
16+
uses: obervinov/_templates/.github/workflows/pyproject.yaml@v2.0.0

.github/workflows/release.yaml

Lines changed: 2 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -8,18 +8,5 @@ on:
88
- closed
99

1010
jobs:
11-
changelog:
12-
uses: obervinov/_templates/.github/workflows/[email protected]
13-
14-
pylint:
15-
uses: obervinov/_templates/.github/workflows/[email protected]
16-
17-
pytest:
18-
uses: obervinov/_templates/.github/workflows/[email protected]
19-
20-
pyproject:
21-
uses: obervinov/_templates/.github/workflows/[email protected]
22-
23-
create-release:
24-
uses: obervinov/_templates/.github/workflows/[email protected]
25-
needs: [changelog, pylint, pytest, pyproject]
11+
release:
12+
uses: obervinov/_templates/.github/workflows/[email protected]

CHANGELOG.md

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,18 @@ All notable changes to this project will be documented in this file.
33
The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/).
44

55

6+
## v2.0.0 - 2024-10-11
7+
### What's Changed
8+
**full changelog**: https://github.com/obervinov/messages-package/compare/v1.0.4..v2.0.0 by @ obervinov https://github.com/obervinov/messages-package/pull/27
9+
#### 💥 Breaking Changes
10+
* Bump python version to `3.12`
11+
#### 📚 Bug Fixes
12+
* [Fix invalid default path to messages.json ](https://github.com/obervinov/messages-package/issues/25)
13+
#### 🚀 Features
14+
* Bump workflows to `v2.0.0`
15+
* [Add additional exceptions for more informative errors](https://github.com/obervinov/messages-package/issues/26)
16+
17+
618
## v1.0.4 - 2024-02-04
719
### What's Changed
820
**full changelog**: https://github.com/obervinov/messages-package/compare/v1.0.3...v1.0.4 by @ obervinov https://github.com/obervinov/messages-package/pull/24

README.md

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,10 +12,6 @@
1212
## <img src="https://github.com/obervinov/_templates/blob/main/icons/book.png" width="25" title="about"> About this project
1313
This package helps to easily and quickly generate beautiful messages for telegram bots using templates described in json.
1414

15-
## <img src="https://github.com/obervinov/_templates/blob/main/icons/github-actions.png" width="25" title="github-actions"> GitHub Actions
16-
| Name | Version |
17-
| ------------------------ | ----------- |
18-
| GitHub Actions Templates | [v1.0.12](https://github.com/obervinov/_templates/tree/v1.0.12) |
1915

2016

2117
## <img src="https://github.com/obervinov/_templates/blob/main/icons/requirements.png" width="25" title="functions"> Supported functions
@@ -37,8 +33,8 @@ name = myproject"
3733
version = "1.0.0"
3834
3935
[tool.poetry.dependencies]
40-
python = "^3.10"
41-
messages = { git = "https://github.com/obervinov/messages-package.git", tag = "v1.0.3" }
36+
python = "^3.12"
37+
messages = { git = "https://github.com/obervinov/messages-package.git", tag = "v2.0.0" }
4238
4339
[build-system]
4440
requires = ["poetry-core"]
@@ -125,3 +121,8 @@ _output result_
125121
🏞 Messages from the queue have already been processed
126122
[◾◾◾◾◾◾◾◾◾◾◾◾◾◾◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️◻️]19%
127123
```
124+
125+
## <img src="https://github.com/obervinov/_templates/blob/main/icons/github-actions.png" width="25" title="github-actions"> GitHub Actions
126+
| Name | Version |
127+
| ------------------------ | ----------- |
128+
| GitHub Actions Templates | [v2.0.0](https://github.com/obervinov/_templates/tree/v2.0.0) |

SECURITY.md

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,9 @@ Versions supported to fix vulnerabilities
66

77
| Version | Supported |
88
| ------- | ------------------ |
9-
| 1.0.x | :white_check_mark: |
9+
| 2.x.x | :white_check_mark: |
10+
| 1.x.x | :x: |
1011

1112
## Reporting a Vulnerability
1213

13-
In order to inform me about the vulnerability, write the details to the mail `github.obervinov@proton.me`
14+
In order to inform me about the vulnerability, just create an issue: https://github.com/obervinov/messages-package/security/advisories/new

messages/__init__.py

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,5 +3,12 @@
33
No need to add anything here. Feel free to delete this line when you make your own package
44
Leave it empty
55
"""
6-
# flake8: noqa
7-
from .messages import *
6+
from .messages import Messages
7+
from .exceptions import ConfigurationIsNotValid, TemplateNotFound, TemplatesIsNotValid
8+
9+
__all__ = [
10+
'Messages',
11+
'ConfigurationIsNotValid',
12+
'TemplateNotFound',
13+
'TemplatesIsNotValid'
14+
]

messages/configs/messages.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
{"templates": {}}

messages/exceptions.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""
2+
This module contains custom exceptions that are used in the application.
3+
"""
4+
5+
6+
class ConfigurationIsNotValid(Exception):
7+
"""
8+
Exception raised when the configuration file is not valid JSON.
9+
"""
10+
def __init__(self, message):
11+
self.message = message
12+
super().__init__(self.message)
13+
14+
15+
class TemplateNotFound(Exception):
16+
"""
17+
Exception raised when the template is not found in the configuration file.
18+
"""
19+
def __init__(self, message):
20+
self.message = message
21+
super().__init__(self.message)
22+
23+
24+
class TemplatesIsNotValid(Exception):
25+
"""
26+
Exception raised when the templates is not valid.
27+
"""
28+
def __init__(self, message):
29+
self.message = message
30+
super().__init__(self.message)

messages/messages.py

Lines changed: 76 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -1,69 +1,106 @@
1-
"""
2-
This module contains classes and methods
3-
for assembling and sending telegram messages to the bot.
4-
"""
1+
"""This module contains classes and methods for assembling and sending telegram messages to the bot."""
52
import os
63
import json
74
import math
85
import re
9-
from typing import Union
106
import emoji
7+
from .exceptions import ConfigurationIsNotValid, TemplateNotFound, TemplatesIsNotValid
118

129

1310
class Messages:
1411
"""
15-
This class contains methods
16-
for assembling and sending telegram messages to the bot.
12+
This class contains methods for assembling and sending telegram messages to the bot.
13+
14+
Attributes:
15+
configuration (dict): the contents of the configuration file.
16+
17+
Exceptions:
18+
ConfigurationIsNotValid: raised when the configuration file is not valid JSON.
19+
TemplateNotFound: raised when the template is not found in the configuration file.
20+
TemplatesIsNotValid: raised when the templates is not valid.
21+
22+
Examples:
23+
>>> from messages import Messages
24+
>>> messages = Messages('configs/messages.json')
25+
>>> messages.render_template('test_message', username='pytest')
1726
"""
1827

19-
def __init__(
20-
self,
21-
config_path: str = None
22-
) -> None:
28+
def __init__(self, config_path: str = 'configs/messages.json') -> None:
2329
"""
2430
Method for create a new messages instance.
2531
2632
Args:
2733
config (str): the path as a file containing a dictionary with message templates.
34+
"""
35+
env_variable = os.environ.get("MESSAGES_CONFIG", None)
2836

29-
Returns:
30-
None
37+
if env_variable:
38+
config_file = env_variable
39+
else:
40+
config_file = config_path
3141

32-
Examples:
33-
>>> from messages import Messages
34-
>>> messages = Messages('configs/messages.json')
42+
self.configuration = self._read_configuration(config_file=config_file)
43+
44+
if not self._templates_is_valid():
45+
raise TemplatesIsNotValid(
46+
"Templates have invalid elements. Please check your configuration file. "
47+
"Otherwise, check examples: https://github.com/obervinov/messages-package?tab=readme-ov-file#-usage-examples"
48+
)
49+
50+
def _read_configuration(self, config_file: str = None) -> dict:
3551
"""
36-
if os.environ.get("MESSAGES_CONFIG", None) is not None:
37-
self.config_path = os.environ.get("MESSAGES_CONFIG", None)
38-
elif config_path:
39-
self.config_path = config_path
40-
else:
41-
self.config_path = 'configs/messages.json'
52+
Method for checking the validity of the configuration file and reading its contents.
53+
54+
Args:
55+
config_file (str): the path as a file containing a dictionary with message templates.
4256
43-
if os.path.exists(self.config_path):
44-
with open(self.config_path, 'r', encoding='UTF-8') as config_json:
57+
Returns:
58+
dict: the contents of the configuration file.
59+
"""
60+
if os.path.exists(config_file):
61+
with open(config_file, 'r', encoding='UTF-8') as config_json:
4562
try:
46-
self.data = json.load(config_json)
47-
config_json.close()
63+
return json.load(config_json)
4864
except json.JSONDecodeError as json_error:
49-
# pylint: disable=no-value-for-parameter
50-
raise json.JSONDecodeError(
51-
f"Configuration file {self.config_path} is not valid JSON: {json_error}\n"
65+
raise ConfigurationIsNotValid(
66+
"Configuration file structure is not valid JSON. Please check examples: "
5267
"https://github.com/obervinov/messages-package?tab=readme-ov-file#-usage-examples"
53-
)
68+
) from json_error
5469
else:
55-
raise FileNotFoundError(f"Configuration file not found: {self.config_path}")
70+
raise FileNotFoundError(f"Configuration file not found: {config_file}")
71+
72+
def _templates_is_valid(self) -> bool:
73+
"""
74+
Method for checking the validity of the templates in the configuration file.
75+
76+
Returns:
77+
bool: True if the templates are valid, False otherwise.
78+
"""
79+
if 'templates' in self.configuration:
80+
for template in self.configuration['templates'].values():
81+
if 'text' not in template or 'args' not in template:
82+
print(f"[Messages]: there are no text or args in template {template}")
83+
return False
84+
if not isinstance(template['text'], str) or not isinstance(template['args'], list):
85+
print(f"[Messages]: text or args in template {template} has an invalid data type")
86+
return False
87+
args_provided = len(template['args'])
88+
args_expected = len(re.findall(r"{.*?}", template['text']))
89+
if args_provided != args_expected:
90+
print(f"[Messages]: the number of arguments in the template {template} does nots match")
91+
return False
92+
return True
5693

5794
def render_template(
5895
self,
5996
template_alias: str = None,
6097
**kwargs
61-
) -> Union[str, None]:
98+
) -> str | None:
6299
"""
63100
Method for reading the text from the configuration file.
64101
65102
Args:
66-
template_alias (str): the name of the template key for extracting text from conifg.
103+
template_alias (str): the name of the template key for extracting text from config.
67104
68105
Keyword Args:
69106
**kwargs: passing additional parameters for message assembly.
@@ -78,7 +115,7 @@ def render_template(
78115
>>> messages.render_template('test_message', username='pytest')
79116
"""
80117
try:
81-
template = self.data['templates'][template_alias]
118+
template = self.configuration['templates'][template_alias]
82119
arguments = []
83120
for arg in template['args']:
84121
if re.match(r":.*:", arg):
@@ -89,15 +126,17 @@ def render_template(
89126
arguments.append(kwargs.get(arg))
90127
# Building full message
91128
return template['text'].format(*arguments)
92-
except KeyError:
129+
except KeyError as error:
93130
print(f"[Messages]: template not found: {template_alias}")
94-
return None
131+
raise TemplateNotFound(
132+
"Template not found in the configuration file. Please check your configuration file."
133+
) from error
95134

96135
def render_progressbar(
97136
self,
98137
total_count: int = 0,
99138
current_count: int = 0
100-
) -> Union[str, None]:
139+
) -> str | None:
101140
"""
102141
A Method for generating string with a progress bar based
103142
on the transmitted statistics data.

0 commit comments

Comments
 (0)