notefeed 0.2.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.
notefeed/__init__.py ADDED
@@ -0,0 +1,9 @@
1
+ """Post markdown notes to a notefeed server."""
2
+
3
+ from importlib.metadata import version as _version
4
+
5
+ __version__ = _version("notefeed")
6
+
7
+ from .client import AuthError, Client, ConfigError, InvalidNoteError, Note, NotefeedError, NoteTooLargeError # noqa: E402
8
+
9
+ __all__ = ["AuthError", "Client", "ConfigError", "InvalidNoteError", "Note", "NotefeedError", "NoteTooLargeError"]
notefeed/cli.py ADDED
@@ -0,0 +1,63 @@
1
+ """`notefeed post ...` — post a note from the command line."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import os
7
+ import sys
8
+
9
+ from . import __version__
10
+ from .client import Client, ConfigError, NotefeedError
11
+
12
+
13
+ def main(argv: list[str] | None = None) -> int:
14
+ parser = argparse.ArgumentParser(prog="notefeed", description="Post markdown notes to notefeed.")
15
+ parser.add_argument("--version", action="version", version=f"notefeed {__version__}")
16
+ sub = parser.add_subparsers(dest="command", required=True)
17
+ p = sub.add_parser("post", help="post a note; prints its URL")
18
+ p.add_argument("text", nargs="?", help='the markdown, or "-" to read stdin')
19
+ p.add_argument("--file", help="read the markdown from this file")
20
+ p.add_argument("--url", help="notefeed base URL (default: $NOTEFEED_URL)")
21
+ p.add_argument("--token", help="API token (default: $NOTEFEED_TOKEN)")
22
+ args = parser.parse_args(argv)
23
+
24
+ try:
25
+ markdown = _read(args)
26
+ url = args.url or os.environ.get("NOTEFEED_URL")
27
+ token = args.token or os.environ.get("NOTEFEED_TOKEN")
28
+ if not url:
29
+ raise _UsageError("no URL given; pass --url or set NOTEFEED_URL")
30
+ if not token:
31
+ raise _UsageError("no token given; pass --token or set NOTEFEED_TOKEN")
32
+ note = Client(url, token).post(markdown)
33
+ except (ConfigError, _UsageError) as e:
34
+ print(f"notefeed: {e}", file=sys.stderr)
35
+ return 2
36
+ except NotefeedError as e:
37
+ print(f"notefeed: {e}", file=sys.stderr)
38
+ return 1
39
+ print(note.url)
40
+ return 0
41
+
42
+
43
+ class _UsageError(Exception):
44
+ pass
45
+
46
+
47
+ def _read(args: argparse.Namespace) -> str:
48
+ if args.file:
49
+ try:
50
+ with open(args.file, "rb") as f:
51
+ return f.read().decode("utf-8")
52
+ except OSError as e:
53
+ raise _UsageError(f"cannot read {args.file}: {e.strerror}") from None
54
+ except UnicodeDecodeError:
55
+ raise _UsageError(f"{args.file} is not UTF-8") from None
56
+ if args.text == "-":
57
+ try:
58
+ return sys.stdin.buffer.read().decode("utf-8")
59
+ except UnicodeDecodeError:
60
+ raise _UsageError("stdin is not UTF-8") from None
61
+ if args.text is None:
62
+ raise _UsageError('give the note text, "-" for stdin, or --file PATH')
63
+ return args.text
notefeed/client.py ADDED
@@ -0,0 +1,93 @@
1
+ """A tiny client for notefeed's POST /api/notes. Standard library only."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import http.client
6
+ import json
7
+ import re
8
+ import urllib.error
9
+ import urllib.request
10
+ from dataclasses import dataclass
11
+
12
+
13
+ @dataclass(frozen=True)
14
+ class Note:
15
+ id: str
16
+ url: str
17
+
18
+
19
+ class NotefeedError(Exception):
20
+ """Any failure talking to notefeed. `status` is the HTTP status, or None (network, config)."""
21
+
22
+ def __init__(self, message: str, status: int | None = None):
23
+ super().__init__(message)
24
+ self.status = status
25
+
26
+
27
+ class ConfigError(NotefeedError):
28
+ """URL or token missing."""
29
+
30
+
31
+ class InvalidNoteError(NotefeedError):
32
+ """The server rejected the note (400, 415): empty, not UTF-8, wrong type."""
33
+
34
+
35
+ class AuthError(NotefeedError):
36
+ """Missing or wrong token (401)."""
37
+
38
+
39
+ class NoteTooLargeError(NotefeedError):
40
+ """The note is over the server's size limit (413)."""
41
+
42
+
43
+ _ERRORS = {400: InvalidNoteError, 415: InvalidNoteError, 401: AuthError, 413: NoteTooLargeError}
44
+
45
+
46
+ class Client:
47
+ """A notefeed server. URL and token are set once here; post() takes only the note."""
48
+
49
+ def __init__(self, url: str, token: str, timeout: float = 10.0):
50
+ if not url:
51
+ raise ConfigError("no url given")
52
+ if not (token or "").strip():
53
+ raise ConfigError("no token given")
54
+ self.url = url.rstrip("/")
55
+ self.token = token.strip()
56
+ if re.search(r"[\x00-\x1f\x7f]", self.token):
57
+ # Never echo the value: it would end up in terminals and CI logs.
58
+ raise ConfigError("token contains invalid characters")
59
+ self.timeout = timeout
60
+
61
+ def post(self, markdown: str) -> Note:
62
+ req = urllib.request.Request(
63
+ f"{self.url}/api/notes",
64
+ data=markdown.encode("utf-8"),
65
+ method="POST",
66
+ headers={
67
+ "Authorization": f"Bearer {self.token}",
68
+ "Content-Type": "text/markdown; charset=utf-8",
69
+ },
70
+ )
71
+ try:
72
+ with urllib.request.urlopen(req, timeout=self.timeout) as res:
73
+ status, text = res.status, res.read().decode("utf-8", errors="replace")
74
+ except urllib.error.HTTPError as e:
75
+ raise _http_error(e) from None
76
+ except (urllib.error.URLError, http.client.HTTPException, OSError) as e:
77
+ reason = getattr(e, "reason", e)
78
+ raise NotefeedError(f"could not reach {self.url}: {reason}") from None
79
+ try:
80
+ data = json.loads(text)
81
+ return Note(id=data["id"], url=data["url"])
82
+ except (ValueError, KeyError, TypeError):
83
+ raise NotefeedError(f"unexpected response from {self.url} (not a notefeed server?)", status=status) from None
84
+
85
+
86
+ def _http_error(e: urllib.error.HTTPError) -> NotefeedError:
87
+ text = e.read().decode("utf-8", errors="replace")
88
+ try:
89
+ message = json.loads(text)["error"]
90
+ except (ValueError, KeyError, TypeError):
91
+ message = f"HTTP {e.code}: {' '.join(text[:200].split())}"
92
+ return _ERRORS.get(e.code, NotefeedError)(message, status=e.code)
93
+
@@ -0,0 +1,37 @@
1
+ Metadata-Version: 2.5
2
+ Name: notefeed
3
+ Version: 0.2.0
4
+ Summary: Post markdown notes to a notefeed server, from Python or the command line.
5
+ Project-URL: Documentation, https://marceltov.github.io/notefeed/clients/
6
+ Project-URL: Source, https://github.com/Marceltov/notefeed
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Environment :: Console
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Communications
12
+ Requires-Python: >=3.10
13
+ Provides-Extra: test
14
+ Requires-Dist: pytest>=9; extra == 'test'
15
+ Description-Content-Type: text/markdown
16
+
17
+ # notefeed
18
+
19
+ Post markdown notes to a [notefeed](https://github.com/Marceltov/notefeed) server from Python or the command line. No dependencies.
20
+
21
+ ```sh
22
+ pip install notefeed
23
+ export NOTEFEED_URL=https://notes.example.com NOTEFEED_TOKEN=...
24
+ notefeed post "# Backup finished"
25
+ backup.sh 2>&1 | notefeed post -
26
+ ```
27
+
28
+ ```python
29
+ from notefeed import Client
30
+
31
+ client = Client("https://notes.example.com", token) # URL and token set once
32
+ print(client.post("# Deploy done\nversion 1.4.2").url)
33
+ ```
34
+
35
+ The `notefeed` command reads `--url` / `--token`, or `NOTEFEED_URL` / `NOTEFEED_TOKEN`. The library itself never reads the environment.
36
+
37
+ Full documentation: https://marceltov.github.io/notefeed/clients/
@@ -0,0 +1,8 @@
1
+ notefeed/__init__.py,sha256=qSEeqQcY7rIJ3v-9kj99yumUxX460Fsa9smY6k9xKCw,376
2
+ notefeed/cli.py,sha256=sUguAVOKjzRPqGxq8wELdKCaIBE8V7tZhtr9BJkyE-M,2333
3
+ notefeed/client.py,sha256=AqetedMythSXlBJaCRoYQF0PVOThAAoYaqXU5uAZKLs,3105
4
+ notefeed-0.2.0.dist-info/METADATA,sha256=myr8D0NiFkLNFC1jTnwGuXzxQZOzaSWtN7b1QWbmEk8,1251
5
+ notefeed-0.2.0.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
6
+ notefeed-0.2.0.dist-info/entry_points.txt,sha256=jT3tEJPxh9CT7uxnmCxNgl3Spjutk6wE9mpRFBDQto4,47
7
+ notefeed-0.2.0.dist-info/licenses/LICENSE,sha256=AhfRnZW5Yfi9VuESZGyPTziynbdP9kNMOtCykeDpAyw,1072
8
+ notefeed-0.2.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.4
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ notefeed = notefeed.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcel Bruckner
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.