texfleet 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- texfleet/__init__.py +3 -0
- texfleet/__main__.py +3 -0
- texfleet/cli.py +343 -0
- texfleet/config.py +151 -0
- texfleet/files.py +265 -0
- texfleet/latex.py +555 -0
- texfleet/projects.py +283 -0
- texfleet/remote.py +249 -0
- texfleet/server.py +578 -0
- texfleet/static/app.css +343 -0
- texfleet/static/favicon.svg +1 -0
- texfleet/static/index.html +32 -0
- texfleet/static/js/api.js +50 -0
- texfleet/static/js/app.js +129 -0
- texfleet/static/js/home.js +202 -0
- texfleet/static/js/pdfview.js +307 -0
- texfleet/static/js/util.js +223 -0
- texfleet/static/js/workspace.js +1242 -0
- texfleet/static/vendor/VERSIONS +2 -0
- texfleet/static/vendor/codemirror/LICENSE +21 -0
- texfleet/static/vendor/codemirror/codemirror.bundle.css +384 -0
- texfleet/static/vendor/codemirror/codemirror.bundle.js +17520 -0
- texfleet/static/vendor/codemirror/vim.js +5978 -0
- texfleet/static/vendor/pdfjs/LICENSE +177 -0
- texfleet/static/vendor/pdfjs/pdf.min.mjs +21 -0
- texfleet/static/vendor/pdfjs/pdf.worker.min.mjs +21 -0
- texfleet-0.1.0.dist-info/METADATA +202 -0
- texfleet-0.1.0.dist-info/RECORD +33 -0
- texfleet-0.1.0.dist-info/WHEEL +4 -0
- texfleet-0.1.0.dist-info/entry_points.txt +2 -0
- texfleet-0.1.0.dist-info/licenses/LICENSE +21 -0
- texfleet-0.1.0.dist-info/licenses/texfleet/static/vendor/codemirror/LICENSE +21 -0
- texfleet-0.1.0.dist-info/licenses/texfleet/static/vendor/pdfjs/LICENSE +177 -0
texfleet/__init__.py
ADDED
texfleet/__main__.py
ADDED
texfleet/cli.py
ADDED
|
@@ -0,0 +1,343 @@
|
|
|
1
|
+
"""Command line: texfleet serve | open | url | ensure | stop | deploy | add-machine | install | service."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import platform
|
|
9
|
+
import shlex
|
|
10
|
+
import signal
|
|
11
|
+
import subprocess
|
|
12
|
+
import sys
|
|
13
|
+
import time
|
|
14
|
+
import urllib.request
|
|
15
|
+
|
|
16
|
+
from texfleet import __version__
|
|
17
|
+
from texfleet.config import (get_token, home_dir, load_config, norm, path_in_home, read_json,
|
|
18
|
+
save_config)
|
|
19
|
+
|
|
20
|
+
USAGE = """\
|
|
21
|
+
texfleet: a lightweight web editor for LaTeX papers on your local and remote machines.
|
|
22
|
+
|
|
23
|
+
texfleet serve [--port N] [--bind ADDR]... [--root DIR]... run the server in the foreground
|
|
24
|
+
texfleet open start in the background if needed, open the browser
|
|
25
|
+
texfleet url print the URL (with access token) of the running server
|
|
26
|
+
texfleet stop stop the background server
|
|
27
|
+
texfleet add-machine NAME --ssh HOST add a remote machine reached over ssh (or --url URL)
|
|
28
|
+
texfleet deploy HOST copy this texfleet to HOST:~/.local/bin/texfleet over ssh
|
|
29
|
+
texfleet install [DIR] install this texfleet as DIR/texfleet (default ~/.local/bin)
|
|
30
|
+
texfleet service install start texfleet at login (systemd user unit / launchd)
|
|
31
|
+
texfleet ensure (used over ssh) start if needed, print port and token
|
|
32
|
+
texfleet version
|
|
33
|
+
|
|
34
|
+
Config: %s/config.json
|
|
35
|
+
"""
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _running():
|
|
39
|
+
"""server.json of a live server, else None."""
|
|
40
|
+
info = read_json(path_in_home("server.json"))
|
|
41
|
+
if not info:
|
|
42
|
+
return None
|
|
43
|
+
try:
|
|
44
|
+
os.kill(int(info["pid"]), 0)
|
|
45
|
+
except (OSError, KeyError, ValueError):
|
|
46
|
+
return None
|
|
47
|
+
host = _connect_host(info)
|
|
48
|
+
try:
|
|
49
|
+
with urllib.request.urlopen(f"http://{host}:{info['port']}/ping", timeout=2) as r:
|
|
50
|
+
pong = json.load(r)
|
|
51
|
+
if pong.get("ok"):
|
|
52
|
+
info["live_version"] = pong.get("version")
|
|
53
|
+
return info
|
|
54
|
+
except (OSError, ValueError):
|
|
55
|
+
return None
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _connect_host(info: dict) -> str:
|
|
60
|
+
binds = info.get("binds") or ["127.0.0.1"]
|
|
61
|
+
if "127.0.0.1" in binds:
|
|
62
|
+
return "127.0.0.1"
|
|
63
|
+
b = binds[0]
|
|
64
|
+
return "127.0.0.1" if b in ("0.0.0.0", "") else b
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _self_argv() -> list:
|
|
68
|
+
"""How to re-run this texfleet (from a zipapp or from the source tree)."""
|
|
69
|
+
loader = getattr(sys.modules["texfleet"], "__loader__", None)
|
|
70
|
+
archive = getattr(loader, "archive", None)
|
|
71
|
+
if archive:
|
|
72
|
+
return [sys.executable, archive]
|
|
73
|
+
src = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
74
|
+
return [sys.executable, "-c", f"import sys; sys.path.insert(0, {src!r}); "
|
|
75
|
+
"from texfleet.cli import main; main()"]
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _start_background() -> dict:
|
|
79
|
+
log = open(path_in_home("server.log"), "ab")
|
|
80
|
+
subprocess.Popen(_self_argv() + ["serve", "--quiet"], stdin=subprocess.DEVNULL, stdout=log,
|
|
81
|
+
stderr=log, start_new_session=True, close_fds=True)
|
|
82
|
+
deadline = time.time() + 10
|
|
83
|
+
while time.time() < deadline:
|
|
84
|
+
info = _running()
|
|
85
|
+
if info:
|
|
86
|
+
return info
|
|
87
|
+
time.sleep(0.15)
|
|
88
|
+
raise SystemExit(f"texfleet did not start; see {path_in_home('server.log')}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _stop(info: dict) -> None:
|
|
92
|
+
try:
|
|
93
|
+
os.kill(int(info["pid"]), signal.SIGTERM)
|
|
94
|
+
except OSError:
|
|
95
|
+
return
|
|
96
|
+
for _ in range(50):
|
|
97
|
+
try:
|
|
98
|
+
os.kill(int(info["pid"]), 0)
|
|
99
|
+
except OSError:
|
|
100
|
+
return
|
|
101
|
+
time.sleep(0.1)
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def ensure() -> dict:
|
|
105
|
+
info = _running()
|
|
106
|
+
if info and info.get("live_version") != __version__:
|
|
107
|
+
_stop(info) # an older texfleet after `texfleet deploy`: replace it
|
|
108
|
+
info = None
|
|
109
|
+
if not info:
|
|
110
|
+
info = _start_background()
|
|
111
|
+
return info
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def cmd_ensure(_args) -> None:
|
|
115
|
+
info = ensure()
|
|
116
|
+
print(json.dumps({"port": info["port"], "host": _connect_host(info), "token": get_token(),
|
|
117
|
+
"version": __version__, "name": info.get("name")}))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _url(info: dict) -> str:
|
|
121
|
+
return f"http://{_connect_host(info)}:{info['port']}/?token={get_token()}"
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def cmd_serve(args) -> None:
|
|
125
|
+
cfg = load_config()
|
|
126
|
+
if args.port is not None:
|
|
127
|
+
cfg["port"] = args.port
|
|
128
|
+
if args.bind:
|
|
129
|
+
cfg["bind"] = args.bind
|
|
130
|
+
if args.root:
|
|
131
|
+
cfg["roots"] = [norm(r) for r in args.root]
|
|
132
|
+
if args.name:
|
|
133
|
+
cfg["name"] = args.name
|
|
134
|
+
info = _running()
|
|
135
|
+
if info and int(info["port"]) == int(cfg["port"]):
|
|
136
|
+
raise SystemExit(f"texfleet is already running on port {info['port']} (pid {info['pid']}); "
|
|
137
|
+
"`texfleet stop` first")
|
|
138
|
+
|
|
139
|
+
def term(*_):
|
|
140
|
+
raise KeyboardInterrupt
|
|
141
|
+
signal.signal(signal.SIGTERM, term)
|
|
142
|
+
|
|
143
|
+
def ready(binds, port, token):
|
|
144
|
+
if args.open:
|
|
145
|
+
_open_browser(f"http://{binds[0]}:{port}/?token={token}")
|
|
146
|
+
|
|
147
|
+
from texfleet.server import serve
|
|
148
|
+
serve(cfg, quiet=args.quiet, on_ready=ready)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _open_browser(url: str) -> None:
|
|
152
|
+
opener = "open" if platform.system() == "Darwin" else "xdg-open"
|
|
153
|
+
try:
|
|
154
|
+
subprocess.Popen([opener, url], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
|
155
|
+
except OSError:
|
|
156
|
+
print(url)
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def cmd_open(_args) -> None:
|
|
160
|
+
info = ensure()
|
|
161
|
+
url = _url(info)
|
|
162
|
+
print(url)
|
|
163
|
+
_open_browser(url)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def cmd_url(_args) -> None:
|
|
167
|
+
info = _running()
|
|
168
|
+
if not info:
|
|
169
|
+
raise SystemExit("texfleet is not running (start it with `texfleet open` or `texfleet serve`)")
|
|
170
|
+
for b in info.get("binds", []):
|
|
171
|
+
print(f"http://{'127.0.0.1' if b == '0.0.0.0' else b}:{info['port']}/?token={get_token()}")
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def cmd_stop(_args) -> None:
|
|
175
|
+
info = _running()
|
|
176
|
+
if not info:
|
|
177
|
+
print("texfleet is not running")
|
|
178
|
+
return
|
|
179
|
+
_stop(info)
|
|
180
|
+
print(f"stopped texfleet (pid {info['pid']})")
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def cmd_deploy(args) -> None:
|
|
184
|
+
from texfleet.remote import Machine, package_bytes
|
|
185
|
+
m = Machine({"name": args.host, "ssh": args.host, "command": args.command})
|
|
186
|
+
print(m.deploy(package_bytes()))
|
|
187
|
+
print(f"installed texfleet on {args.host}:{args.command}")
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def cmd_add_machine(args) -> None:
|
|
191
|
+
if not args.ssh and not args.url:
|
|
192
|
+
raise SystemExit("give --ssh HOST and/or --url URL")
|
|
193
|
+
cfg = load_config()
|
|
194
|
+
machines = [m for m in cfg.get("machines", []) if m.get("name") != args.name]
|
|
195
|
+
spec = {"name": args.name}
|
|
196
|
+
if args.ssh:
|
|
197
|
+
spec["ssh"] = args.ssh
|
|
198
|
+
if args.url:
|
|
199
|
+
spec["url"] = args.url
|
|
200
|
+
if args.token:
|
|
201
|
+
spec["token"] = args.token
|
|
202
|
+
if args.command:
|
|
203
|
+
spec["command"] = args.command
|
|
204
|
+
machines.append(spec)
|
|
205
|
+
cfg["machines"] = machines
|
|
206
|
+
save_config(cfg)
|
|
207
|
+
print(f"added {args.name}; restart texfleet (`texfleet stop && texfleet open`) to pick it up")
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def cmd_install(args) -> None:
|
|
211
|
+
from texfleet.remote import package_bytes
|
|
212
|
+
d = os.path.expanduser(args.dir)
|
|
213
|
+
os.makedirs(d, exist_ok=True)
|
|
214
|
+
dst = os.path.join(d, "texfleet")
|
|
215
|
+
import zipfile
|
|
216
|
+
if os.path.exists(dst) and not zipfile.is_zipfile(dst) and not args.force:
|
|
217
|
+
# e.g. the launcher script of a pip/pipx/uv installation: leave it alone.
|
|
218
|
+
raise SystemExit(f"{dst} exists and is not a texfleet zipapp (installed with pip, pipx "
|
|
219
|
+
"or uv?); use --force to replace it")
|
|
220
|
+
data = package_bytes()
|
|
221
|
+
tmp = dst + ".tmp"
|
|
222
|
+
with open(tmp, "wb") as f:
|
|
223
|
+
f.write(data)
|
|
224
|
+
os.chmod(tmp, 0o755)
|
|
225
|
+
os.replace(tmp, dst)
|
|
226
|
+
print(f"installed {dst}")
|
|
227
|
+
if d not in os.environ.get("PATH", "").split(os.pathsep):
|
|
228
|
+
print(f"note: {d} is not on your PATH")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def cmd_service(args) -> None:
|
|
232
|
+
import shutil
|
|
233
|
+
import zipfile
|
|
234
|
+
exe = shutil.which("texfleet") or os.path.expanduser("~/.local/bin/texfleet")
|
|
235
|
+
if not os.path.exists(exe):
|
|
236
|
+
raise SystemExit("texfleet is not on PATH; install it (pipx/uv tool install texfleet, "
|
|
237
|
+
"or `texfleet install`) first")
|
|
238
|
+
exe = os.path.realpath(exe)
|
|
239
|
+
# A zipapp runs through this interpreter; a pip/uv launcher script runs as is.
|
|
240
|
+
argv = ([sys.executable, exe] if zipfile.is_zipfile(exe) else [exe]) + ["serve", "--quiet"]
|
|
241
|
+
if platform.system() == "Darwin":
|
|
242
|
+
plist = os.path.expanduser("~/Library/LaunchAgents/dev.texfleet.plist")
|
|
243
|
+
if args.action == "uninstall":
|
|
244
|
+
subprocess.run(["launchctl", "unload", plist])
|
|
245
|
+
if os.path.exists(plist):
|
|
246
|
+
os.remove(plist)
|
|
247
|
+
print(f"removed {plist}")
|
|
248
|
+
return
|
|
249
|
+
os.makedirs(os.path.dirname(plist), exist_ok=True)
|
|
250
|
+
log = path_in_home("server.log")
|
|
251
|
+
with open(plist, "w") as f:
|
|
252
|
+
f.write(f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
253
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
254
|
+
<plist version="1.0"><dict>
|
|
255
|
+
<key>Label</key><string>dev.texfleet</string>
|
|
256
|
+
<key>ProgramArguments</key><array>
|
|
257
|
+
{"".join(f"<string>{a}</string>" for a in argv)}
|
|
258
|
+
</array>
|
|
259
|
+
<key>RunAtLoad</key><true/>
|
|
260
|
+
<key>KeepAlive</key><true/>
|
|
261
|
+
<key>EnvironmentVariables</key><dict>
|
|
262
|
+
<key>PATH</key><string>{os.environ.get('PATH', '/usr/bin:/bin')}</string>
|
|
263
|
+
</dict>
|
|
264
|
+
<key>StandardOutPath</key><string>{log}</string>
|
|
265
|
+
<key>StandardErrorPath</key><string>{log}</string>
|
|
266
|
+
</dict></plist>
|
|
267
|
+
""")
|
|
268
|
+
subprocess.run(["launchctl", "unload", plist], stderr=subprocess.DEVNULL)
|
|
269
|
+
subprocess.run(["launchctl", "load", plist], check=True)
|
|
270
|
+
print(f"installed and loaded {plist}")
|
|
271
|
+
return
|
|
272
|
+
unit_dir = os.path.expanduser("~/.config/systemd/user")
|
|
273
|
+
unit = os.path.join(unit_dir, "texfleet.service")
|
|
274
|
+
if args.action == "uninstall":
|
|
275
|
+
subprocess.run(["systemctl", "--user", "disable", "--now", "texfleet"])
|
|
276
|
+
if os.path.exists(unit):
|
|
277
|
+
os.remove(unit)
|
|
278
|
+
print(f"removed {unit}")
|
|
279
|
+
return
|
|
280
|
+
os.makedirs(unit_dir, exist_ok=True)
|
|
281
|
+
with open(unit, "w") as f:
|
|
282
|
+
f.write(f"""[Unit]
|
|
283
|
+
Description=texfleet LaTeX web editor
|
|
284
|
+
After=network-online.target
|
|
285
|
+
|
|
286
|
+
[Service]
|
|
287
|
+
ExecStart={" ".join(shlex.quote(a) for a in argv)}
|
|
288
|
+
Environment=PATH={os.environ.get('PATH', '/usr/bin:/bin')}
|
|
289
|
+
Restart=on-failure
|
|
290
|
+
|
|
291
|
+
[Install]
|
|
292
|
+
WantedBy=default.target
|
|
293
|
+
""")
|
|
294
|
+
subprocess.run(["systemctl", "--user", "daemon-reload"], check=True)
|
|
295
|
+
subprocess.run(["systemctl", "--user", "enable", "--now", "texfleet"], check=True)
|
|
296
|
+
print(f"installed {unit} and started it (systemctl --user status texfleet)")
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def main(argv=None) -> None:
|
|
300
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
301
|
+
if sys.version_info < (3, 9):
|
|
302
|
+
raise SystemExit("texfleet needs Python 3.9 or newer")
|
|
303
|
+
if not argv or argv[0] in ("-h", "--help", "help"):
|
|
304
|
+
print(USAGE % home_dir())
|
|
305
|
+
return
|
|
306
|
+
p = argparse.ArgumentParser(prog="texfleet", add_help=True)
|
|
307
|
+
sub = p.add_subparsers(dest="cmd")
|
|
308
|
+
s = sub.add_parser("serve")
|
|
309
|
+
s.add_argument("--port", type=int)
|
|
310
|
+
s.add_argument("--bind", action="append",
|
|
311
|
+
help="address to listen on; repeatable; 'tailscale' = this machine's Tailscale IP")
|
|
312
|
+
s.add_argument("--root", action="append", help="directory to expose; repeatable")
|
|
313
|
+
s.add_argument("--name", help="machine name shown in the UI")
|
|
314
|
+
s.add_argument("--open", action="store_true", help="open the browser")
|
|
315
|
+
s.add_argument("--quiet", action="store_true")
|
|
316
|
+
sub.add_parser("open")
|
|
317
|
+
sub.add_parser("url")
|
|
318
|
+
sub.add_parser("stop")
|
|
319
|
+
sub.add_parser("ensure")
|
|
320
|
+
sub.add_parser("version")
|
|
321
|
+
d = sub.add_parser("deploy")
|
|
322
|
+
d.add_argument("host")
|
|
323
|
+
d.add_argument("--command", default="~/.local/bin/texfleet", help="install path on the remote")
|
|
324
|
+
a = sub.add_parser("add-machine")
|
|
325
|
+
a.add_argument("name")
|
|
326
|
+
a.add_argument("--ssh")
|
|
327
|
+
a.add_argument("--url")
|
|
328
|
+
a.add_argument("--token")
|
|
329
|
+
a.add_argument("--command", help="texfleet path on the remote (default ~/.local/bin/texfleet)")
|
|
330
|
+
i = sub.add_parser("install")
|
|
331
|
+
i.add_argument("dir", nargs="?", default="~/.local/bin")
|
|
332
|
+
i.add_argument("--force", action="store_true", help="replace an existing non-zipapp texfleet")
|
|
333
|
+
sv = sub.add_parser("service")
|
|
334
|
+
sv.add_argument("action", choices=["install", "uninstall"])
|
|
335
|
+
args = p.parse_args(argv)
|
|
336
|
+
{"serve": cmd_serve, "open": cmd_open, "url": cmd_url, "stop": cmd_stop,
|
|
337
|
+
"ensure": cmd_ensure, "deploy": cmd_deploy, "add-machine": cmd_add_machine,
|
|
338
|
+
"install": cmd_install, "service": cmd_service,
|
|
339
|
+
"version": lambda _a: print(f"texfleet {__version__}")}[args.cmd](args)
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
if __name__ == "__main__":
|
|
343
|
+
main()
|
texfleet/config.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""Configuration, persistent UI state and the access token.
|
|
2
|
+
|
|
3
|
+
Everything lives in one directory: $TEXFLEET_HOME, else $XDG_CONFIG_HOME/texfleet, else ~/.config/texfleet.
|
|
4
|
+
|
|
5
|
+
config.json user-edited settings (roots, port, bind addresses, remote machines)
|
|
6
|
+
state.json written by texfleet (pinned / manually added / hidden projects)
|
|
7
|
+
token random access token, mode 0600
|
|
8
|
+
server.json pid, port and addresses of the running server
|
|
9
|
+
server.log output of a server started in the background by `texfleet ensure`
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import secrets
|
|
17
|
+
import socket
|
|
18
|
+
import threading
|
|
19
|
+
|
|
20
|
+
DEFAULT_PORT = 7878
|
|
21
|
+
|
|
22
|
+
# Directories never descended into when discovering projects, listing or searching files.
|
|
23
|
+
IGNORED_DIRS = {
|
|
24
|
+
".git", ".hg", ".svn", "node_modules", "__pycache__", ".venv", "venv", ".tox",
|
|
25
|
+
".mypy_cache", ".pytest_cache", ".ruff_cache", ".cache", ".idea", ".vscode",
|
|
26
|
+
".ipynb_checkpoints", "site-packages", ".eggs", "target", ".next", ".texfleet-trash",
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def home_dir() -> str:
|
|
31
|
+
d = os.environ.get("TEXFLEET_HOME")
|
|
32
|
+
if not d:
|
|
33
|
+
base = os.environ.get("XDG_CONFIG_HOME") or os.path.expanduser("~/.config")
|
|
34
|
+
d = os.path.join(base, "texfleet")
|
|
35
|
+
os.makedirs(d, mode=0o700, exist_ok=True)
|
|
36
|
+
return d
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def path_in_home(name: str) -> str:
|
|
40
|
+
return os.path.join(home_dir(), name)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def short_hostname() -> str:
|
|
44
|
+
return socket.gethostname().split(".")[0] or "local"
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _default_roots() -> list:
|
|
48
|
+
ws = os.path.expanduser("~/workspace")
|
|
49
|
+
return ["~/workspace"] if os.path.isdir(ws) else ["~"]
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def default_config() -> dict:
|
|
53
|
+
return {
|
|
54
|
+
"name": short_hostname(),
|
|
55
|
+
"roots": _default_roots(),
|
|
56
|
+
"port": DEFAULT_PORT,
|
|
57
|
+
"bind": ["127.0.0.1"],
|
|
58
|
+
"machines": [],
|
|
59
|
+
"discover_depth": 3,
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def load_config() -> dict:
|
|
64
|
+
cfg = default_config()
|
|
65
|
+
p = path_in_home("config.json")
|
|
66
|
+
if os.path.exists(p):
|
|
67
|
+
with open(p, encoding="utf-8") as f:
|
|
68
|
+
user = json.load(f)
|
|
69
|
+
if not isinstance(user, dict):
|
|
70
|
+
raise SystemExit(f"{p}: expected a JSON object")
|
|
71
|
+
cfg.update(user)
|
|
72
|
+
if isinstance(cfg.get("bind"), str):
|
|
73
|
+
cfg["bind"] = [cfg["bind"]]
|
|
74
|
+
cfg["roots"] = [norm(r) for r in cfg.get("roots") or []]
|
|
75
|
+
return cfg
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def save_config(cfg: dict) -> None:
|
|
79
|
+
out = dict(cfg)
|
|
80
|
+
out["roots"] = [unexpand(r) for r in out.get("roots", [])]
|
|
81
|
+
write_json(path_in_home("config.json"), out)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def norm(p: str) -> str:
|
|
85
|
+
return os.path.normpath(os.path.abspath(os.path.expanduser(p)))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def unexpand(p: str) -> str:
|
|
89
|
+
h = os.path.expanduser("~")
|
|
90
|
+
if p == h:
|
|
91
|
+
return "~"
|
|
92
|
+
if p.startswith(h + os.sep):
|
|
93
|
+
return "~" + p[len(h):]
|
|
94
|
+
return p
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def write_json(path: str, obj, mode: int = 0o600) -> None:
|
|
98
|
+
tmp = f"{path}.{os.getpid()}.tmp"
|
|
99
|
+
fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, mode)
|
|
100
|
+
with os.fdopen(fd, "w", encoding="utf-8") as f:
|
|
101
|
+
json.dump(obj, f, indent=2)
|
|
102
|
+
f.write("\n")
|
|
103
|
+
os.replace(tmp, path)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def read_json(path: str, default=None):
|
|
107
|
+
try:
|
|
108
|
+
with open(path, encoding="utf-8") as f:
|
|
109
|
+
return json.load(f)
|
|
110
|
+
except (OSError, ValueError):
|
|
111
|
+
return default
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def get_token() -> str:
|
|
115
|
+
p = path_in_home("token")
|
|
116
|
+
try:
|
|
117
|
+
with open(p, encoding="utf-8") as f:
|
|
118
|
+
tok = f.read().strip()
|
|
119
|
+
if tok:
|
|
120
|
+
return tok
|
|
121
|
+
except OSError:
|
|
122
|
+
pass
|
|
123
|
+
tok = secrets.token_urlsafe(24)
|
|
124
|
+
fd = os.open(p, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
125
|
+
with os.fdopen(fd, "w") as f:
|
|
126
|
+
f.write(tok + "\n")
|
|
127
|
+
return tok
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class State:
|
|
131
|
+
"""Small JSON store for things the UI changes: pinned, added and hidden projects."""
|
|
132
|
+
|
|
133
|
+
def __init__(self) -> None:
|
|
134
|
+
self._lock = threading.Lock()
|
|
135
|
+
self._path = path_in_home("state.json")
|
|
136
|
+
data = read_json(self._path, {}) or {}
|
|
137
|
+
self.pinned = list(data.get("pinned", []))
|
|
138
|
+
self.added = list(data.get("added", []))
|
|
139
|
+
self.hidden = list(data.get("hidden", []))
|
|
140
|
+
|
|
141
|
+
def _save(self) -> None:
|
|
142
|
+
write_json(self._path, {"pinned": self.pinned, "added": self.added, "hidden": self.hidden})
|
|
143
|
+
|
|
144
|
+
def update(self, key: str, path: str, on: bool) -> None:
|
|
145
|
+
with self._lock:
|
|
146
|
+
lst = getattr(self, key)
|
|
147
|
+
if on and path not in lst:
|
|
148
|
+
lst.append(path)
|
|
149
|
+
elif not on and path in lst:
|
|
150
|
+
lst.remove(path)
|
|
151
|
+
self._save()
|