]> kaliko git repositories - python-musicpdaio.git/blobdiff - mpdaio/utils.py
Partially implement protocol (AsyncIO POC)
[python-musicpdaio.git] / mpdaio / utils.py
diff --git a/mpdaio/utils.py b/mpdaio/utils.py
new file mode 100644 (file)
index 0000000..1d01db5
--- /dev/null
@@ -0,0 +1,47 @@
+# -*- coding: utf-8 -*-
+# SPDX-FileCopyrightText: 2012-2024  kaliko <kaliko@azylum.org>
+# SPDX-License-Identifier: LGPL-3.0-or-later
+
+class Range:
+
+    def __init__(self, tpl):
+        self.tpl = tpl
+        self.lower = ''
+        self.upper = ''
+        self._check()
+
+    def __str__(self):
+        return f'{self.lower}:{self.upper}'
+
+    def __repr__(self):
+        return f'Range({self.tpl})'
+
+    def _check_element(self, item):
+        if item is None or item == '':
+            return ''
+        try:
+            return str(int(item))
+        except (TypeError, ValueError) as err:
+            raise CommandError(f'Not an integer: "{item}"') from err
+        return item
+
+    def _check(self):
+        if not isinstance(self.tpl, tuple):
+            raise CommandError('Wrong type, provide a tuple')
+        if len(self.tpl) == 0:
+            return
+        if len(self.tpl) == 1:
+            self.lower = self._check_element(self.tpl[0])
+            return
+        if len(self.tpl) != 2:
+            raise CommandError('Range wrong size (0, 1 or 2 allowed)')
+        self.lower = self._check_element(self.tpl[0])
+        self.upper = self._check_element(self.tpl[1])
+        if self.lower == '' and self.upper != '':
+            raise CommandError(f'Integer expected to start the range: {self.tpl}')
+        if self.upper.isdigit() and self.lower.isdigit():
+            if int(self.lower) > int(self.upper):
+                raise CommandError(f'Wrong range: {self.lower} > {self.upper}')
+
+def escape(text):
+    return text.replace("\\", "\\\\").replace('"', '\\"')