fairshare-cli 0.1.1__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.
fairshare/__init__.py ADDED
@@ -0,0 +1,2 @@
1
+ """fairshare: route sessions across several subscriptions by real usage."""
2
+ __version__ = "0.1.1"
fairshare/browser.py ADDED
@@ -0,0 +1,91 @@
1
+ """Which browser an account's sign-in link opens in. Provider-neutral: the provider's own sign-in
2
+ calls the program named by BROWSER with the link as its one argument (a value with arguments is
3
+ not split, so it must name one executable). fairshare writes a one-line launcher per account and
4
+ names it there; it never sees the link.
5
+
6
+ An account's `browser` line in accounts.toml:
7
+ absent the system default
8
+ chrome:<profile folder> that Google Chrome profile (macOS)
9
+ command:<absolute path> an executable taking the link
10
+
11
+ Chrome's profiles are read from its own `Local State` file, and only each profile's folder name
12
+ and display name; no other browser data is read."""
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import os
17
+ import shlex
18
+ import tempfile
19
+ from pathlib import Path
20
+
21
+ ENV = "BROWSER"
22
+ CHROME, COMMAND = "chrome:", "command:"
23
+ CHROME_APP = "Google Chrome"
24
+ CHROME_LOCAL_STATE = "Library/Application Support/Google/Chrome/Local State" # under HOME
25
+ CHROME_PROFILES = ("profile", "info_cache") # where Local State lists the profiles
26
+ CHROME_NAME = "name" # a profile's display name
27
+
28
+
29
+ def parse(spec: str) -> tuple[str, str]:
30
+ """(kind, value) of a `browser` line; raises ValueError for one that is not accepted."""
31
+ if isinstance(spec, str) and spec.startswith(CHROME) and spec[len(CHROME):].strip():
32
+ return CHROME, spec[len(CHROME):]
33
+ if isinstance(spec, str) and spec.startswith(COMMAND) and os.path.isabs(spec[len(COMMAND):]):
34
+ return COMMAND, spec[len(COMMAND):]
35
+ raise ValueError(f"browser {spec!r}: use '{CHROME}<profile folder>' or "
36
+ f"'{COMMAND}<absolute path>' (or leave it out for the default browser)")
37
+
38
+
39
+ def chrome_profiles(home: Path) -> list[tuple[str, str]]:
40
+ """(profile folder, display name) of each Chrome profile, by display name; [] when Chrome's
41
+ Local State is missing or unreadable."""
42
+ try:
43
+ d = json.loads((home / CHROME_LOCAL_STATE).read_text(encoding="utf-8"))
44
+ for key in CHROME_PROFILES:
45
+ d = d[key]
46
+ found = [(folder, str(p.get(CHROME_NAME) or folder)) for folder, p in d.items()
47
+ if isinstance(p, dict)]
48
+ except (OSError, UnicodeDecodeError, ValueError, KeyError, TypeError, AttributeError):
49
+ return []
50
+ return sorted(found, key=lambda x: (x[1].lower(), x[0]))
51
+
52
+
53
+ def script(spec: str) -> str:
54
+ """The launcher's text: a shell script that opens its one argument as `spec` says."""
55
+ kind, value = parse(spec)
56
+ if kind == CHROME:
57
+ line = (f"exec open -na {shlex.quote(CHROME_APP)} --args "
58
+ f"--profile-directory={shlex.quote(value)} \"$1\"")
59
+ else:
60
+ line = f"exec {shlex.quote(value)} \"$1\""
61
+ return f"#!/bin/sh\n{line}\n"
62
+
63
+
64
+ def launcher(hub: Path, account_id: str) -> Path:
65
+ return hub / "browsers" / account_id
66
+
67
+
68
+ def ensure(hub: Path, account_id: str, spec: str | None) -> Path | None:
69
+ """The account's launcher, (re)written when missing or different, mode 755; None when the
70
+ account uses the default browser. Raises OSError when it cannot be written."""
71
+ if spec is None:
72
+ return None
73
+ path, text = launcher(hub, account_id), script(spec)
74
+ try:
75
+ current = path.read_text(encoding="utf-8")
76
+ except (OSError, UnicodeDecodeError):
77
+ current = None
78
+ if current != text or not os.access(path, os.X_OK):
79
+ path.parent.mkdir(parents=True, exist_ok=True)
80
+ fd, tmp = tempfile.mkstemp(dir=path.parent)
81
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
82
+ f.write(text)
83
+ os.chmod(tmp, 0o755)
84
+ os.replace(tmp, path)
85
+ return path
86
+
87
+
88
+ def env(hub: Path, account_id: str, spec: str | None) -> dict[str, str]:
89
+ """The variable to add to the account's sign-in and sessions: {} for the default browser."""
90
+ path = ensure(hub, account_id, spec)
91
+ return {ENV: str(path.absolute())} if path else {}