|
| 1 | +import itertools |
| 2 | +import json |
| 3 | +import subprocess |
| 4 | + |
| 5 | + |
| 6 | +class XDGSettingsException(Exception): |
| 7 | + pass |
| 8 | + |
| 9 | + |
| 10 | +class Settings(object): |
| 11 | + @classmethod |
| 12 | + def get(cls, key, subkey=None): |
| 13 | + args = [key] |
| 14 | + if subkey is not None: |
| 15 | + args.append(subkey) |
| 16 | + |
| 17 | + stdout = subprocess.check_output(["/opt/bin/xdg-settings", "get"] + args) |
| 18 | + if stdout: |
| 19 | + return json.loads(stdout) |
| 20 | + |
| 21 | + return None |
| 22 | + |
| 23 | + @classmethod |
| 24 | + def set(cls, key: tuple[str] | str, val): |
| 25 | + if isinstance(key, str): |
| 26 | + args = [key] |
| 27 | + elif isinstance(key, tuple[str]): |
| 28 | + args = list(key) |
| 29 | + else: |
| 30 | + raise ValueError() |
| 31 | + |
| 32 | + args.append(val) |
| 33 | + stdout = subprocess.check_output(["/opt/bin/xdg-settings", "set"] + args) |
| 34 | + if stdout: |
| 35 | + return json.loads(stdout) |
| 36 | + |
| 37 | + return None |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def keys(cls) -> tuple[str]: |
| 41 | + stdout = subprocess.check_output(["/opt/bin/xdg-settings", "--list"]) |
| 42 | + lines = stdout.decode("utf-8").rstrip().split("\n") |
| 43 | + res = [] |
| 44 | + if lines.pop(0) != "Known properties:": |
| 45 | + raise XDGSettingsException("Unknown xdg-settings output") |
| 46 | + |
| 47 | + peeker, lines = itertools.tee(lines) |
| 48 | + next(peeker) |
| 49 | + category = None |
| 50 | + for line in lines: |
| 51 | + key = line.lstrip().split(" ")[0] |
| 52 | + next_line = next(peeker, None) |
| 53 | + eof = next_line is None |
| 54 | + next_is_indented = not eof and next_line.startswith(" ") |
| 55 | + is_indented = line.startswith(" ") |
| 56 | + if category is not None and not is_indented: |
| 57 | + category = None |
| 58 | + |
| 59 | + if not is_indented and next_is_indented: |
| 60 | + category = key |
| 61 | + continue |
| 62 | + |
| 63 | + if category is None and not is_indented and (eof or not next_is_indented): |
| 64 | + res.append((key, None)) |
| 65 | + continue |
| 66 | + |
| 67 | + if category is not None and is_indented: |
| 68 | + res.append((category, key)) |
| 69 | + continue |
| 70 | + |
| 71 | + raise XDGSettingsException( |
| 72 | + "Unable to parse xdg-settings --list output\n" |
| 73 | + f" Current line: {line}\n" |
| 74 | + f" Line indented: {is_indented}\n" |
| 75 | + f" Next line indented: {next_is_indented}\n" |
| 76 | + f" Category: {category}" |
| 77 | + ) |
| 78 | + |
| 79 | + return res |
| 80 | + |
| 81 | + @classmethod |
| 82 | + def items(cls): |
| 83 | + for key in cls.keys(): |
| 84 | + yield (key, cls.get(*key)) |
| 85 | + |
| 86 | + @classmethod |
| 87 | + def values(cls): |
| 88 | + for key in cls.keys(): |
| 89 | + yield cls.get(*key) |
0 commit comments