Bug 1718787 [wpt PR 29544] - Add web platform tests for cookie size requirements...
[gecko.git] / tools / tryselect / preset.py
blob98d2849a71e8bb3d96398ce0317e10ef42881e1c
1 # This Source Code Form is subject to the terms of the Mozilla Public
2 # License, v. 2.0. If a copy of the MPL was not distributed with this
3 # file, You can obtain one at http://mozilla.org/MPL/2.0/.
6 import os
7 import shlex
8 import subprocess
10 import yaml
13 class PresetHandler:
14 def __init__(self, path):
15 self.path = path
16 self._presets = {}
18 @property
19 def presets(self):
20 if not self._presets and os.path.isfile(self.path):
21 with open(self.path) as fh:
22 self._presets = yaml.safe_load(fh) or {}
24 return self._presets
26 def __contains__(self, name):
27 return name in self.presets
29 def __getitem__(self, name):
30 return self.presets[name]
32 def __len__(self):
33 return len(self.presets)
35 def __str__(self):
36 if not self.presets:
37 return ""
38 return yaml.safe_dump(self.presets, default_flow_style=False)
40 def list(self):
41 if not self.presets:
42 print("no presets found")
43 else:
44 print(self)
46 def edit(self):
47 if "EDITOR" not in os.environ:
48 print(
49 "error: must set the $EDITOR environment variable to use --edit-presets"
51 return
53 subprocess.call(shlex.split(os.environ["EDITOR"]) + [self.path])
55 def save(self, name, **data):
56 self.presets[name] = data
58 with open(self.path, "w") as fh:
59 fh.write(str(self))
62 class MergedHandler:
63 def __init__(self, *paths):
64 """Helper class for dealing with multiple preset files."""
65 self.handlers = [PresetHandler(p) for p in paths]
67 def __contains__(self, name):
68 return any(name in handler for handler in self.handlers)
70 def __getitem__(self, name):
71 for handler in self.handlers:
72 if name in handler:
73 return handler[name]
74 raise KeyError(name)
76 def __len__(self):
77 return sum(len(h) for h in self.handlers)
79 def __str__(self):
80 all_presets = {
81 k: v for handler in self.handlers for k, v in handler.presets.items()
83 return yaml.safe_dump(all_presets, default_flow_style=False)
85 def list(self):
86 if len(self) == 0:
87 print("no presets found")
88 return
90 for handler in self.handlers:
91 val = str(handler)
92 if val:
93 val = "\n ".join(
94 [""] + val.splitlines() + [""]
95 ) # indent all lines by 2 spaces
96 print("Presets from {}:".format(handler.path))
97 print(val)