keeptabs 0.0.2__tar.gz

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.
@@ -0,0 +1,120 @@
1
+ .claude/handoffs/
2
+ .claude/scratch/
3
+
4
+ # Byte-compiled / optimized / DLL files
5
+ __pycache__/
6
+ *.py[cod]
7
+ *$py.class
8
+
9
+
10
+ .DS_Store
11
+ # C extensions
12
+ *.so
13
+
14
+ # TLS certificates
15
+ ## Ignore all PEM files anywhere
16
+ *.pem
17
+ ## Also ignore any certs directory
18
+ certs/
19
+
20
+ # Distribution / packaging
21
+ .Python
22
+ build/
23
+ develop-eggs/
24
+ dist/
25
+ downloads/
26
+ eggs/
27
+ .eggs/
28
+ lib/
29
+ lib64/
30
+ parts/
31
+ sdist/
32
+ var/
33
+ wheels/
34
+ *.egg-info/
35
+ .installed.cfg
36
+ *.egg
37
+ MANIFEST
38
+ _build
39
+
40
+ # PyInstaller
41
+ # Usually these files are written by a python script from a template
42
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
43
+ *.manifest
44
+ *.spec
45
+
46
+ # Installer logs
47
+ pip-log.txt
48
+ pip-delete-this-directory.txt
49
+
50
+ # Unit test / coverage reports
51
+ htmlcov/
52
+ .tox/
53
+ .coverage
54
+ .coverage.*
55
+ .cache
56
+ nosetests.xml
57
+ coverage.xml
58
+ *.cover
59
+ .hypothesis/
60
+ .pytest_cache/
61
+
62
+ # Translations
63
+ *.mo
64
+ *.pot
65
+
66
+ # Django stuff:
67
+ *.log
68
+ local_settings.py
69
+ db.sqlite3
70
+
71
+ # Flask stuff:
72
+ instance/
73
+ .webassets-cache
74
+
75
+ # Scrapy stuff:
76
+ .scrapy
77
+
78
+ # Sphinx documentation
79
+ docs/_build/
80
+ docs/*
81
+
82
+ # PyBuilder
83
+ target/
84
+
85
+ # Jupyter Notebook
86
+ .ipynb_checkpoints
87
+
88
+ # pyenv
89
+ .python-version
90
+
91
+ # celery beat schedule file
92
+ celerybeat-schedule
93
+
94
+ # SageMath parsed files
95
+ *.sage.py
96
+
97
+ # Environments
98
+ .env
99
+ .venv
100
+ env/
101
+ venv/
102
+ ENV/
103
+ env.bak/
104
+ venv.bak/
105
+
106
+ # Spyder project settings
107
+ .spyderproject
108
+ .spyproject
109
+
110
+ # Rope project settings
111
+ .ropeproject
112
+
113
+ # mkdocs documentation
114
+ /site
115
+
116
+ # mypy
117
+ .mypy_cache/
118
+
119
+ # PyCharm
120
+ .idea
keeptabs-0.0.2/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Thor Whalen
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,208 @@
1
+ Metadata-Version: 2.5
2
+ Name: keeptabs
3
+ Version: 0.0.2
4
+ Summary: Technology watch for people who work with AI agents: say what to follow, let a scheduled run collect what is new, ask what changed
5
+ Project-URL: Homepage, https://github.com/thorwhalen/keeptabs
6
+ Project-URL: Repository, https://github.com/thorwhalen/keeptabs
7
+ Project-URL: Documentation, https://thorwhalen.github.io/keeptabs
8
+ Author: Thor Whalen
9
+ License: mit
10
+ License-File: LICENSE
11
+ Keywords: agents,digest,horizon scanning,newsletter,rss,technology watch,veille
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: cw<0.2,>=0.1.1
14
+ Requires-Dist: dol
15
+ Requires-Dist: feedparser>=6.0
16
+ Requires-Dist: filelock>=3.12
17
+ Requires-Dist: pyyaml>=6.0
18
+ Provides-Extra: dev
19
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
20
+ Requires-Dist: pytest>=7.0; extra == 'dev'
21
+ Requires-Dist: ruff>=0.1.0; extra == 'dev'
22
+ Provides-Extra: docs
23
+ Requires-Dist: sphinx-rtd-theme>=1.0; extra == 'docs'
24
+ Requires-Dist: sphinx>=6.0; extra == 'docs'
25
+ Provides-Extra: mail
26
+ Requires-Dist: correspond>=0.0.8; extra == 'mail'
27
+ Description-Content-Type: text/markdown
28
+
29
+ # keeptabs
30
+
31
+ Keep tabs on the subjects you care about: say what to follow, let a scheduled run collect what is new, and ask what changed.
32
+
33
+ ```
34
+ pip install keeptabs
35
+ ```
36
+
37
+ This is technology watch, also called horizon scanning, and *veille* in French. It is built to be driven by an AI agent: the agent writes the specification with you, the package does the collecting, and an agent answers your questions from what was collected.
38
+
39
+ ## Quick start
40
+
41
+ ```bash
42
+ keeptabs init-watch "Generative AI" --example gen-ai --watch-id gen-ai
43
+ keeptabs tick
44
+ keeptabs whats-new gen-ai --as-text
45
+ ```
46
+
47
+ The first command creates a watch from a shipped example. The second fetches every source that is due, keeps what matches, and stores it. The third prints what is new, grouped by subtopic, with links.
48
+
49
+ In Python, by watch id:
50
+
51
+ ```python
52
+ from keeptabs import tools
53
+
54
+ tools.tick()
55
+ news = tools.whats_new("gen-ai", since="3d")
56
+ ```
57
+
58
+ Or with the stores in hand:
59
+
60
+ ```python
61
+ from keeptabs import watch_mall
62
+
63
+ mall = watch_mall("gen-ai") # stores: items, dropped, entities, runs, digests, state
64
+ recent = [item for item in mall["items"].values() if item["score"] >= 3]
65
+ ```
66
+
67
+ ## How it works
68
+
69
+ A **watch** is one subject you follow. Its specification is a YAML file that starts as a vague idea and gets sharper over time: a scope, subtopics with keywords, named things to track (models, libraries, companies), sources, and how often to report.
70
+
71
+ A **tick** is one run. It works out which sources are due from their stored state, fetches them, drops what it has already seen, scores each item against the specification, and stores what is relevant. It is safe to run as often as you like, so any scheduler can trigger it.
72
+
73
+ A **digest** is the answer to "what's new": the items acquired since the last one, grouped by subtopic. It is stored locally, and sent to the channels you chose only if you turned that on.
74
+
75
+ Everything is stored under `~/.local/share/keeptabs/`, in stores with a dictionary interface:
76
+
77
+ ```
78
+ specs/<watch id>.yaml
79
+ data/<watch id>/{items,dropped,entities,runs,digests,state}/<key>.json
80
+ ```
81
+
82
+ Set `KEEPTABS_ROOTDIR`, or pass `rootdir=`, to put it elsewhere.
83
+
84
+ ## Building a watch
85
+
86
+ ```bash
87
+ keeptabs init-watch "Music AI" --intent "real-time music generation and gesture control"
88
+ keeptabs add-keywords music-ai "real-time music generation, neural audio synthesis" --subtopic "Real-time generation" --priority high
89
+ keeptabs add-entity music-ai "Magenta RealTime" --kind model --aliases "Magenta RT"
90
+ keeptabs add-source music-ai arxiv 'cat:cs.SD AND all:"real-time"' --cadence 1d
91
+ keeptabs add-source music-ai github_releases magenta/magenta-realtime --keep-all
92
+ keeptabs add-source music-ai feed https://example.org/blog/feed.xml --cadence 12h
93
+ keeptabs tick --watch music-ai --force
94
+ ```
95
+
96
+ | Source kind | Target | Notes |
97
+ |---|---|---|
98
+ | `feed` | feed URL | RSS, Atom or JSON Feed, fetched conditionally |
99
+ | `arxiv` | arXiv query | newest first |
100
+ | `github_releases` | `owner/name` | releases of a repository |
101
+ | `hackernews` | search words | |
102
+ | `news_search` | search words | news articles |
103
+ | `email` | sender address | newsletters in a mailbox, read through [correspond](https://github.com/thorwhalen/correspond); needs `pip install 'keeptabs[mail]'` |
104
+
105
+ Some things only you can do, such as subscribing to a newsletter or providing a key. An agent records them with `keeptabs add-action`, the sources that depend on them are skipped until `keeptabs resolve-action`, and `keeptabs pending` lists what is waiting on you.
106
+
107
+ ## Asking
108
+
109
+ ```bash
110
+ keeptabs whats-new music-ai --since 3d --as-text
111
+ keeptabs items music-ai --query "latency" --entity magenta-realtime
112
+ keeptabs entities music-ai
113
+ keeptabs due # what runs next, what is failing
114
+ ```
115
+
116
+ Add `--json` to any command for the full result.
117
+
118
+ ## Scheduling
119
+
120
+ ```bash
121
+ keeptabs schedule # a launchd entry on macOS, a cron line elsewhere
122
+ keeptabs schedule --kind systemd
123
+ ```
124
+
125
+ It prints the entry and how to install it. It installs nothing.
126
+
127
+ ## Digests
128
+
129
+ In the specification:
130
+
131
+ ```yaml
132
+ digest:
133
+ cadence: 1w
134
+ channels:
135
+ - email:someone@example.org
136
+ - github:owner/repo#12 # a discussion
137
+ - slack: # webhook URL in KEEPTABS_SLACK_WEBHOOK_URL
138
+ - slack:team # webhook URL in KEEPTABS_SLACK_WEBHOOK_URL_TEAM
139
+ auto_send: false
140
+ ```
141
+
142
+ `keeptabs digest <watch>` is a dry run: it shows the digest and what would be sent where, and changes nothing. `keeptabs digest <watch> --send` sends that same digest, and from then on its items count as reported. The scheduled run writes the digest to the local store, and sends it only when `auto_send` is true. With channels and no `auto_send`, the items wait for your `--send`. Items count as reported only once every channel took the digest, so one that did not arrive is sent again. Email and GitHub go through `correspond`, so they pass its outbound checks.
143
+
144
+ What the items say was written by other people. Titles and summaries are escaped in a digest, and every link is built from a stored item's URL.
145
+
146
+ ## Agent skills
147
+
148
+ Two skills ship with the package, in `keeptabs/data/skills/`:
149
+
150
+ - `keeptabs-spec`: create and refine a watch with the user.
151
+ - `keeptabs-ask`: answer questions from what a watch collected.
152
+
153
+ ## Extending
154
+
155
+ Each part that you may want to replace is one keyword argument of `tick` or `make_digest`, with a default that works out of the box.
156
+
157
+ | Argument | Default | Replace it to |
158
+ |---|---|---|
159
+ | `rootdir=` | `~/.local/share/keeptabs` | keep the local files elsewhere |
160
+ | `specs=`, `malls=`, `lock=` | local files, a local file lock | store elsewhere, with any `MutableMapping` |
161
+ | `fetchers=`, `http_get=` | standard library HTTP, `feedparser` | add a source kind, or use another HTTP client |
162
+ | `matcher=` | whole-word keyword scoring | score with embeddings or a model, detect near-duplicates |
163
+ | `summarizer=` | Markdown, no model | write the digest with a model |
164
+ | `senders=` | `correspond`, a Slack webhook | add a delivery channel |
165
+
166
+ A source kind is any name that has a fetcher at run time. A kind of your own says what to fetch in its `target` field:
167
+
168
+ ```python
169
+ from keeptabs import tick
170
+
171
+
172
+ def fetch_my_api(source, *, state, http_get):
173
+ reply = http_get(f"https://api.example.org/new?q={source['target']}")
174
+ ...
175
+ return items, state # items: dicts with at least 'url' and 'title'
176
+
177
+
178
+ tick(fetchers={"my_api": fetch_my_api}) # for sources with kind: my_api
179
+ ```
180
+
181
+ A matcher receives the watch's stores, so it can compare an item with what is already there:
182
+
183
+ ```python
184
+ def matcher(item, spec, *, mall):
185
+ ...
186
+ return {
187
+ "score": 3.0,
188
+ "subtopics": [],
189
+ "entities": [],
190
+ "matched": [],
191
+ "duplicate_of": None,
192
+ }
193
+ ```
194
+
195
+ To keep everything in stores of your own, give both, and the run takes no local lock:
196
+
197
+ ```python
198
+ tick(specs=my_specs, malls=lambda watch_id: my_stores_for(watch_id))
199
+ ```
200
+
201
+ The command line and the shipped skills run with what `keeptabs.tools.components` returns, which is the one place to change for another surface.
202
+
203
+ ## What it does not do yet
204
+
205
+ - It does not discover new things to track by itself: an agent adds them with `add-entity`. A matcher of your own may name new things, which are stored as candidates.
206
+ - It matches by keywords. Near-duplicates under different URLs are stored separately.
207
+ - An item judged irrelevant is not judged again when the keywords change later. It is kept in the `dropped` store, with its score.
208
+ - Newsletter reading keeps one item per message, filtered by sender.
@@ -0,0 +1,180 @@
1
+ # keeptabs
2
+
3
+ Keep tabs on the subjects you care about: say what to follow, let a scheduled run collect what is new, and ask what changed.
4
+
5
+ ```
6
+ pip install keeptabs
7
+ ```
8
+
9
+ This is technology watch, also called horizon scanning, and *veille* in French. It is built to be driven by an AI agent: the agent writes the specification with you, the package does the collecting, and an agent answers your questions from what was collected.
10
+
11
+ ## Quick start
12
+
13
+ ```bash
14
+ keeptabs init-watch "Generative AI" --example gen-ai --watch-id gen-ai
15
+ keeptabs tick
16
+ keeptabs whats-new gen-ai --as-text
17
+ ```
18
+
19
+ The first command creates a watch from a shipped example. The second fetches every source that is due, keeps what matches, and stores it. The third prints what is new, grouped by subtopic, with links.
20
+
21
+ In Python, by watch id:
22
+
23
+ ```python
24
+ from keeptabs import tools
25
+
26
+ tools.tick()
27
+ news = tools.whats_new("gen-ai", since="3d")
28
+ ```
29
+
30
+ Or with the stores in hand:
31
+
32
+ ```python
33
+ from keeptabs import watch_mall
34
+
35
+ mall = watch_mall("gen-ai") # stores: items, dropped, entities, runs, digests, state
36
+ recent = [item for item in mall["items"].values() if item["score"] >= 3]
37
+ ```
38
+
39
+ ## How it works
40
+
41
+ A **watch** is one subject you follow. Its specification is a YAML file that starts as a vague idea and gets sharper over time: a scope, subtopics with keywords, named things to track (models, libraries, companies), sources, and how often to report.
42
+
43
+ A **tick** is one run. It works out which sources are due from their stored state, fetches them, drops what it has already seen, scores each item against the specification, and stores what is relevant. It is safe to run as often as you like, so any scheduler can trigger it.
44
+
45
+ A **digest** is the answer to "what's new": the items acquired since the last one, grouped by subtopic. It is stored locally, and sent to the channels you chose only if you turned that on.
46
+
47
+ Everything is stored under `~/.local/share/keeptabs/`, in stores with a dictionary interface:
48
+
49
+ ```
50
+ specs/<watch id>.yaml
51
+ data/<watch id>/{items,dropped,entities,runs,digests,state}/<key>.json
52
+ ```
53
+
54
+ Set `KEEPTABS_ROOTDIR`, or pass `rootdir=`, to put it elsewhere.
55
+
56
+ ## Building a watch
57
+
58
+ ```bash
59
+ keeptabs init-watch "Music AI" --intent "real-time music generation and gesture control"
60
+ keeptabs add-keywords music-ai "real-time music generation, neural audio synthesis" --subtopic "Real-time generation" --priority high
61
+ keeptabs add-entity music-ai "Magenta RealTime" --kind model --aliases "Magenta RT"
62
+ keeptabs add-source music-ai arxiv 'cat:cs.SD AND all:"real-time"' --cadence 1d
63
+ keeptabs add-source music-ai github_releases magenta/magenta-realtime --keep-all
64
+ keeptabs add-source music-ai feed https://example.org/blog/feed.xml --cadence 12h
65
+ keeptabs tick --watch music-ai --force
66
+ ```
67
+
68
+ | Source kind | Target | Notes |
69
+ |---|---|---|
70
+ | `feed` | feed URL | RSS, Atom or JSON Feed, fetched conditionally |
71
+ | `arxiv` | arXiv query | newest first |
72
+ | `github_releases` | `owner/name` | releases of a repository |
73
+ | `hackernews` | search words | |
74
+ | `news_search` | search words | news articles |
75
+ | `email` | sender address | newsletters in a mailbox, read through [correspond](https://github.com/thorwhalen/correspond); needs `pip install 'keeptabs[mail]'` |
76
+
77
+ Some things only you can do, such as subscribing to a newsletter or providing a key. An agent records them with `keeptabs add-action`, the sources that depend on them are skipped until `keeptabs resolve-action`, and `keeptabs pending` lists what is waiting on you.
78
+
79
+ ## Asking
80
+
81
+ ```bash
82
+ keeptabs whats-new music-ai --since 3d --as-text
83
+ keeptabs items music-ai --query "latency" --entity magenta-realtime
84
+ keeptabs entities music-ai
85
+ keeptabs due # what runs next, what is failing
86
+ ```
87
+
88
+ Add `--json` to any command for the full result.
89
+
90
+ ## Scheduling
91
+
92
+ ```bash
93
+ keeptabs schedule # a launchd entry on macOS, a cron line elsewhere
94
+ keeptabs schedule --kind systemd
95
+ ```
96
+
97
+ It prints the entry and how to install it. It installs nothing.
98
+
99
+ ## Digests
100
+
101
+ In the specification:
102
+
103
+ ```yaml
104
+ digest:
105
+ cadence: 1w
106
+ channels:
107
+ - email:someone@example.org
108
+ - github:owner/repo#12 # a discussion
109
+ - slack: # webhook URL in KEEPTABS_SLACK_WEBHOOK_URL
110
+ - slack:team # webhook URL in KEEPTABS_SLACK_WEBHOOK_URL_TEAM
111
+ auto_send: false
112
+ ```
113
+
114
+ `keeptabs digest <watch>` is a dry run: it shows the digest and what would be sent where, and changes nothing. `keeptabs digest <watch> --send` sends that same digest, and from then on its items count as reported. The scheduled run writes the digest to the local store, and sends it only when `auto_send` is true. With channels and no `auto_send`, the items wait for your `--send`. Items count as reported only once every channel took the digest, so one that did not arrive is sent again. Email and GitHub go through `correspond`, so they pass its outbound checks.
115
+
116
+ What the items say was written by other people. Titles and summaries are escaped in a digest, and every link is built from a stored item's URL.
117
+
118
+ ## Agent skills
119
+
120
+ Two skills ship with the package, in `keeptabs/data/skills/`:
121
+
122
+ - `keeptabs-spec`: create and refine a watch with the user.
123
+ - `keeptabs-ask`: answer questions from what a watch collected.
124
+
125
+ ## Extending
126
+
127
+ Each part that you may want to replace is one keyword argument of `tick` or `make_digest`, with a default that works out of the box.
128
+
129
+ | Argument | Default | Replace it to |
130
+ |---|---|---|
131
+ | `rootdir=` | `~/.local/share/keeptabs` | keep the local files elsewhere |
132
+ | `specs=`, `malls=`, `lock=` | local files, a local file lock | store elsewhere, with any `MutableMapping` |
133
+ | `fetchers=`, `http_get=` | standard library HTTP, `feedparser` | add a source kind, or use another HTTP client |
134
+ | `matcher=` | whole-word keyword scoring | score with embeddings or a model, detect near-duplicates |
135
+ | `summarizer=` | Markdown, no model | write the digest with a model |
136
+ | `senders=` | `correspond`, a Slack webhook | add a delivery channel |
137
+
138
+ A source kind is any name that has a fetcher at run time. A kind of your own says what to fetch in its `target` field:
139
+
140
+ ```python
141
+ from keeptabs import tick
142
+
143
+
144
+ def fetch_my_api(source, *, state, http_get):
145
+ reply = http_get(f"https://api.example.org/new?q={source['target']}")
146
+ ...
147
+ return items, state # items: dicts with at least 'url' and 'title'
148
+
149
+
150
+ tick(fetchers={"my_api": fetch_my_api}) # for sources with kind: my_api
151
+ ```
152
+
153
+ A matcher receives the watch's stores, so it can compare an item with what is already there:
154
+
155
+ ```python
156
+ def matcher(item, spec, *, mall):
157
+ ...
158
+ return {
159
+ "score": 3.0,
160
+ "subtopics": [],
161
+ "entities": [],
162
+ "matched": [],
163
+ "duplicate_of": None,
164
+ }
165
+ ```
166
+
167
+ To keep everything in stores of your own, give both, and the run takes no local lock:
168
+
169
+ ```python
170
+ tick(specs=my_specs, malls=lambda watch_id: my_stores_for(watch_id))
171
+ ```
172
+
173
+ The command line and the shipped skills run with what `keeptabs.tools.components` returns, which is the one place to change for another surface.
174
+
175
+ ## What it does not do yet
176
+
177
+ - It does not discover new things to track by itself: an agent adds them with `add-entity`. A matcher of your own may name new things, which are stored as candidates.
178
+ - It matches by keywords. Near-duplicates under different URLs are stored separately.
179
+ - An item judged irrelevant is not judged again when the keywords change later. It is kept in the `dropped` store, with its score.
180
+ - Newsletter reading keeps one item per message, filtered by sender.
@@ -0,0 +1,51 @@
1
+ """Keep tabs on the subjects you care about (technology watch; in French, "veille").
2
+
3
+ Describe what to follow as watch specifications, let a scheduled ``tick`` acquire
4
+ and match what is new, and ask "what's new" whenever you like.
5
+
6
+ By watch id, with everything on its default (this is what the command line runs):
7
+
8
+ >>> from keeptabs import tools
9
+ >>> tools.tick() # doctest: +SKIP
10
+ >>> tools.whats_new('gen-ai', since='3d') # doctest: +SKIP
11
+
12
+ With parts of your own (stores, fetchers, a matcher, a summarizer, senders):
13
+
14
+ >>> from keeptabs import tick, whats_new, make_digest # doctest: +SKIP
15
+ """
16
+
17
+ from keeptabs import tools
18
+ from keeptabs.digest import (
19
+ deliver,
20
+ escape_text,
21
+ make_digest,
22
+ render_markdown,
23
+ scheduled_digest,
24
+ whats_new,
25
+ )
26
+ from keeptabs.engine import AlreadyRunning, tick
27
+ from keeptabs.fetchers import DEFAULT_FETCHERS, Response, http_get
28
+ from keeptabs.matching import keyword_matcher
29
+ from keeptabs.spec import SpecError, normalize_spec
30
+ from keeptabs.stores import memory_mall, spec_store, watch_mall
31
+
32
+ __all__ = [
33
+ "AlreadyRunning",
34
+ "DEFAULT_FETCHERS",
35
+ "Response",
36
+ "SpecError",
37
+ "deliver",
38
+ "escape_text",
39
+ "http_get",
40
+ "keyword_matcher",
41
+ "make_digest",
42
+ "memory_mall",
43
+ "normalize_spec",
44
+ "render_markdown",
45
+ "scheduled_digest",
46
+ "spec_store",
47
+ "tick",
48
+ "tools",
49
+ "watch_mall",
50
+ "whats_new",
51
+ ]
@@ -0,0 +1,77 @@
1
+ """The ``keeptabs`` command: one sub-command per function in :data:`keeptabs.tools.TOOLS`."""
2
+
3
+ import json
4
+ import sys
5
+
6
+ import cw
7
+
8
+ from keeptabs import tools
9
+ from keeptabs.engine import AlreadyRunning
10
+ from keeptabs.spec import SpecError
11
+
12
+ #: What a user can cause, and fix: shown as one line, with no traceback.
13
+ USER_ERRORS = (SpecError, AlreadyRunning, KeyError, ValueError, FileNotFoundError)
14
+
15
+
16
+ def _guarded(tool):
17
+ """The tool, returning a failed result where it would raise a user error."""
18
+ import functools
19
+
20
+ @functools.wraps(tool)
21
+ def guarded(*args, **kwargs):
22
+ try:
23
+ return tool(*args, **kwargs)
24
+ except USER_ERRORS as error:
25
+ message = (
26
+ error.args[0] if isinstance(error, KeyError) and error.args else error
27
+ )
28
+ return {
29
+ "ok": False,
30
+ "error": type(error).__name__,
31
+ "text": f"keeptabs: {message}",
32
+ }
33
+
34
+ return guarded
35
+
36
+
37
+ def _egress(as_json):
38
+ def egress(result, *, out, err):
39
+ failed = isinstance(result, dict) and not result.get("ok", True)
40
+ if (
41
+ not as_json
42
+ and isinstance(result, dict)
43
+ and isinstance(result.get("text"), str)
44
+ ):
45
+ print(result["text"], file=err if failed and "error" in result else out)
46
+ else:
47
+ print(
48
+ json.dumps(result, indent=2, ensure_ascii=False, default=str), file=out
49
+ )
50
+ return 0 if not isinstance(result, dict) or result.get("ok", True) else 1
51
+
52
+ return egress
53
+
54
+
55
+ def main(argv=None):
56
+ """Run one ``keeptabs`` command. ``--json`` prints the full result as JSON."""
57
+ for stream in (
58
+ sys.stdout,
59
+ sys.stderr,
60
+ ): # a cp1252 console must not crash on a title
61
+ getattr(stream, "reconfigure", lambda **_: None)(errors="backslashreplace")
62
+ argv = list(sys.argv[1:] if argv is None else argv)
63
+ as_json = "--json" in argv
64
+ commands = {tool.__name__.replace("_", "-"): _guarded(tool) for tool in tools.TOOLS}
65
+ raise SystemExit(
66
+ cw.dispatch(
67
+ commands,
68
+ [a for a in argv if a != "--json"],
69
+ prog="keeptabs",
70
+ convention=cw.MODERN,
71
+ egress=_egress(as_json),
72
+ )
73
+ )
74
+
75
+
76
+ if __name__ == "__main__":
77
+ main()