prettynb 0.13.0__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.
Files changed (127) hide show
  1. prettynb-0.13.0/LICENSE +22 -0
  2. prettynb-0.13.0/MANIFEST.in +1 -0
  3. prettynb-0.13.0/PKG-INFO +72 -0
  4. prettynb-0.13.0/README.md +50 -0
  5. prettynb-0.13.0/docs/prettynb.md +49 -0
  6. prettynb-0.13.0/pyproject.toml +64 -0
  7. prettynb-0.13.0/setup.cfg +4 -0
  8. prettynb-0.13.0/src/prettynb/__init__.py +7 -0
  9. prettynb-0.13.0/src/prettynb/_internal/__init__.py +1 -0
  10. prettynb-0.13.0/src/prettynb/_internal/backups.py +327 -0
  11. prettynb-0.13.0/src/prettynb/_internal/cli_tools.py +48 -0
  12. prettynb-0.13.0/src/prettynb/_internal/containers.py +103 -0
  13. prettynb-0.13.0/src/prettynb/_internal/deployment.py +194 -0
  14. prettynb-0.13.0/src/prettynb/_internal/diagnostics.py +49 -0
  15. prettynb-0.13.0/src/prettynb/_internal/http.py +37 -0
  16. prettynb-0.13.0/src/prettynb/_internal/icons.py +51 -0
  17. prettynb-0.13.0/src/prettynb/_internal/identities.py +295 -0
  18. prettynb-0.13.0/src/prettynb/_internal/journal.py +305 -0
  19. prettynb-0.13.0/src/prettynb/_internal/legacy_rendering.py +167 -0
  20. prettynb-0.13.0/src/prettynb/_internal/links.py +184 -0
  21. prettynb-0.13.0/src/prettynb/_internal/moves.py +168 -0
  22. prettynb-0.13.0/src/prettynb/_internal/navigation.py +234 -0
  23. prettynb-0.13.0/src/prettynb/_internal/operation_logs.py +97 -0
  24. prettynb-0.13.0/src/prettynb/_internal/publication_execute.py +125 -0
  25. prettynb-0.13.0/src/prettynb/_internal/publication_plan.py +296 -0
  26. prettynb-0.13.0/src/prettynb/_internal/publication_state.py +111 -0
  27. prettynb-0.13.0/src/prettynb/_internal/publishing.py +449 -0
  28. prettynb-0.13.0/src/prettynb/_internal/rendering.py +49 -0
  29. prettynb-0.13.0/src/prettynb/_internal/routes.py +88 -0
  30. prettynb-0.13.0/src/prettynb/_internal/search.py +113 -0
  31. prettynb-0.13.0/src/prettynb/_internal/storage.py +271 -0
  32. prettynb-0.13.0/src/prettynb/_internal/web_state.py +99 -0
  33. prettynb-0.13.0/src/prettynb/appearance.py +63 -0
  34. prettynb-0.13.0/src/prettynb/cli.py +510 -0
  35. prettynb-0.13.0/src/prettynb/commands/__init__.py +0 -0
  36. prettynb-0.13.0/src/prettynb/commands/code.py +161 -0
  37. prettynb-0.13.0/src/prettynb/commands/collect.py +249 -0
  38. prettynb-0.13.0/src/prettynb/commands/commit.py +274 -0
  39. prettynb-0.13.0/src/prettynb/commands/correct.py +234 -0
  40. prettynb-0.13.0/src/prettynb/commands/deploy.py +111 -0
  41. prettynb-0.13.0/src/prettynb/commands/graph.py +189 -0
  42. prettynb-0.13.0/src/prettynb/commands/logs.py +17 -0
  43. prettynb-0.13.0/src/prettynb/commands/pprint.py +91 -0
  44. prettynb-0.13.0/src/prettynb/commands/subl.py +75 -0
  45. prettynb-0.13.0/src/prettynb/commands/tasks.py +323 -0
  46. prettynb-0.13.0/src/prettynb/helpers/__init__.py +2 -0
  47. prettynb-0.13.0/src/prettynb/helpers/_datetime.py +26 -0
  48. prettynb-0.13.0/src/prettynb/helpers/wrappers.py +77 -0
  49. prettynb-0.13.0/src/prettynb/markdown/__init__.py +31 -0
  50. prettynb-0.13.0/src/prettynb/markdown/dialect.py +8 -0
  51. prettynb-0.13.0/src/prettynb/markdown/inlines.py +11 -0
  52. prettynb-0.13.0/src/prettynb/markdown/nodes.py +49 -0
  53. prettynb-0.13.0/src/prettynb/markdown/parser.py +11 -0
  54. prettynb-0.13.0/src/prettynb/markdown/renderers.py +200 -0
  55. prettynb-0.13.0/src/prettynb/models/__init__.py +4 -0
  56. prettynb-0.13.0/src/prettynb/models/components/__init__.py +13 -0
  57. prettynb-0.13.0/src/prettynb/models/components/codeblock.py +123 -0
  58. prettynb-0.13.0/src/prettynb/models/components/component.py +79 -0
  59. prettynb-0.13.0/src/prettynb/models/components/link.py +252 -0
  60. prettynb-0.13.0/src/prettynb/models/components/tag.py +72 -0
  61. prettynb-0.13.0/src/prettynb/models/components/url.py +104 -0
  62. prettynb-0.13.0/src/prettynb/models/note.py +504 -0
  63. prettynb-0.13.0/src/prettynb/models/notebook.py +639 -0
  64. prettynb-0.13.0/src/prettynb/resources/deploy/checkpoint.py.tmpl +42 -0
  65. prettynb-0.13.0/src/prettynb/resources/deploy/common.sh.tmpl +56 -0
  66. prettynb-0.13.0/src/prettynb/resources/deploy/environment.example.tmpl +10 -0
  67. prettynb-0.13.0/src/prettynb/resources/deploy/init.sh.tmpl +29 -0
  68. prettynb-0.13.0/src/prettynb/resources/deploy/nginx.conf.tmpl +33 -0
  69. prettynb-0.13.0/src/prettynb/resources/deploy/rollback.sh.tmpl +27 -0
  70. prettynb-0.13.0/src/prettynb/resources/deploy/service.tmpl +25 -0
  71. prettynb-0.13.0/src/prettynb/resources/deploy/upgrade.sh.tmpl +36 -0
  72. prettynb-0.13.0/src/prettynb/settings.py +402 -0
  73. prettynb-0.13.0/src/prettynb.egg-info/PKG-INFO +72 -0
  74. prettynb-0.13.0/src/prettynb.egg-info/SOURCES.txt +125 -0
  75. prettynb-0.13.0/src/prettynb.egg-info/dependency_links.txt +1 -0
  76. prettynb-0.13.0/src/prettynb.egg-info/entry_points.txt +2 -0
  77. prettynb-0.13.0/src/prettynb.egg-info/requires.txt +7 -0
  78. prettynb-0.13.0/src/prettynb.egg-info/top_level.txt +1 -0
  79. prettynb-0.13.0/tests/fixtures/markdown/NOTICE.md +11 -0
  80. prettynb-0.13.0/tests/fixtures/markdown/commonmark-blocks.json +1794 -0
  81. prettynb-0.13.0/tests/fixtures/markdown/commonmark-inlines.json +3426 -0
  82. prettynb-0.13.0/tests/test_appearance.py +49 -0
  83. prettynb-0.13.0/tests/test_backups.py +220 -0
  84. prettynb-0.13.0/tests/test_checked_publication_execution.py +306 -0
  85. prettynb-0.13.0/tests/test_cleanup_contracts.py +108 -0
  86. prettynb-0.13.0/tests/test_cli_collections.py +64 -0
  87. prettynb-0.13.0/tests/test_cli_interface.py +97 -0
  88. prettynb-0.13.0/tests/test_code_extraction.py +173 -0
  89. prettynb-0.13.0/tests/test_component_semantics.py +62 -0
  90. prettynb-0.13.0/tests/test_config_contracts.py +159 -0
  91. prettynb-0.13.0/tests/test_containers.py +71 -0
  92. prettynb-0.13.0/tests/test_current_content.py +75 -0
  93. prettynb-0.13.0/tests/test_deploy.py +174 -0
  94. prettynb-0.13.0/tests/test_diagnostics.py +79 -0
  95. prettynb-0.13.0/tests/test_empty_sections.py +44 -0
  96. prettynb-0.13.0/tests/test_favicon_client.py +104 -0
  97. prettynb-0.13.0/tests/test_git_automation.py +212 -0
  98. prettynb-0.13.0/tests/test_hash_publication_plans.py +235 -0
  99. prettynb-0.13.0/tests/test_http_client.py +115 -0
  100. prettynb-0.13.0/tests/test_icons.py +56 -0
  101. prettynb-0.13.0/tests/test_identities.py +281 -0
  102. prettynb-0.13.0/tests/test_links.py +118 -0
  103. prettynb-0.13.0/tests/test_local_operation_logs.py +127 -0
  104. prettynb-0.13.0/tests/test_lookup.py +63 -0
  105. prettynb-0.13.0/tests/test_markdown_adoption.py +81 -0
  106. prettynb-0.13.0/tests/test_markdown_blocks.py +136 -0
  107. prettynb-0.13.0/tests/test_markdown_builders.py +91 -0
  108. prettynb-0.13.0/tests/test_markdown_dialect.py +160 -0
  109. prettynb-0.13.0/tests/test_markdown_inlines.py +98 -0
  110. prettynb-0.13.0/tests/test_markdown_migration.py +185 -0
  111. prettynb-0.13.0/tests/test_moves.py +311 -0
  112. prettynb-0.13.0/tests/test_namespace.py +30 -0
  113. prettynb-0.13.0/tests/test_navigation.py +262 -0
  114. prettynb-0.13.0/tests/test_note_commands.py +170 -0
  115. prettynb-0.13.0/tests/test_note_io.py +155 -0
  116. prettynb-0.13.0/tests/test_note_state.py +95 -0
  117. prettynb-0.13.0/tests/test_protected_text.py +118 -0
  118. prettynb-0.13.0/tests/test_publication_eligibility.py +93 -0
  119. prettynb-0.13.0/tests/test_publication_preflight.py +145 -0
  120. prettynb-0.13.0/tests/test_publication_sync.py +327 -0
  121. prettynb-0.13.0/tests/test_rendering.py +155 -0
  122. prettynb-0.13.0/tests/test_routes.py +117 -0
  123. prettynb-0.13.0/tests/test_search.py +120 -0
  124. prettynb-0.13.0/tests/test_settings.py +291 -0
  125. prettynb-0.13.0/tests/test_smoke.py +28 -0
  126. prettynb-0.13.0/tests/test_tasks.py +143 -0
  127. prettynb-0.13.0/tests/test_terminal_markdown.py +78 -0
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 prettynb
4
+ Copyright (c) 2026 wispsy
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ recursive-include tests/fixtures/markdown *.json *.md
@@ -0,0 +1,72 @@
1
+ Metadata-Version: 2.4
2
+ Name: prettynb
3
+ Version: 0.13.0
4
+ Summary: Python tools for parsing and querying wiki-linked, tagged Markdown notebooks.
5
+ Author: prettynb
6
+ Maintainer: wispsy
7
+ License-Expression: MIT
8
+ Project-URL: Homepage, https://wispsy.com
9
+ Project-URL: Repository, https://github.com/wispsy/prettynb
10
+ Project-URL: Documentation, https://github.com/wispsy/prettynb/tree/v0.13.0/docs
11
+ Project-URL: Issues, https://github.com/wispsy/prettynb/issues
12
+ Keywords: markdown,notes,wikilinks,knowledge-management
13
+ Requires-Python: >=3.14
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Requires-Dist: expose-interface<0.2,>=0.1.0
17
+ Requires-Dist: requ<0.3,>=0.2.0
18
+ Requires-Dist: parse-md<0.2,>=0.1.0
19
+ Requires-Dist: escape-colors[markdown]<0.4,>=0.3.0
20
+ Provides-Extra: legacy-markdown
21
+ Requires-Dist: markdown>=3.3.4; extra == "legacy-markdown"
22
+ Dynamic: license-file
23
+
24
+ # prettynb
25
+
26
+ <p align="center">
27
+ <img src="https://raw.githubusercontent.com/wispsy/prettynb/v0.13.0/docs/_static/prettynb.jpg" alt="prettynb" width="320">
28
+ </p>
29
+
30
+ A pretty notebook engine for interconnected Markdown notes, with a Python
31
+ library, command-line interface and optional Expose API web publisher.
32
+
33
+ The distribution, Python package and executable share one name: `prettynb`.
34
+ Python 3.14 or newer is required.
35
+
36
+ ```sh
37
+ python -m pip install prettynb==0.13.0
38
+ prettynb --help
39
+ ```
40
+
41
+ ```python
42
+ from prettynb import Notebook, Note
43
+
44
+ nb = Notebook.open("~/notes", settings={"NOTE_NESTED": "recurs"})
45
+ note = nb.get("guides/overview", fuzzy=False)
46
+ ```
47
+
48
+ A notebook is an existing directory of Markdown files. Notes have explicit
49
+ wiki-link, tag, code-block and URL models; Markdown remains the authoritative
50
+ content. The library provides stable note identities, checked saves and renames,
51
+ publication plans, search, navigation, local rendering and durable operation logs.
52
+
53
+ Opening reads files without prompting or creating configuration. Initialize
54
+ explicitly with `prettynb init PATH`; configuration and private state live under
55
+ `.prettynb/`. `NOTE_PATH` selects the notebook for environment-based use.
56
+
57
+ This is a breaking rename with no legacy import, executable or configuration
58
+ aliases. See the [namespace guide](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/package-migration.md)
59
+ before switching existing installations.
60
+
61
+ - [Workflow tutorial](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/tutorials.md)
62
+ - [Settings and profiles](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/settings.md)
63
+ - [API and CLI reference](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/reference.md)
64
+ - [Checked publishing](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/checked-publishing.md)
65
+ - [Web deployment](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/web.md)
66
+ - [Source and issue queue](https://github.com/wispsy/prettynb)
67
+
68
+ The web publisher runs from a checkout and is separate from the core wheel.
69
+ Its supported profile is one Gunicorn instance with 1–4 coordinated workers,
70
+ one local SQLite database, trusted editors and a TLS reverse proxy. Hosted
71
+ activation and the experimental macOS URL handlers remain separate from the
72
+ core package contract.
@@ -0,0 +1,50 @@
1
+ # prettynb
2
+
3
+ <p align="center">
4
+ <img src="docs/_static/prettynb.jpg" alt="prettynb" width="320">
5
+ </p>
6
+
7
+ A pretty notebook engine for interconnected Markdown notes: a Python library,
8
+ a command-line interface, and an optional Expose API web publisher.
9
+
10
+ `prettynb` is the single name for the repository, PyPI distribution, Python
11
+ package and executable. Python 3.14 or newer is required.
12
+
13
+ ```sh
14
+ python -m pip install prettynb==0.13.0
15
+ prettynb --help
16
+ ```
17
+
18
+ ```python
19
+ from prettynb import Notebook, Note
20
+
21
+ nb = Notebook.open("~/notes", settings={"NOTE_NESTED": "recurs"})
22
+ ```
23
+
24
+ A notebook is an existing directory of Markdown files. Wiki links, tags, stable
25
+ note identities, pending edits, checked publication, search, navigation, appearance
26
+ preferences and operation logs build on those files. Opening a notebook reads
27
+ its contents; use `prettynb init PATH` to create `.prettynb` configuration and state.
28
+
29
+ The namespace rename is a breaking boundary. Legacy imports, commands,
30
+ configuration names and transition distributions are removed. Read the
31
+ [package migration guide](docs/package-migration.md) before switching an existing
32
+ installation or preparing a new web deployment.
33
+
34
+ The `apps/web` publisher supports one Gunicorn instance with up to four coordinated
35
+ workers, one local SQLite database, explicitly owned public notebooks and a TLS
36
+ reverse proxy. The web application is run from a checkout and is separate from
37
+ the core wheel. Read the [deployment contract](docs/web.md) before exposing it.
38
+ The experimental macOS URL handlers remain unsupported.
39
+
40
+ [Documentation](docs/index.md) · [Tutorial](docs/tutorials.md) · [API and CLI](docs/reference.md) · [0.13.0 release notes](docs/release-0.13.0.md) · [Versions](docs/versions.md) · [Roadmap](docs/roadmap.md)
41
+
42
+ ```mermaid
43
+ graph BT
44
+ Notebook[(Notebook)]
45
+ Note[(Note)] --> Notebook
46
+ Link --> Note
47
+ Url --> Note
48
+ CodeBlock --> Note
49
+ Tag --> Note
50
+ ```
@@ -0,0 +1,49 @@
1
+ # prettynb
2
+
3
+ <p align="center">
4
+ <img src="https://raw.githubusercontent.com/wispsy/prettynb/v0.13.0/docs/_static/prettynb.jpg" alt="prettynb" width="320">
5
+ </p>
6
+
7
+ A pretty notebook engine for interconnected Markdown notes, with a Python
8
+ library, command-line interface and optional Expose API web publisher.
9
+
10
+ The distribution, Python package and executable share one name: `prettynb`.
11
+ Python 3.14 or newer is required.
12
+
13
+ ```sh
14
+ python -m pip install prettynb==0.13.0
15
+ prettynb --help
16
+ ```
17
+
18
+ ```python
19
+ from prettynb import Notebook, Note
20
+
21
+ nb = Notebook.open("~/notes", settings={"NOTE_NESTED": "recurs"})
22
+ note = nb.get("guides/overview", fuzzy=False)
23
+ ```
24
+
25
+ A notebook is an existing directory of Markdown files. Notes have explicit
26
+ wiki-link, tag, code-block and URL models; Markdown remains the authoritative
27
+ content. The library provides stable note identities, checked saves and renames,
28
+ publication plans, search, navigation, local rendering and durable operation logs.
29
+
30
+ Opening reads files without prompting or creating configuration. Initialize
31
+ explicitly with `prettynb init PATH`; configuration and private state live under
32
+ `.prettynb/`. `NOTE_PATH` selects the notebook for environment-based use.
33
+
34
+ This is a breaking rename with no legacy import, executable or configuration
35
+ aliases. See the [namespace guide](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/package-migration.md)
36
+ before switching existing installations.
37
+
38
+ - [Workflow tutorial](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/tutorials.md)
39
+ - [Settings and profiles](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/settings.md)
40
+ - [API and CLI reference](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/reference.md)
41
+ - [Checked publishing](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/checked-publishing.md)
42
+ - [Web deployment](https://github.com/wispsy/prettynb/blob/v0.13.0/docs/web.md)
43
+ - [Source and issue queue](https://github.com/wispsy/prettynb)
44
+
45
+ The web publisher runs from a checkout and is separate from the core wheel.
46
+ Its supported profile is one Gunicorn instance with 1–4 coordinated workers,
47
+ one local SQLite database, trusted editors and a TLS reverse proxy. Hosted
48
+ activation and the experimental macOS URL handlers remain separate from the
49
+ core package contract.
@@ -0,0 +1,64 @@
1
+ [build-system]
2
+ requires = ["setuptools>=84.1.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "prettynb"
7
+ version = "0.13.0"
8
+ description = "Python tools for parsing and querying wiki-linked, tagged Markdown notebooks."
9
+ readme = "docs/prettynb.md"
10
+ requires-python = ">=3.14"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+
14
+ authors = [
15
+ { name = "prettynb" },
16
+ ]
17
+ maintainers = [
18
+ { name = "wispsy" },
19
+ ]
20
+
21
+ keywords = [
22
+ "markdown",
23
+ "notes",
24
+ "wikilinks",
25
+ "knowledge-management",
26
+ ]
27
+
28
+ dependencies = [
29
+ "expose-interface>=0.1.0,<0.2",
30
+ "requ>=0.2.0,<0.3",
31
+ "parse-md>=0.1.0,<0.2",
32
+ "escape-colors[markdown]>=0.3.0,<0.4",
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ legacy-markdown = ["markdown>=3.3.4"]
37
+
38
+ [project.urls]
39
+ Homepage = "https://wispsy.com"
40
+ Repository = "https://github.com/wispsy/prettynb"
41
+ Documentation = "https://github.com/wispsy/prettynb/tree/v0.13.0/docs"
42
+ Issues = "https://github.com/wispsy/prettynb/issues"
43
+
44
+ [project.scripts]
45
+ prettynb = "prettynb.cli:cli"
46
+
47
+ [tool.setuptools]
48
+ package-dir = { "" = "src" }
49
+
50
+ [tool.setuptools.packages.find]
51
+ where = ["src"]
52
+ include = ["prettynb*"]
53
+ namespaces = false
54
+
55
+ [tool.setuptools.package-data]
56
+ prettynb = ["resources/deploy/*.tmpl"]
57
+
58
+ [tool.pytest.ini_options]
59
+ addopts = ["-ra", "--strict-config", "--strict-markers"]
60
+ testpaths = ["tests"]
61
+ filterwarnings = [
62
+ "error",
63
+ "ignore:'crypt' is deprecated and slated for removal in Python 3.13:DeprecationWarning:passlib\\.utils",
64
+ ]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,7 @@
1
+ from .models import Notebook, Note
2
+ from .settings import NotebookSettings, SettingsError
3
+ from prettynb._internal.identities import IdentityError
4
+ from prettynb._internal.search import SearchHit
5
+ from prettynb._internal.navigation import NavigationHistory, NavigationIndex
6
+
7
+ __all__ = ["Notebook", "Note", "NotebookSettings", "SettingsError", "IdentityError", "SearchHit", "NavigationIndex", "NavigationHistory"]
@@ -0,0 +1 @@
1
+ """Private implementation helpers; use the public package API."""
@@ -0,0 +1,327 @@
1
+ """Preview-first, stopped-site recovery into new private locations."""
2
+
3
+ from contextlib import closing, contextmanager
4
+ from dataclasses import replace
5
+ from importlib.metadata import version as package_version
6
+ import hashlib
7
+ import json
8
+ import os
9
+ from pathlib import Path
10
+ import re
11
+ import sqlite3
12
+ import stat
13
+ import time
14
+ import tomllib
15
+
16
+ from .deployment import _run_checked, check_environment
17
+ from .web_state import CURRENT_VERSION, inspect_web_state
18
+
19
+ AUXILIARY = {'db.sqlite3-wal', 'db.sqlite3-shm', 'db.sqlite3-journal'}
20
+
21
+
22
+ def _location(value):
23
+ path = Path(value).expanduser().absolute()
24
+ if path.is_symlink():
25
+ raise ValueError('Recovery locations must not be symlinks.')
26
+ return path.resolve()
27
+
28
+
29
+ def _new_location(value, *sources):
30
+ path = _location(value)
31
+ if path.exists() or not path.parent.is_dir():
32
+ raise ValueError('Choose a new output location with an existing parent directory.')
33
+ for source in sources:
34
+ source = _location(source)
35
+ if path.is_relative_to(source) or source.is_relative_to(path):
36
+ raise ValueError('Recovery output must be separate from existing state and backups.')
37
+ return path
38
+
39
+
40
+ def _scan(root, *, copy_to=None, skip=frozenset()):
41
+ """Read relative to directory descriptors and reject links/special files."""
42
+ files, directories = {}, []
43
+ descriptor = os.open(root, os.O_RDONLY | os.O_DIRECTORY | os.O_NOFOLLOW)
44
+ def unreadable(error):
45
+ raise error
46
+ try:
47
+ for relative, names, filenames, directory in os.fwalk('.', dir_fd=descriptor, follow_symlinks=False, onerror=unreadable):
48
+ prefix = Path(relative)
49
+ if copy_to is not None:
50
+ (copy_to / prefix).mkdir(mode=0o700, exist_ok=True)
51
+ for name in names:
52
+ if not stat.S_ISDIR(os.stat(name, dir_fd=directory, follow_symlinks=False).st_mode):
53
+ raise ValueError('Recovery trees must not contain symlinks or special files.')
54
+ directories.append((prefix / name).as_posix())
55
+ for name in sorted(filenames):
56
+ if not stat.S_ISREG(os.stat(name, dir_fd=directory, follow_symlinks=False).st_mode):
57
+ raise ValueError('Recovery trees must contain regular files only.')
58
+ relative_name = (prefix / name).as_posix()
59
+ if relative_name in skip:
60
+ continue
61
+ fd = os.open(name, os.O_RDONLY | os.O_NOFOLLOW, dir_fd=directory)
62
+ target = None
63
+ try:
64
+ before = os.fstat(fd)
65
+ if not stat.S_ISREG(before.st_mode):
66
+ raise ValueError('Recovery source is not a regular file.')
67
+ if copy_to is not None:
68
+ target_fd = os.open(copy_to / relative_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
69
+ target = os.fdopen(target_fd, 'wb')
70
+ digest = hashlib.sha256()
71
+ with os.fdopen(fd, 'rb', closefd=False) as stream:
72
+ for chunk in iter(lambda: stream.read(1024 * 1024), b''):
73
+ digest.update(chunk)
74
+ if target is not None:
75
+ target.write(chunk)
76
+ after = os.fstat(fd)
77
+ if (before.st_ino, before.st_size, before.st_mtime_ns, before.st_ctime_ns) != (after.st_ino, after.st_size, after.st_mtime_ns, after.st_ctime_ns):
78
+ raise ValueError('Recovery source changed while it was read; preserve the incomplete output.')
79
+ if target is not None:
80
+ target.flush()
81
+ os.fsync(target.fileno())
82
+ files[relative_name] = {'sha256': digest.hexdigest(), 'size': before.st_size}
83
+ finally:
84
+ if target is not None:
85
+ target.close()
86
+ os.close(fd)
87
+ finally:
88
+ os.close(descriptor)
89
+ return {'files': files, 'directories': sorted(directories)}
90
+
91
+
92
+ def _write(path, data):
93
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW, 0o600)
94
+ with os.fdopen(fd, 'wb') as output:
95
+ output.write(data if isinstance(data, bytes) else data.encode('utf-8'))
96
+ output.flush()
97
+ os.fsync(output.fileno())
98
+
99
+
100
+ def _private_bytes(path):
101
+ fd = os.open(path, os.O_RDONLY | os.O_NOFOLLOW)
102
+ with os.fdopen(fd, 'rb') as source:
103
+ info = os.fstat(source.fileno())
104
+ if not stat.S_ISREG(info.st_mode) or info.st_mode & 0o077 or info.st_size > 1024 * 1024:
105
+ raise ValueError('Recovery environment must be a private regular file within the 1 MiB bound.')
106
+ contents = source.read(1024 * 1024 + 1)
107
+ if len(contents) > 1024 * 1024:
108
+ raise ValueError('Recovery environment grew beyond its supported bound.')
109
+ return contents
110
+
111
+
112
+ def _code_identity(spec, profile):
113
+ if profile == 'vps':
114
+ revision = _run_checked(['git', '-C', str(spec.checkout), 'rev-parse', 'HEAD'], label='Backup code revision check')
115
+ if _run_checked(['git', '-C', str(spec.checkout), 'status', '--porcelain', '--untracked-files=all'], label='Backup checkout check'):
116
+ raise ValueError('Use a clean pinned checkout for recovery.')
117
+ try:
118
+ with (spec.checkout / 'pyproject.toml').open('rb') as source:
119
+ version = tomllib.load(source)['project']['version']
120
+ except (OSError, ValueError, KeyError) as error:
121
+ raise ValueError('Matching application metadata is unavailable.') from error
122
+ identity = {'revision': revision, 'version': version}
123
+ elif profile == 'container':
124
+ image = f'prettynb:{spec.revision}'
125
+ revision = _run_checked(['docker', 'image', 'inspect', '--format', '{{index .Config.Labels "org.opencontainers.image.revision"}}', image], label='Backup image revision check')
126
+ image_id = _run_checked(['docker', 'image', 'inspect', '--format', '{{.Id}}', image], label='Backup image identity check')
127
+ version = _run_checked(['docker', 'run', '--rm', '--network', 'none', '--entrypoint', 'python', image,
128
+ '-c', 'from importlib.metadata import version; print(version("prettynb"))'], label='Backup image package check')
129
+ identity = {'revision': revision, 'version': version, 'image_id': image_id}
130
+ else:
131
+ raise ValueError('Unknown recovery profile.')
132
+ if (revision != spec.revision or version != package_version('prettynb')
133
+ or not isinstance(version, str) or not re.fullmatch(r'[A-Za-z0-9.!+_-]{1,64}', version)):
134
+ raise ValueError('Recovery requires the exact matching application revision and version.')
135
+ return identity
136
+
137
+
138
+ def _require_stopped(spec, profile, code, *, match_image=True):
139
+ if profile == 'vps':
140
+ output = _run_checked(['systemctl', 'show', spec.service, '--property=LoadState,ActiveState,MainPID'], label='Stopped service check')
141
+ fields = dict(line.split('=', 1) for line in output.splitlines() if '=' in line)
142
+ if fields.get('LoadState') != 'loaded' or fields.get('ActiveState') not in {'inactive', 'failed'} or fields.get('MainPID') != '0':
143
+ raise ValueError('Stop the managed service completely before applying recovery.')
144
+ else:
145
+ state = json.loads(_run_checked(['docker', 'inspect', '--format', '{{json .State}}', spec.service], label='Stopped container check'))
146
+ image_id = _run_checked(['docker', 'inspect', '--format', '{{.Image}}', spec.service], label='Stopped container image check')
147
+ if not isinstance(state, dict) or state.get('Status') not in {'created', 'exited'} or state.get('Running') or state.get('Restarting') or state.get('Pid') != 0 or (match_image and image_id != code['image_id']):
148
+ raise ValueError('Stop the matching managed container completely before applying recovery.')
149
+
150
+
151
+ @contextmanager
152
+ def _state_lock(root):
153
+ import fcntl
154
+ fd = os.open(root / 'site.lock', os.O_RDONLY | os.O_NOFOLLOW)
155
+ try:
156
+ if not stat.S_ISREG(os.fstat(fd).st_mode):
157
+ raise ValueError('State coordination lock must be a regular file.')
158
+ try:
159
+ fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
160
+ except BlockingIOError as error:
161
+ raise ValueError('A state operation is running; stop the service before backup.') from error
162
+ yield
163
+ finally:
164
+ os.close(fd)
165
+
166
+
167
+ def _environment_check(spec, profile):
168
+ expected = {} if profile == 'vps' else {
169
+ 'PRETTYNB_DATA_DIR': '/var/lib/prettynb',
170
+ 'PRETTYNB_DATABASE_URL': 'sqlite:///var/lib/prettynb/db.sqlite3',
171
+ 'PRETTYNB_PORT': str(spec.port), 'PRETTYNB_WORKERS': str(spec.workers),
172
+ }
173
+ check_environment(spec, expected_values=expected)
174
+
175
+
176
+ def _snapshot_database(source, destination):
177
+ _write(destination, b'')
178
+ deadline = time.monotonic() + 30
179
+ def progress(*args):
180
+ if time.monotonic() > deadline:
181
+ raise ValueError('Database snapshot timed out; preserve the incomplete output.')
182
+ with closing(sqlite3.connect(source.as_uri() + '?mode=ro', uri=True, timeout=5)) as original:
183
+ with closing(sqlite3.connect(destination)) as snapshot:
184
+ original.backup(snapshot, pages=256, progress=progress, sleep=0.05)
185
+ with destination.open('rb') as stream:
186
+ os.fsync(stream.fileno())
187
+
188
+
189
+ def _finish(root, name, payload):
190
+ receipt = json.dumps(payload, indent=2, sort_keys=True) + '\n'
191
+ if len(receipt.encode('utf-8')) > 16 * 1024 * 1024:
192
+ raise ValueError('Recovery receipt exceeds the supported 16 MiB bound; preserve the incomplete output.')
193
+ _write(root / name, receipt)
194
+ # Persist directory entries after all file contents and the receipt are durable.
195
+ for directory in sorted((p for p in root.rglob('*') if p.is_dir()), reverse=True):
196
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
197
+ try:
198
+ os.fsync(fd)
199
+ finally:
200
+ os.close(fd)
201
+ (root / '.incomplete').unlink()
202
+ for directory in (root, root.parent):
203
+ fd = os.open(directory, os.O_RDONLY | os.O_DIRECTORY)
204
+ try:
205
+ os.fsync(fd)
206
+ finally:
207
+ os.close(fd)
208
+
209
+
210
+ def backup_site(spec, output, *, profile='vps', apply=False):
211
+ source = _location(spec.data_dir)
212
+ output = _new_location(output, source, spec.env_file)
213
+ code = _code_identity(spec, profile)
214
+ _environment_check(spec, profile)
215
+ storage = inspect_web_state(source)
216
+ report = {'operation': 'backup', 'apply': apply, 'output': str(output), 'revision': spec.revision,
217
+ 'version': code['version'], 'schema_version': storage['schema_version'], 'profile': profile}
218
+ if not apply:
219
+ return report
220
+ _require_stopped(spec, profile, code)
221
+ with _state_lock(source):
222
+ before = _scan(source, skip={'db.sqlite3-shm'})
223
+ environment = _private_bytes(spec.env_file)
224
+ output.mkdir(mode=0o700)
225
+ _write(output / '.incomplete', 'Backup is incomplete; do not restore.\n')
226
+ (output / 'state').mkdir(mode=0o700)
227
+ _scan(source, copy_to=output / 'state', skip={'db.sqlite3', *AUXILIARY})
228
+ _snapshot_database(source / 'db.sqlite3', output / 'state/db.sqlite3')
229
+ _write(output / 'environment', environment)
230
+ _write(output / 'deployment.json', json.dumps(spec.to_dict(), sort_keys=True))
231
+ inspect_web_state(output / 'state')
232
+ if before != _scan(source, skip={'db.sqlite3-shm'}) or environment != _private_bytes(spec.env_file):
233
+ raise ValueError('Source changed during backup; preserve the incomplete output and retry stopped.')
234
+ if _code_identity(spec, profile) != code:
235
+ raise ValueError('Application identity changed during backup.')
236
+ _require_stopped(spec, profile, code)
237
+ inventory = _scan(output, skip={'.incomplete'})
238
+ _finish(output, 'manifest.json', {'format': 1, 'profile': profile, 'code': code,
239
+ 'schema_version': CURRENT_VERSION, 'inventory': inventory})
240
+ return {**report, 'verified': True}
241
+
242
+
243
+ def verify_backup(path):
244
+ root = _location(path)
245
+ if not root.is_dir() or root.stat().st_mode & 0o077:
246
+ raise ValueError('Backup must be a private directory (mode 0700).')
247
+ if (root / '.incomplete').exists():
248
+ raise ValueError('Backup is incomplete; preserve it and use a verified backup.')
249
+ try:
250
+ manifest_path = root / 'manifest.json'
251
+ if manifest_path.is_symlink() or manifest_path.stat().st_size > 16 * 1024 * 1024:
252
+ raise ValueError('Backup receipt is invalid or exceeds the supported bound.')
253
+ manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
254
+ if (not isinstance(manifest, dict) or manifest.get('format') != 1 or manifest.get('profile') not in {'vps', 'container'}
255
+ or manifest.get('schema_version') != CURRENT_VERSION
256
+ or _scan(root, skip={'manifest.json'}) != manifest.get('inventory')):
257
+ raise ValueError('Backup is incomplete, corrupt or unsupported.')
258
+ if not {'environment', 'deployment.json'} <= set(manifest['inventory']['files']):
259
+ raise ValueError('Backup is missing private configuration.')
260
+ inspect_web_state(root / 'state')
261
+ except (OSError, json.JSONDecodeError, UnicodeError, TypeError, KeyError) as error:
262
+ raise ValueError('Backup could not be verified; preserve it and inspect the private files locally.') from error
263
+ return manifest
264
+
265
+
266
+ def _owner(spec, profile):
267
+ if profile == 'container':
268
+ return 10001, 10001
269
+ import pwd
270
+ try:
271
+ user = pwd.getpwnam(spec.user)
272
+ except KeyError as error:
273
+ raise ValueError('The recovery service account is unavailable.') from error
274
+ if user.pw_uid == 0:
275
+ raise ValueError('Recovery state needs a non-root service account.')
276
+ return user.pw_uid, user.pw_gid
277
+
278
+
279
+ def restore_site(spec, backup, output, *, profile='vps', apply=False):
280
+ backup = _location(backup)
281
+ output = _new_location(output, backup, spec.data_dir, spec.env_file)
282
+ manifest = verify_backup(backup)
283
+ code = _code_identity(spec, profile)
284
+ if manifest['profile'] != profile or manifest['code'] != code:
285
+ raise ValueError('Restore requires the exact backup profile, code version, revision and image identity.')
286
+ deployment = json.loads((backup / 'deployment.json').read_text(encoding='utf-8'))
287
+ if not isinstance(deployment, dict) or any(deployment.get(key) != spec.to_dict()[key] for key in ('domain', 'port', 'workers', 'prefix')):
288
+ raise ValueError('Restore options must retain the backed-up domain, port, workers and prefix.')
289
+ restored_spec = replace(spec, data_dir=output / 'state', env_file=output / 'environment')
290
+ report = {'operation': 'restore', 'apply': apply, 'output': str(output), 'revision': spec.revision,
291
+ 'version': code['version'], 'profile': profile, 'activation_required': True}
292
+ if not apply:
293
+ return report
294
+ _require_stopped(spec, profile, code, match_image=False)
295
+ owner, group = _owner(spec, profile)
296
+ if os.geteuid() != 0 and (owner, group) != (os.geteuid(), os.getegid()):
297
+ raise ValueError('Apply restoration as root or the planned state owner/group.')
298
+ output.mkdir(mode=0o700)
299
+ _write(output / '.incomplete', 'Restoration is incomplete; do not activate.\n')
300
+ (output / 'state').mkdir(mode=0o700)
301
+ _scan(backup / 'state', copy_to=output / 'state')
302
+ expected_state = {
303
+ 'files': {name.removeprefix('state/'): value for name, value in manifest['inventory']['files'].items() if name.startswith('state/')},
304
+ 'directories': [name.removeprefix('state/') for name in manifest['inventory']['directories'] if name.startswith('state/')],
305
+ }
306
+ if _scan(output / 'state') != expected_state:
307
+ raise ValueError('Restored files differ from the verified checkpoint; preserve the incomplete output.')
308
+ original_environment = _private_bytes(backup / 'environment').decode('utf-8')
309
+ environment = original_environment
310
+ if profile == 'vps':
311
+ import shlex
312
+ values = {'PRETTYNB_DATA_DIR': str(output / 'state'), 'PRETTYNB_DATABASE_URL': 'sqlite://' + str(output / 'state/db.sqlite3')}
313
+ environment = '\n'.join(key + '=' + shlex.quote(values[key]) if (key := line.partition('=')[0].strip()) in values else line for line in environment.splitlines()) + '\n'
314
+ _write(output / 'environment.original', original_environment)
315
+ _write(output / 'environment', environment)
316
+ _environment_check(restored_spec, profile)
317
+ inspect_web_state(output / 'state')
318
+ if verify_backup(backup) != manifest:
319
+ raise ValueError('Backup changed during restoration; preserve the incomplete output.')
320
+ _require_stopped(spec, profile, code, match_image=False)
321
+ if _code_identity(spec, profile) != code:
322
+ raise ValueError('Application identity changed during restoration.')
323
+ for path in [output, output / 'state', *(output / 'state').rglob('*')]:
324
+ os.chown(path, owner, group)
325
+ _finish(output, 'restore.json', {'format': 1, 'code': code, 'state': str(output / 'state'),
326
+ 'environment': str(output / 'environment'), 'activation_required': True})
327
+ return {**report, 'verified': True, 'state': str(output / 'state'), 'environment': str(output / 'environment')}
@@ -0,0 +1,48 @@
1
+ """Small application-specific CLI converters and editor support."""
2
+
3
+ import os
4
+ from pathlib import Path
5
+ import shlex
6
+ import subprocess
7
+ import tempfile
8
+
9
+ from expose_interface import CommandError
10
+
11
+
12
+ def limit_value(value):
13
+ result = int(value)
14
+ if not 1 <= result <= 200:
15
+ raise ValueError("expected an integer from 1 to 200")
16
+ return result
17
+
18
+
19
+ def offset_value(value):
20
+ result = int(value)
21
+ if result < 0:
22
+ raise ValueError("expected a nonnegative integer")
23
+ return result
24
+
25
+
26
+ def existing_file(value):
27
+ path = Path(value)
28
+ if not path.is_file():
29
+ raise ValueError("expected an existing file")
30
+ return path
31
+
32
+
33
+ def edit_text(text):
34
+ """Edit private temporary Markdown using VISUAL, EDITOR, or the platform editor."""
35
+ editor = os.environ.get("VISUAL") or os.environ.get("EDITOR") or ("notepad" if os.name == "nt" else "vi")
36
+ with tempfile.TemporaryDirectory(prefix="prettynb-edit-") as temporary:
37
+ path = Path(temporary) / "note.md"
38
+ path.write_text(text, encoding="utf-8")
39
+ path.chmod(0o600)
40
+ try:
41
+ command = shlex.split(editor)
42
+ if not command:
43
+ raise ValueError("The editor command is empty.")
44
+ subprocess.run([*command, str(path)], check=True)
45
+ except (OSError, ValueError, subprocess.CalledProcessError) as error:
46
+ raise CommandError("The editor could not complete; the note was not changed.") from error
47
+ edited = path.read_text(encoding="utf-8")
48
+ return None if edited == text else edited