]> kaliko git repositories - python-musicpdaio.git/blob - mpdaio/utils.py
Partially implement protocol (AsyncIO POC)
[python-musicpdaio.git] / mpdaio / utils.py
1 # -*- coding: utf-8 -*-
2 # SPDX-FileCopyrightText: 2012-2024  kaliko <kaliko@azylum.org>
3 # SPDX-License-Identifier: LGPL-3.0-or-later
4
5 class Range:
6
7     def __init__(self, tpl):
8         self.tpl = tpl
9         self.lower = ''
10         self.upper = ''
11         self._check()
12
13     def __str__(self):
14         return f'{self.lower}:{self.upper}'
15
16     def __repr__(self):
17         return f'Range({self.tpl})'
18
19     def _check_element(self, item):
20         if item is None or item == '':
21             return ''
22         try:
23             return str(int(item))
24         except (TypeError, ValueError) as err:
25             raise CommandError(f'Not an integer: "{item}"') from err
26         return item
27
28     def _check(self):
29         if not isinstance(self.tpl, tuple):
30             raise CommandError('Wrong type, provide a tuple')
31         if len(self.tpl) == 0:
32             return
33         if len(self.tpl) == 1:
34             self.lower = self._check_element(self.tpl[0])
35             return
36         if len(self.tpl) != 2:
37             raise CommandError('Range wrong size (0, 1 or 2 allowed)')
38         self.lower = self._check_element(self.tpl[0])
39         self.upper = self._check_element(self.tpl[1])
40         if self.lower == '' and self.upper != '':
41             raise CommandError(f'Integer expected to start the range: {self.tpl}')
42         if self.upper.isdigit() and self.lower.isdigit():
43             if int(self.lower) > int(self.upper):
44                 raise CommandError(f'Wrong range: {self.lower} > {self.upper}')
45
46 def escape(text):
47     return text.replace("\\", "\\\\").replace('"', '\\"')