Repository navigation
Expand file tree
/
Copy pathparse-opencode.py
More file actions
executable file
·66 lines (58 loc) · 1.98 KB
/
Copy pathparse-opencode.py
File metadata and controls
executable file
·66 lines (58 loc) · 1.98 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
#!/usr/bin/env python3
"""opencode (OpenCode Go) workspace page text -> usage JSON.
Reads the dashboard page innerText on stdin, writes the generic usage JSON
(consumed by Sources/main.swift's parseGenericItems) on stdout. Exits non-zero
when no usage windows are found — e.g. a login redirect — so the caller can
keep the previous good snapshot instead of overwriting it with nothing.
"""
import json
import re
import sys
from datetime import datetime, timezone
# (page label, output label) in display order: rolling 5h, weekly, monthly.
WINDOWS = [
("滾動使用量", "5h"),
("每週使用量", "Weekly"),
("每月使用量", "Monthly"),
]
def parse(text):
items = []
for page_label, label in WINDOWS:
start = text.find(page_label)
if start < 0:
continue
# Slice from this window label up to the nearest other window label
# (or end of text), so each window's %/reset stays in its own block.
rest = text[start + len(page_label):]
cut = len(rest)
for other, _ in WINDOWS:
if other == page_label:
continue
j = rest.find(other)
if 0 <= j < cut:
cut = j
block = rest[:cut]
pct_m = re.search(r"(\d+)\s*%", block)
if not pct_m:
continue
reset_m = re.search(r"重置時間:\s*([^\n]+)", block)
items.append({
"label": label,
"used_percentage": int(pct_m.group(1)),
"resets_info": reset_m.group(1).strip() if reset_m else "",
})
return items
def main():
items = parse(sys.stdin.read())
if not items:
sys.stderr.write("parse-opencode: no usage windows found\n")
sys.exit(1)
out = {
"plan": "Go",
"items": items,
"updated_at": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}
json.dump(out, sys.stdout, ensure_ascii=False)
sys.stdout.write("\n")
if __name__ == "__main__":
main()