summaryrefslogtreecommitdiffstats
path: root/tools/tryselect/preset.py
blob: dc8cba5c574ae0970a31dc5eba73ce7c7b3590a9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.


import os
import shlex
import subprocess

import yaml


# Ensure strings with ' like fzf query strings get double-quoted:
def represent_str(self, data):
    if "'" in data:
        return self.represent_scalar("tag:yaml.org,2002:str", data, style='"')
    return self.represent_scalar("tag:yaml.org,2002:str", data)


yaml.SafeDumper.add_representer(str, represent_str)


class PresetHandler:
    def __init__(self, path):
        self.path = path
        self._presets = {}

    @property
    def presets(self):
        if not self._presets and os.path.isfile(self.path):
            with open(self.path) as fh:
                self._presets = yaml.safe_load(fh) or {}

        return self._presets

    def __contains__(self, name):
        return name in self.presets

    def __getitem__(self, name):
        return self.presets[name]

    def __len__(self):
        return len(self.presets)

    def __str__(self):
        if not self.presets:
            return ""
        return yaml.safe_dump(self.presets, default_flow_style=False)

    def list(self):
        if not self.presets:
            print("no presets found")
        else:
            print(self)

    def edit(self):
        if "EDITOR" not in os.environ:
            print(
                "error: must set the $EDITOR environment variable to use --edit-presets"
            )
            return

        subprocess.call(shlex.split(os.environ["EDITOR"]) + [self.path])

    def save(self, name, **data):
        self.presets[name] = data

        with open(self.path, "w") as fh:
            fh.write(str(self))


class MergedHandler:
    def __init__(self, *paths):
        """Helper class for dealing with multiple preset files."""
        self.handlers = [PresetHandler(p) for p in paths]

    def __contains__(self, name):
        return any(name in handler for handler in self.handlers)

    def __getitem__(self, name):
        for handler in self.handlers:
            if name in handler:
                return handler[name]
        raise KeyError(name)

    def __len__(self):
        return sum(len(h) for h in self.handlers)

    def __str__(self):
        all_presets = {
            k: v for handler in self.handlers for k, v in handler.presets.items()
        }
        return yaml.safe_dump(all_presets, default_flow_style=False)

    def list(self):
        if len(self) == 0:
            print("no presets found")
            return

        for handler in self.handlers:
            val = str(handler)
            if val:
                val = "\n  ".join(
                    [""] + val.splitlines() + [""]
                )  # indent all lines by 2 spaces
                print("Presets from {}:".format(handler.path))
                print(val)