|
| 1 | +# |
| 2 | +# sambacc: a samba container configuration tool |
| 3 | +# Copyright (C) 2023 John Mulligan |
| 4 | +# |
| 5 | +# This program is free software: you can redistribute it and/or modify |
| 6 | +# it under the terms of the GNU General Public License as published by |
| 7 | +# the Free Software Foundation, either version 3 of the License, or |
| 8 | +# (at your option) any later version. |
| 9 | +# |
| 10 | +# This program is distributed in the hope that it will be useful, |
| 11 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | +# GNU General Public License for more details. |
| 14 | +# |
| 15 | +# You should have received a copy of the GNU General Public License |
| 16 | +# along with this program. If not, see <http://www.gnu.org/licenses/> |
| 17 | +# |
| 18 | + |
| 19 | +import typing |
| 20 | + |
| 21 | + |
| 22 | +class SchemeNotSupported(Exception): |
| 23 | + pass |
| 24 | + |
| 25 | + |
| 26 | +class Opener(typing.Protocol): |
| 27 | + """Protocol for a basic opener type that takes a path-ish or uri-ish |
| 28 | + string and tries to open it. |
| 29 | + """ |
| 30 | + |
| 31 | + def open(self, path_or_uri: str) -> typing.IO: |
| 32 | + ... # pragma: no cover |
| 33 | + |
| 34 | + |
| 35 | +class FallbackOpener: |
| 36 | + """FallbackOpener is used to open a path if a the string can not be |
| 37 | + opened as a URI/URL. |
| 38 | + """ |
| 39 | + |
| 40 | + def __init__( |
| 41 | + self, |
| 42 | + openers: list[Opener], |
| 43 | + open_fn: typing.Optional[typing.Callable[..., typing.IO]] = None, |
| 44 | + ) -> None: |
| 45 | + self._openers = openers |
| 46 | + self._open_fn = open_fn or open |
| 47 | + |
| 48 | + def open(self, path_or_uri: str) -> typing.IO: |
| 49 | + for opener in self._openers: |
| 50 | + try: |
| 51 | + return opener.open(path_or_uri) |
| 52 | + except SchemeNotSupported: |
| 53 | + pass |
| 54 | + return self._open(path_or_uri) |
| 55 | + |
| 56 | + def _open(self, path: str) -> typing.IO: |
| 57 | + return self._open_fn(path) |
0 commit comments