-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
407 lines (319 loc) · 12.5 KB
/
Copy pathapp.py
File metadata and controls
407 lines (319 loc) · 12.5 KB
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
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
import os
import re
import shutil
import glob
import time
import datetime
import json
from flask import Flask, render_template, jsonify, request, send_file, Response
from ruamel.yaml import YAML
from io import StringIO
from werkzeug.utils import secure_filename
app = Flask(__name__)
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
MATCH_DIR = os.path.join(SCRIPT_DIR, ".espanso", "match")
INACTIVE_DIR = os.path.join(MATCH_DIR, "inactive")
BACKUP_DIR = os.path.join(SCRIPT_DIR, ".espanso", "backups")
os.makedirs(MATCH_DIR, exist_ok=True)
os.makedirs(INACTIVE_DIR, exist_ok=True)
os.makedirs(BACKUP_DIR, exist_ok=True)
yaml = YAML()
yaml.preserve_quotes = True
yaml.width = 4096
yaml.default_flow_style = False
def find_match_files():
files = sorted(glob.glob(os.path.join(MATCH_DIR, "*.yml")))
return [f for f in files if "packages" not in f.lower()]
def find_inactive_files():
files = sorted(glob.glob(os.path.join(INACTIVE_DIR, "*.yml")))
return files
def load_all_matches():
result = []
for filepath in find_match_files():
filename = os.path.basename(filepath)
try:
with open(filepath, "r", encoding="utf-8") as f:
raw = f.read()
labels = {}
lines = raw.split("\n")
match_idx = 0
for line in lines:
stripped = line.strip()
m = re.match(r"^#\s*label:\s*(.+)$", stripped)
if m:
labels[match_idx] = m.group(1).strip()
elif stripped.startswith("- trigger:") or (stripped.startswith("- ") and "trigger" in stripped):
match_idx += 1
with open(filepath, "r", encoding="utf-8") as f:
data = yaml.load(f)
if data and "matches" in data:
for i, match in enumerate(data["matches"]):
if isinstance(match, dict) and "trigger" in match:
replace_val = match.get("replace", "")
result.append({
"file": filename,
"index": i,
"label": labels.get(i, ""),
"trigger": match.get("trigger", ""),
"replace": replace_val if replace_val else "",
"replace_type": "multiline" if (isinstance(replace_val, str) and "\n" in replace_val) else "single",
"vars": match.get("vars", None),
"has_vars": bool(match.get("vars")),
})
except Exception as e:
print(f"Error loading {filepath}: {e}")
return result
def backup_file(filepath):
if not os.path.exists(filepath):
return
for attempt in range(3):
try:
ts = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
basename = os.path.basename(filepath)
backup_path = os.path.join(BACKUP_DIR, f"{basename}.{ts}.bak")
shutil.copy2(filepath, backup_path)
latest = os.path.join(BACKUP_DIR, f"{basename}.latest.bak")
shutil.copy2(filepath, latest)
return
except PermissionError:
time.sleep(0.5)
print(f"Warning: Could not backup {filepath}")
def write_yaml_with_labels(filepath, matches_data):
backup_file(filepath)
try:
with open(filepath, "r", encoding="utf-8") as f:
header_lines = []
for line in f:
if line.strip().startswith("matches:"):
break
header_lines.append(line.rstrip("\n"))
except FileNotFoundError:
header_lines = []
doc = {"matches": []}
for m in matches_data:
entry = {"trigger": m["trigger"], "replace": m["replace"]}
if m.get("vars"):
entry["vars"] = m["vars"]
entry["word"] = True
doc["matches"].append(entry)
stream = StringIO()
yaml.dump(doc, stream)
content = stream.getvalue()
y2 = YAML()
y2.preserve_quotes = True
y2.width = 4096
parsed = y2.load(StringIO(content))
if not parsed or "matches" not in parsed:
return jsonify({"error": "YAML validation failed"}), 500
lines = content.split("\n")
new_lines = []
match_idx = 0
for line in lines:
stripped = line.strip()
if stripped.startswith("- trigger:"):
label = matches_data[match_idx].get("label", "").strip() if match_idx < len(matches_data) else ""
if label:
indent = line[:len(line) - len(stripped)]
new_lines.append(f"{indent}# label: {label}")
match_idx += 1
new_lines.append(line)
final_lines = header_lines + [""] + new_lines
final_content = "\n".join(final_lines)
tmp_path = filepath + ".tmp"
for attempt in range(3):
try:
with open(tmp_path, "w", encoding="utf-8") as f:
f.write(final_content)
os.replace(tmp_path, filepath)
return None
except PermissionError:
time.sleep(0.5)
if os.path.exists(tmp_path):
os.remove(tmp_path)
return jsonify({"error": "Write error: file is locked"}), 500
@app.route("/")
def index():
return render_template("index.html")
@app.route("/api/matches", methods=["GET"])
def get_matches():
return jsonify(load_all_matches())
@app.route("/api/matches", methods=["POST"])
def create_match():
data = request.json
trigger = data.get("trigger", "").strip()
replace = data.get("replace", "").strip()
label = data.get("label", "").strip()
filename = data.get("file", "base.yml")
if not trigger or not replace:
return jsonify({"error": "Trigger and Replace are required"}), 400
if not trigger.startswith(":"):
trigger = ":" + trigger
filepath = os.path.join(MATCH_DIR, filename)
if not os.path.exists(filepath):
with open(filepath, "w", encoding="utf-8") as f:
f.write("# espanso match file\n\nmatches:\n")
all_matches = load_all_matches()
file_matches = [m for m in all_matches if m["file"] == filename]
file_matches.append({
"file": filename,
"index": len(file_matches),
"label": label,
"trigger": trigger,
"replace": replace,
"vars": None,
"has_vars": False,
})
err = write_yaml_with_labels(filepath, file_matches)
if err:
return err
return jsonify({"ok": True})
@app.route("/api/matches/<filename>/<int:index>", methods=["PUT"])
def update_match(filename, index):
data = request.json
trigger = data.get("trigger", "").strip()
replace = data.get("replace", "").strip()
label = data.get("label", "").strip()
if not trigger or not replace:
return jsonify({"error": "Trigger and Replace are required"}), 400
if not trigger.startswith(":"):
trigger = ":" + trigger
filepath = os.path.join(MATCH_DIR, filename)
if not os.path.exists(filepath):
return jsonify({"error": "File not found"}), 404
all_matches = load_all_matches()
file_matches = [m for m in all_matches if m["file"] == filename]
if index >= len(file_matches):
return jsonify({"error": "Index out of range"}), 404
file_matches[index]["trigger"] = trigger
file_matches[index]["replace"] = replace
file_matches[index]["label"] = label
err = write_yaml_with_labels(filepath, file_matches)
if err:
return err
return jsonify({"ok": True})
@app.route("/api/matches/<filename>/<int:index>", methods=["DELETE"])
def delete_match(filename, index):
filepath = os.path.join(MATCH_DIR, filename)
if not os.path.exists(filepath):
return jsonify({"error": "File not found"}), 404
all_matches = load_all_matches()
file_matches = [m for m in all_matches if m["file"] == filename]
if index >= len(file_matches):
return jsonify({"error": "Index out of range"}), 404
file_matches.pop(index)
err = write_yaml_with_labels(filepath, file_matches)
if err:
return err
return jsonify({"ok": True})
@app.route("/api/files", methods=["GET"])
def list_files():
active = [os.path.basename(f) for f in find_match_files()]
inactive = [os.path.basename(f) for f in find_inactive_files()]
return jsonify({"active": active, "inactive": inactive})
@app.route("/api/files/move", methods=["POST"])
def move_file():
data = request.json
filename = data.get("filename")
direction = data.get("direction")
if not filename:
return jsonify({"error": "No filename provided"}), 400
src = ""
dst = ""
if direction == "to_inactive":
src = os.path.join(MATCH_DIR, filename)
dst = os.path.join(INACTIVE_DIR, filename)
elif direction == "to_active":
src = os.path.join(INACTIVE_DIR, filename)
dst = os.path.join(MATCH_DIR, filename)
else:
return jsonify({"error": "Invalid direction"}), 400
if not os.path.exists(src):
return jsonify({"error": "File not found"}), 404
backup_file(src)
shutil.move(src, dst)
return jsonify({"ok": True})
@app.route("/api/export/<filename>", methods=["GET"])
def export_file(filename):
filepath = os.path.join(MATCH_DIR, filename)
if not os.path.exists(filepath):
filepath = os.path.join(INACTIVE_DIR, filename)
if not os.path.exists(filepath):
return jsonify({"error": "File not found"}), 404
return send_file(filepath, as_attachment=True, download_name=filename)
@app.route("/api/import", methods=["POST"])
def import_file():
if "file" not in request.files:
return jsonify({"error": "No file provided"}), 400
file = request.files["file"]
mode = request.form.get("mode", "merge")
if file.filename == "":
return jsonify({"error": "No filename"}), 400
filename = secure_filename(file.filename)
if not filename.endswith(".yml"):
filename += ".yml"
content = file.read().decode("utf-8")
try:
y = YAML()
data = y.load(StringIO(content))
if not data or "matches" not in data:
return jsonify({"error": "Invalid format: no matches section"}), 400
except Exception as e:
return jsonify({"error": f"YAML parse error: {e}"}), 400
if mode == "replace":
filepath = os.path.join(MATCH_DIR, "base.yml")
backup_file(filepath)
with open(filepath, "w", encoding="utf-8") as f:
f.write(content)
return jsonify({"ok": True, "mode": "replace"})
if mode == "merge":
target_path = os.path.join(MATCH_DIR, "base.yml")
backup_file(target_path)
try:
with open(target_path, "r", encoding="utf-8") as f:
existing = yaml.load(f)
if existing is None:
existing = {"matches": []}
except Exception:
existing = {"matches": []}
if "matches" not in existing:
existing["matches"] = []
existing["matches"].extend(data["matches"])
err = write_yaml_with_labels(target_path, [
{
"trigger": m.get("trigger", ""),
"replace": m.get("replace", ""),
"vars": m.get("vars"),
"label": ""
} for m in data["matches"]
])
if err:
return err
return jsonify({"ok": True, "mode": "merge", "added": len(data["matches"])})
return jsonify({"error": "Unknown mode"}), 400
@app.route("/api/backups", methods=["GET"])
def list_backups():
backups = []
if os.path.exists(BACKUP_DIR):
for f in sorted(os.listdir(BACKUP_DIR), reverse=True):
if f.endswith(".bak"):
fp = os.path.join(BACKUP_DIR, f)
backups.append({
"name": f,
"size": os.path.getsize(fp),
"time": datetime.datetime.fromtimestamp(os.path.getmtime(fp)).strftime("%Y-%m-%d %H:%M:%S"),
})
return jsonify(backups)
@app.route("/api/backups/<name>/restore", methods=["POST"])
def restore_backup(name):
backup_path = os.path.join(BACKUP_DIR, name)
if not os.path.exists(backup_path):
return jsonify({"error": "Backup not found"}), 404
target_name = name.split(".")[0] + ".yml"
target_path = os.path.join(MATCH_DIR, target_name)
backup_file(target_path)
shutil.copy2(backup_path, target_path)
return jsonify({"ok": True})
if __name__ == "__main__":
print(f"Espanso Manager running at: http://localhost:5567")
print(f"Match dir: {MATCH_DIR}")
app.run(host="127.0.0.1", port=5567, debug=False)