-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfind_and_open_file
executable file
·283 lines (221 loc) · 8.58 KB
/
find_and_open_file
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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
#!/bin/python3
# complete rewrite of zzzfoo, to be simpler and work on my system
from recoll import recoll
import subprocess as sp
from subprocess import PIPE
import argparse
from dataclasses import dataclass
from tomllib import load as load_toml
import os
from sys import stderr
import typing
#
# ============================================================================================================
#
# maximum number of results to return
# making an assumption about how many results the user is willing to dig through
MAX_RESULTS: int = 20
FALLBACK_DEFAULT_COMMAND_FORMAT: list[str] = ['xdg-open', '{file}']
#
# config stuff ===============================================================================================
#
@dataclass(init=False)
class Config:
pdf_command_format: list[str] | None
default_command_format: list[str] | None
def __init__(self):
for member_name in type(self).__annotations__.keys():
setattr(self, member_name, None)
@staticmethod
def get_member_type(member_name: str):
member_type: type | None = Config.__annotations__.get(member_name)
assert(member_type is not None)
# assumes that all members in this class are written exactly as `some_type | None`, in that order.
return typing.get_args(member_type)[0]
def get_config_file_location() -> str | None:
# TODO check in directories https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
home_dir: str = os.path.expanduser('~')
assert(home_dir != '~')
config_path = home_dir + '/.config/fff.toml'
if os.path.isfile(config_path): return config_path
return None
def get_config() -> Config:
validated_config = Config()
config_file: str | None = get_config_file_location()
if (config_file is None):
print('No config file found')
return validated_config
print(f'Using config file `{config_file}`')
with open(config_file, 'rb') as f:
config: dict = load_toml(f)
config_error: bool = False
valid_config_keys = Config.__annotations__.keys()
for key, val in config.items():
if (key not in valid_config_keys):
stderr.write(f'error: config file: invalid key `{key}`')
config_error = True
continue
if (getattr(validated_config, key) is not None):
stderr.write(f'error: config file: key `{key}` is set multiple times')
config_error = True
continue
expected_type: type = Config.get_member_type(key)
try: casted_val = expected_type(val)
except(ValueError):
stderr.write(f'error: config file: value of `{key}` must have type `{expected_type}`')
config_error = True
continue
setattr(validated_config, key, casted_val)
if (config_error):
stderr.write('error: Aborting due to config errors.')
exit(1)
return validated_config
g_config: Config = get_config()
#
# ============================================================================================================
#
def get_pdf_command(fname: str, page: int | None) -> list[str] | None:
if page is None: page = 0
if (g_config.pdf_command_format is None): return None
cmd: list[str] = g_config.pdf_command_format
for i in range(len(cmd)):
cmd[i] = cmd[i].replace('{file}', fname)
cmd[i] = cmd[i].replace('{page}', str(page))
return cmd
def get_generic_file_command(fname: str) -> list[str]:
cmd: list[str]
if (g_config.default_command_format is not None):
cmd = g_config.default_command_format
else:
cmd = FALLBACK_DEFAULT_COMMAND_FORMAT
for i in range(len(cmd)):
cmd[i] = cmd[i].replace('{file}', fname)
return cmd
def parse_args():
parser = argparse.ArgumentParser(description='find files via a Rofi dialog')
parser.add_argument('--fulltext',
dest='full_text_search',
action='store_const', const=True,
default=False,
help='also do a full text search within files'
)
parser.add_argument('--pdf',
dest='pdf_only',
action='store_const', const=True,
default=False,
help='only return `.pdf` files'
)
return parser.parse_args()
def prompt_search_query(fulltext: bool, pdf_only: bool):
prompt = 'file search' if not fulltext else 'text search'
if pdf_only: prompt = 'PDF ' + prompt
ran = sp.run(['/bin/rofi', '-dmenu', '-p', prompt], stdout=PIPE, text=True)
if ran.returncode != 0: raise RuntimeError('Rofi (search query dialog) returned non-zero')
return ran.stdout
@dataclass
class SearchResult:
file_url: str
filename: str
snippets: list[str]
def search(user_query: str, fulltext: bool, pdf_only: bool) -> list[SearchResult]:
db = recoll.connect()
dbquery = db.query()
# if using sortby(), it must be before executing the search
dbquery.sortby('relevancyrating', ascending=False)
# build the query
# `,` indicates AND
query = []
# fulltext or filename only?
if fulltext: query.append(user_query)
else: query.append('filename:' + user_query.replace(' ',','))
#
if pdf_only: query.append('ext:pdf')
#
query_onestring = ' '.join(query)
# run the query
_n_results = dbquery.execute(query_onestring)
query_results = dbquery.fetchmany(MAX_RESULTS)
results: list[SearchResult] = [
SearchResult(
file_url=result.url,
filename=result.filename,
snippets=dbquery.getsnippets(result, nohl=True) if fulltext else []
)
for result in query_results
]
return results
@dataclass
class SelectableEntry:
filename: str
file_url: str
page: int | None
snippet: str | None
# returns the file url
def prompt_select_result(results: list[SearchResult], search_was_fulltext: bool) -> SelectableEntry:
entries: list[SelectableEntry] = []
idx = 0
for result in results:
if (search_was_fulltext):
for snippet in result.snippets:
entries.append(SelectableEntry(
filename=result.filename,
file_url=result.file_url,
# `snippet` is a tuple: (page number, matched word, actual snippet)
page=int(snippet[0]),
snippet=snippet[2]
))
else:
entries.append(SelectableEntry(
filename=result.filename,
file_url=result.file_url,
page=None,
snippet=None
))
text_entries: list[str] = []
idx = 0
for entry in entries:
text_entries.append(
f'{idx} ' # prepend index to the filename
+ (f'<b>{entry.filename}</b>' if search_was_fulltext else f'{entry.filename}')
+ (f'\n<small> p{entry.page}: {repr(entry.snippet)}</small>' if search_was_fulltext else '')
)
idx += 1
entries_onestring = '\0'.join(text_entries)
# make user select a file
ran = sp.run(
[
'/bin/rofi',
'-dmenu',
'-p', 'results', # prompt text
'-sep', '\\0',
'-i', # case-insensitive
'-markup-rows', # render markup, instead of just displaying it raw
]
+ (['-eh', '2'] if search_was_fulltext else []),
text=True, input=entries_onestring, stdout=PIPE
)
if ran.returncode != 0: raise RuntimeError('Rofi (result selection dialog) returned non-zero')
# process the selection
selected_idx = int(ran.stdout.split(' ')[0]) # get the index that was prepended to the entry
return entries[selected_idx]
if __name__ == '__main__':
args = parse_args() # command-line args
# get query from user
query_str = prompt_search_query(fulltext=args.full_text_search, pdf_only=args.pdf_only).strip()
if query_str == '': raise RuntimeError('empty input')
# search
results = search(query_str, fulltext=args.full_text_search, pdf_only=args.pdf_only)
# have user select file
selection: SelectableEntry = prompt_select_result(results, args.full_text_search)
# open the file and exit
cmd: list[str]
if (os.path.splitext(selection.file_url)[1] == '.pdf'):
pdf_cmd: list[str] | None = get_pdf_command(selection.file_url, selection.page)
if (pdf_cmd is not None): cmd = pdf_cmd
else: cmd = get_generic_file_command(selection.file_url)
else:
cmd = get_generic_file_command(selection.file_url)
print('Running command: ', end='')
print(cmd)
sp.Popen(cmd)
exit(0) # Popen uses fork() (on Unix systems), so exiting now won't kill the child process