-
Notifications
You must be signed in to change notification settings - Fork 26
/
picker.py
56 lines (44 loc) · 1.59 KB
/
picker.py
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
"""
Call a command line fuzzy matcher to select a figure to edit.
Current supported matchers are:
* rofi for Linux platforms
* choose (https://github.com/chipsenkbeil/choose) on MacOS
"""
import subprocess
import platform
SYSTEM_NAME = platform.system()
def get_picker_cmd(picker_args=None, fuzzy=True):
"""
Create the shell command that will be run to start the picker.
"""
if SYSTEM_NAME == "Darwin":
args = ["choose"]
# args = ["choose", "-u", "-n", "15", "-c", "BB33B7", "-b", "BF44C8"]
elif SYSTEM_NAME == "Linux":
args = ["rofi", "-sort", "-no-levenshtein-sort"]
if fuzzy:
args += ["-matching", "fuzzy"]
args += ["-dmenu", "-p", "Select Figure", "-format", "s", "-i", "-lines", "5"]
else:
raise ValueError("No supported picker for {}".format(SYSTEM_NAME))
if picker_args is not None:
args += picker_args
return [str(arg) for arg in args]
def pick(options, picker_args=None, fuzzy=True):
optionstr = "\n".join(option.replace("\n", " ") for option in options)
cmd = get_picker_cmd(picker_args=picker_args, fuzzy=fuzzy)
result = subprocess.run(cmd, input=optionstr, stdout=subprocess.PIPE, universal_newlines=True)
returncode = result.returncode
stdout = result.stdout.strip()
selected = stdout.strip()
try:
index = [opt.strip() for opt in options].index(selected)
except ValueError:
index = -1
if returncode == 0:
key = 0
elif returncode == 1:
key = -1
elif returncode > 9:
key = returncode - 9
return key, index, selected