stilo-cli 0.3.0__tar.gz → 0.4.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 (90) hide show
  1. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/.gitignore +3 -0
  2. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/PKG-INFO +7 -2
  3. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/README.md +4 -0
  4. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/pyproject.toml +9 -4
  5. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/cli/commands.py +8 -19
  6. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/cli/project.py +26 -4
  7. stilo_cli-0.4.0/src/stilo/cli/tutor.py +152 -0
  8. stilo_cli-0.4.0/src/stilo/cli/web.py +37 -0
  9. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/server/app.py +1 -1
  10. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/server/storage.py +37 -48
  11. stilo_cli-0.4.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-ext-wght-italic-Cigfgs4r.woff2 +0 -0
  12. stilo_cli-0.4.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-ext-wght-normal-C6vrW8VD.woff2 +0 -0
  13. stilo_cli-0.4.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-wght-italic-DC5MiAaX.woff2 +0 -0
  14. stilo_cli-0.4.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-wght-normal-BcXVPD7q.woff2 +0 -0
  15. stilo_cli-0.4.0/src/stilo/web/assets/index-B8RYzswc.css +1 -0
  16. stilo_cli-0.3.0/src/stilo/web/assets/index-BT3YAPgN.js → stilo_cli-0.4.0/src/stilo/web/assets/index-CVdAQRVd.js +273 -142
  17. stilo_cli-0.3.0/src/stilo/web/assets/texl_wasm_bg-DXo4-iTL.wasm → stilo_cli-0.4.0/src/stilo/web/assets/texl_wasm_bg-CzhWLYga.wasm +0 -0
  18. stilo_cli-0.4.0/src/stilo/web/favicon.svg +1 -0
  19. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/index.html +3 -2
  20. stilo_cli-0.4.0/texl-lib/charts.texl +161 -0
  21. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/texl-lib/dataframe.texl +14 -10
  22. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/texl-lib/index.texl +6 -3
  23. stilo_cli-0.4.0/tutorial/01-welcome.texl +73 -0
  24. stilo_cli-0.4.0/tutorial/02-cells.texl +79 -0
  25. stilo_cli-0.4.0/tutorial/03-rich-text.texl +57 -0
  26. stilo_cli-0.4.0/tutorial/04-formulas.texl +75 -0
  27. stilo_cli-0.4.0/tutorial/05-cell-types.texl +56 -0
  28. stilo_cli-0.4.0/tutorial/06-tables-and-equations.texl +77 -0
  29. stilo_cli-0.4.0/tutorial/07-data-tables.texl +107 -0
  30. stilo_cli-0.4.0/tutorial/08-linking.texl +66 -0
  31. stilo_cli-0.4.0/tutorial/09-errors.texl +56 -0
  32. stilo_cli-0.4.0/tutorial/10-organising.texl +86 -0
  33. stilo_cli-0.4.0/tutorial/11-command-line.texl +81 -0
  34. stilo_cli-0.4.0/tutorial/12-your-first-project.texl +72 -0
  35. stilo_cli-0.4.0/tutorial/13-formula-language.texl +77 -0
  36. stilo_cli-0.4.0/tutorial/14-libraries.texl +57 -0
  37. stilo_cli-0.4.0/tutorial/files/beam-drawing.pdf +50 -0
  38. stilo_cli-0.4.0/tutorial/files/beam.svg +18 -0
  39. stilo_cli-0.4.0/tutorial/files/report.texl +15 -0
  40. stilo_cli-0.4.0/tutorial/index.texl +62 -0
  41. stilo_cli-0.4.0/tutorial/lib/steel/sections.texl +17 -0
  42. stilo_cli-0.4.0/tutorial/lib/tutorial/index.texl +36 -0
  43. stilo_cli-0.3.0/src/stilo/web/assets/index-kR4PIGIs.css +0 -1
  44. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-ext-opsz-italic-5yUt4G_9.woff2 +0 -0
  45. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-ext-opsz-normal-C5tfwALZ.woff2 +0 -0
  46. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-opsz-italic-Bj0ndbyp.woff2 +0 -0
  47. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-opsz-normal-DgmypKXX.woff2 +0 -0
  48. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-ext-opsz-italic-DFpO5j-Z.woff2 +0 -0
  49. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-ext-opsz-normal-DGm64vGR.woff2 +0 -0
  50. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-opsz-italic-CHERNRFq.woff2 +0 -0
  51. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-opsz-normal-DFglUmAd.woff2 +0 -0
  52. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-ext-opsz-italic-4y8iAqqs.woff2 +0 -0
  53. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-ext-opsz-normal-STiTPs0F.woff2 +0 -0
  54. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-opsz-italic-CJ93D38p.woff2 +0 -0
  55. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-opsz-normal-BHZsWIlc.woff2 +0 -0
  56. stilo_cli-0.3.0/src/stilo/web/assets/literata-vietnamese-opsz-italic-BdcrZMcO.woff2 +0 -0
  57. stilo_cli-0.3.0/src/stilo/web/assets/literata-vietnamese-opsz-normal-Gqw5JQlq.woff2 +0 -0
  58. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-cyrillic-ext-wght-normal-c-5QAGAI.woff2 +0 -0
  59. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-cyrillic-wght-normal-BMDVbyM7.woff2 +0 -0
  60. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-greek-ext-wght-normal-BXZfsJY4.woff2 +0 -0
  61. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-greek-wght-normal-Cc-u-6OI.woff2 +0 -0
  62. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-latin-ext-wght-normal-C8iNium2.woff2 +0 -0
  63. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-latin-wght-normal-Bo_j9asI.woff2 +0 -0
  64. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-vietnamese-wght-normal-BDs68eHQ.woff2 +0 -0
  65. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/LICENSE +0 -0
  66. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/__init__.py +0 -0
  67. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/__main__.py +0 -0
  68. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/cli/__init__.py +0 -0
  69. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/cli/errors.py +0 -0
  70. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/server/__init__.py +0 -0
  71. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/server/home.py +0 -0
  72. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  73. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  74. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  75. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  76. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  77. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  78. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  79. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  80. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  81. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  82. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  83. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  84. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  85. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  86. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  87. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  88. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  89. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  90. {stilo_cli-0.3.0 → stilo_cli-0.4.0}/src/stilo/web/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
@@ -18,3 +18,6 @@ src/stilo/web/
18
18
  local/
19
19
  *.todo.md
20
20
 
21
+
22
+ # Files deleted by the server (stilo serve moves them here)
23
+ .trash/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stilo-cli
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Stilo: edit and render a folder of linked Texl documents
5
5
  Project-URL: Documentation, https://www.onlabs.org/manual/
6
6
  Project-URL: Source, https://github.com/onlabsorg/stilo
@@ -8,7 +8,8 @@ License-Expression: MIT
8
8
  License-File: LICENSE
9
9
  Requires-Python: >=3.11
10
10
  Requires-Dist: fastapi>=0.115
11
- Requires-Dist: pytexl>=0.8.0
11
+ Requires-Dist: platformdirs>=4
12
+ Requires-Dist: pytexl>=0.9.0
12
13
  Requires-Dist: uvicorn>=0.30
13
14
  Description-Content-Type: text/markdown
14
15
 
@@ -35,10 +36,14 @@ Requires Python 3.11 or later. Install the `stilo` command from PyPI, with
35
36
 
36
37
  ```bash
37
38
  uv tool install stilo-cli # or: pip install stilo-cli
39
+ stilo tutor # the tutorial, in your browser
38
40
  stilo serve my-folder # http://127.0.0.1:8000
39
41
  stilo render my-folder/report.texl
40
42
  ```
41
43
 
44
+ `stilo tutor` opens a guided tutorial of short lessons, in your own copy:
45
+ the best way to start.
46
+
42
47
  To try the sample documents, or to work on Stilo itself, use a checkout
43
48
  (Node.js 22+ builds the web app):
44
49
 
@@ -21,10 +21,14 @@ Requires Python 3.11 or later. Install the `stilo` command from PyPI, with
21
21
 
22
22
  ```bash
23
23
  uv tool install stilo-cli # or: pip install stilo-cli
24
+ stilo tutor # the tutorial, in your browser
24
25
  stilo serve my-folder # http://127.0.0.1:8000
25
26
  stilo render my-folder/report.texl
26
27
  ```
27
28
 
29
+ `stilo tutor` opens a guided tutorial of short lessons, in your own copy:
30
+ the best way to start.
31
+
28
32
  To try the sample documents, or to work on Stilo itself, use a checkout
29
33
  (Node.js 22+ builds the web app):
30
34
 
@@ -8,6 +8,8 @@
8
8
  # the release workflow checks that the wheel has it)
9
9
  # texl-lib/ the Texl library `stilo init` copies into projects,
10
10
  # shipped in the wheel as stilo/texl-lib
11
+ # tutorial/ the lessons `stilo tutor` copies and serves, shipped
12
+ # in the wheel as stilo/tutorial
11
13
  #
12
14
  # Build:
13
15
  #
@@ -16,7 +18,7 @@
16
18
 
17
19
  [project]
18
20
  name = "stilo-cli"
19
- version = "0.3.0"
21
+ version = "0.4.0"
20
22
  description = "Stilo: edit and render a folder of linked Texl documents"
21
23
  readme = "README.md"
22
24
  license = "MIT"
@@ -24,7 +26,8 @@ license-files = ["LICENSE"]
24
26
  requires-python = ">=3.11"
25
27
  dependencies = [
26
28
  "fastapi>=0.115",
27
- "pytexl>=0.8.0",
29
+ "platformdirs>=4",
30
+ "pytexl>=0.9.0",
28
31
  "uvicorn>=0.30",
29
32
  ]
30
33
 
@@ -46,14 +49,16 @@ requires = ["hatchling"]
46
49
  build-backend = "hatchling.build"
47
50
 
48
51
  [tool.hatch.build.targets.sdist]
49
- only-include = ["src/stilo", "texl-lib", "README.md", "LICENSE"]
52
+ only-include = ["src/stilo", "texl-lib", "tutorial", "README.md", "LICENSE"]
50
53
 
51
54
  [tool.hatch.build.targets.wheel]
52
55
  packages = ["src/stilo"]
53
56
 
54
- # In a checkout the CLI reads texl-lib/ where it is (stilo/cli/project.py).
57
+ # In a checkout the CLI reads texl-lib/ and tutorial/ where they are
58
+ # (stilo/cli/project.py, stilo/cli/tutor.py).
55
59
  [tool.hatch.build.targets.wheel.force-include]
56
60
  "texl-lib" = "stilo/texl-lib"
61
+ "tutorial" = "stilo/tutorial"
57
62
 
58
63
  # src/stilo/web is git-ignored: include it anyway when it is there. Not a
59
64
  # forced include, so that editable installs (`uv run`) work without it.
@@ -6,23 +6,17 @@ the order `stilo --help` shows them; a plugin system can later add its own.
6
6
  """
7
7
 
8
8
  import asyncio
9
- import shutil
10
9
  import sys
11
10
  from dataclasses import dataclass
12
11
  from pathlib import Path
13
12
  from typing import Callable
14
13
 
15
14
  import pytexl
16
- import uvicorn
17
-
18
- from stilo.server import create_app
19
15
 
20
16
  from .errors import count_returned, find_errors, format_report, numbered_text
21
- from .project import LIB, LIBRARY_NAME, MANIFEST, TEXL_LIB, create_engine, manifest
22
-
23
- # The built web app, `stilo/web`: written there by `npm run build` in a
24
- # checkout, shipped there in the package
25
- WEB_DIST = Path(__file__).resolve().parents[1] / "web"
17
+ from .project import LIB, LIBRARY_NAME, MANIFEST, create_engine, make_project
18
+ from .tutor import tutor, tutor_arguments
19
+ from .web import WEB_DIST, run_server
26
20
 
27
21
 
28
22
  @dataclass
@@ -93,8 +87,9 @@ def serve(args) -> int:
93
87
  if not args.folder.is_dir():
94
88
  print(f"stilo: {args.folder}: not a folder", file=sys.stderr)
95
89
  return 1
96
- print(f"Stilo: serving {args.folder.resolve()} at http://{args.host}:{args.port}/")
97
- uvicorn.run(create_app(args.folder, args.web), host=args.host, port=args.port)
90
+ print(f"Stilo: serving {args.folder.resolve()} at http://{args.host}:{args.port}/ "
91
+ "(press Ctrl+C here to stop)")
92
+ run_server(args.folder, args.host, args.port, args.web)
98
93
  return 0
99
94
 
100
95
 
@@ -111,15 +106,8 @@ def init(args) -> int:
111
106
  if (folder / MANIFEST).exists():
112
107
  print(f"stilo: {args.folder}: already a project ({MANIFEST} exists)", file=sys.stderr)
113
108
  return 1
114
- library = folder / LIB / LIBRARY_NAME
115
109
  try:
116
- folder.mkdir(parents=True, exist_ok=True)
117
- with open(folder / MANIFEST, "x", encoding="utf-8") as file:
118
- file.write(manifest(args.name or folder.name))
119
- (folder / LIB).mkdir(exist_ok=True)
120
- kept = library.exists()
121
- if not kept:
122
- shutil.copytree(TEXL_LIB, library)
110
+ kept = make_project(folder, args.name or folder.name)
123
111
  except OSError as e:
124
112
  print(f"stilo: {args.folder}: {e}", file=sys.stderr)
125
113
  return 1
@@ -133,4 +121,5 @@ COMMANDS = [
133
121
  Command("init", "make a folder a Stilo project, with the Stilo library", init_arguments, init),
134
122
  Command("render", "render a Texl document", render_arguments, render),
135
123
  Command("serve", "serve a folder of Texl documents with the web app", serve_arguments, serve),
124
+ Command("tutor", "learn Stilo: open the tutorial in the web app", tutor_arguments, tutor),
136
125
  ]
@@ -1,5 +1,5 @@
1
1
  """Projects in the CLI (DECISIONS.md S10): the engine that resolves `~` in
2
- file paths, and what `stilo init` writes.
2
+ file paths, and what `stilo init` (and `stilo tutor`, S14) writes.
3
3
 
4
4
  The rule itself is in `stilo.server.home`, shared with the server.
5
5
  """
@@ -7,6 +7,7 @@ The rule itself is in `stilo.server.home`, shared with the server.
7
7
  from __future__ import annotations
8
8
 
9
9
  import re
10
+ import shutil
10
11
  from importlib.metadata import PackageNotFoundError, version
11
12
  from pathlib import Path
12
13
 
@@ -26,6 +27,22 @@ LIB = "lib"
26
27
  LIBRARY_NAME = "stilo"
27
28
 
28
29
 
30
+ def make_project(folder: Path, name: str) -> bool:
31
+ """Makes `folder` a project: creates it if missing, writes `project.texl`
32
+ (never over an existing one: `FileExistsError`), creates `lib/` and
33
+ copies the bundled library into `lib/stilo/`. Returns whether a
34
+ `lib/stilo/` was already there, which is then left as it is."""
35
+ library = folder / LIB / LIBRARY_NAME
36
+ folder.mkdir(parents=True, exist_ok=True)
37
+ with open(folder / MANIFEST, "x", encoding="utf-8") as file:
38
+ file.write(manifest(name))
39
+ (folder / LIB).mkdir(exist_ok=True)
40
+ kept = library.exists()
41
+ if not kept:
42
+ shutil.copytree(TEXL_LIB, library)
43
+ return kept
44
+
45
+
29
46
  def stilo_version() -> str:
30
47
  """The version of the installed package (pyproject.toml), the one place it is set."""
31
48
  try:
@@ -68,10 +85,15 @@ def create_engine() -> pytexl.Engine:
68
85
  return engine
69
86
 
70
87
 
88
+ def swan_text(value: str) -> str:
89
+ """`value` made safe for a Swan text literal in a tag: Swan strings have
90
+ no escapes, so it loses any `"` and `%>`."""
91
+ return re.sub(r'"|%>', "", value).strip()
92
+
93
+
71
94
  def manifest(name: str) -> str:
72
- """The text of a new `project.texl`. Swan strings have no escapes, so
73
- the name loses any `"` and `%>`."""
74
- name = re.sub(r'"|%>', "", name).strip() or "project"
95
+ """The text of a new `project.texl`."""
96
+ name = swan_text(name) or "project"
75
97
  return f"""# {name}
76
98
 
77
99
  This folder is a Stilo project. This file marks its home folder: in an
@@ -0,0 +1,152 @@
1
+ """`stilo tutor`: the tutorial, in a working copy (DECISIONS.md S14).
2
+
3
+ The tutorial's source is `tutorial/` at the root of the checkout, shipped in
4
+ the wheel as `stilo/tutorial` (pyproject.toml). The user never edits it:
5
+ `stilo tutor` copies it into a working folder, makes the copy a project with
6
+ the code of `stilo init`, and serves it. An existing copy is reused, so
7
+ progress is kept; `--reset` moves it aside first, never deleting it.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import re
13
+ import shutil
14
+ import sys
15
+ from datetime import datetime
16
+ from pathlib import Path
17
+
18
+ import platformdirs
19
+
20
+ from .project import MANIFEST, PACKAGE, make_project, stilo_version, swan_text
21
+ from .web import WEB_DIST, run_server
22
+
23
+ _INSTALLED_TUTORIAL = PACKAGE / "tutorial"
24
+ TUTORIAL = _INSTALLED_TUTORIAL if _INSTALLED_TUTORIAL.is_dir() else PACKAGE.parents[1] / "tutorial"
25
+
26
+ PROJECT_NAME = "Stilo tutorial"
27
+ INDEX = "index.texl"
28
+
29
+ # The value `stilo tutor` adds to the copy's project.texl: the folder of the
30
+ # copy, shown by the command-line lessons. It also tells a copy from any
31
+ # other folder.
32
+ FOLDER_NAME = "tutorial_folder"
33
+ _FOLDER_VALUE = re.compile(rf"<%\s*{FOLDER_NAME}\s*=")
34
+ _VERSION_VALUE = re.compile(r'stilo_version\s*=\s*"([^"]*)"')
35
+
36
+
37
+ def default_folder() -> Path:
38
+ """Where the copy goes by default: `tutorial` in Stilo's user data folder."""
39
+ return platformdirs.user_data_path("stilo", appauthor=False) / "tutorial"
40
+
41
+
42
+ def is_copy(folder: Path) -> bool:
43
+ """Whether `folder` is a working copy of the tutorial."""
44
+ try:
45
+ return bool(_FOLDER_VALUE.search((folder / MANIFEST).read_text(encoding="utf-8")))
46
+ except OSError:
47
+ return False
48
+
49
+
50
+ def is_empty(folder: Path) -> bool:
51
+ return not folder.exists() or (folder.is_dir() and not any(folder.iterdir()))
52
+
53
+
54
+ def create_copy(folder: Path):
55
+ """Copies the tutorial into `folder` (missing or empty) and makes it a project."""
56
+ shutil.copytree(TUTORIAL, folder, dirs_exist_ok=True)
57
+ make_project(folder, PROJECT_NAME)
58
+ with open(folder / MANIFEST, "a", encoding="utf-8") as file:
59
+ file.write(f'<% {FOLDER_NAME} = "{swan_text(str(folder))}" %>\n')
60
+
61
+
62
+ def move_aside(folder: Path) -> Path:
63
+ """Renames `folder` to a free name next to it, with the date and time."""
64
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
65
+ target = folder.with_name(f"{folder.name}-old-{stamp}")
66
+ n = 1
67
+ while target.exists():
68
+ n += 1
69
+ target = folder.with_name(f"{folder.name}-old-{stamp}-{n}")
70
+ folder.rename(target)
71
+ return target
72
+
73
+
74
+ def copy_version(folder: Path) -> str | None:
75
+ """The `stilo_version` written in the copy's project.texl, if any."""
76
+ try:
77
+ match = _VERSION_VALUE.search((folder / MANIFEST).read_text(encoding="utf-8"))
78
+ except OSError:
79
+ return None
80
+ return match.group(1) if match else None
81
+
82
+
83
+ def version_key(text: str) -> tuple[int, ...]:
84
+ """A version for comparison: its leading numbers, `0.3.0rc1` as (0, 3, 0)."""
85
+ numbers = []
86
+ for part in text.split("."):
87
+ digits = re.match(r"\d+", part)
88
+ if not digits:
89
+ break
90
+ numbers.append(int(digits.group()))
91
+ return tuple(numbers)
92
+
93
+
94
+ def is_older(version: str | None, than: str) -> bool:
95
+ return version_key(version or "0") < version_key(than)
96
+
97
+
98
+ def prepare(folder: Path, reset: bool, out=None, err=None) -> bool:
99
+ """Makes sure `folder` holds a working copy, as `stilo tutor` does before
100
+ serving it. Says what it did on `out` (standard output); returns False
101
+ on an error, reported on `err` (standard error)."""
102
+ out, err = out or sys.stdout, err or sys.stderr
103
+ if folder.exists() and not folder.is_dir():
104
+ print(f"stilo: {folder}: not a folder", file=err)
105
+ return False
106
+ if not is_empty(folder) and not is_copy(folder):
107
+ print(f"stilo: {folder}: not a copy of the tutorial, and not empty: "
108
+ "choose another folder with --dir", file=err)
109
+ return False
110
+ try:
111
+ if reset and not is_empty(folder):
112
+ old = move_aside(folder)
113
+ print(f"Stilo: your old copy of the tutorial is now in {old}", file=out)
114
+ if is_empty(folder):
115
+ create_copy(folder)
116
+ print(f"Stilo: a new copy of the tutorial is in {folder}", file=out)
117
+ return True
118
+ except OSError as e:
119
+ print(f"stilo: {folder}: {e}", file=err)
120
+ return False
121
+ print(f"Stilo: your copy of the tutorial is in {folder}", file=out)
122
+ version, installed = copy_version(folder), stilo_version()
123
+ if is_older(version, installed):
124
+ print(f"Stilo: this copy was made by Stilo {version or '(unknown)'}, and Stilo "
125
+ f"{installed} may have changed lessons. To start again with the new "
126
+ f"lessons, run: stilo tutor --reset (your copy will be kept, moved aside)",
127
+ file=out)
128
+ return True
129
+
130
+
131
+ def tutor_arguments(parser):
132
+ parser.add_argument("--dir", type=Path, default=None,
133
+ help="folder of your copy of the tutorial (default: "
134
+ f"{default_folder()})")
135
+ parser.add_argument("--reset", action="store_true",
136
+ help="start again from a fresh copy; the old one is moved aside, not deleted")
137
+ parser.add_argument("--port", type=int, default=8000)
138
+ parser.add_argument("--no-browser", action="store_true",
139
+ help="do not open the browser")
140
+
141
+
142
+ def tutor(args) -> int:
143
+ """Copies the tutorial if needed, serves the copy and opens its index."""
144
+ folder = (args.dir or default_folder()).expanduser().resolve()
145
+ if not prepare(folder, args.reset):
146
+ return 1
147
+ host = "127.0.0.1"
148
+ url = f"http://{host}:{args.port}/{INDEX}"
149
+ print(f"Stilo: the tutorial is at {url} (press Ctrl+C here to stop)")
150
+ sys.stdout.flush()
151
+ run_server(folder, host, args.port, WEB_DIST, open_url=None if args.no_browser else url)
152
+ return 0
@@ -0,0 +1,37 @@
1
+ """Serving a folder with the web app, for `stilo serve` and `stilo tutor`."""
2
+
3
+ import threading
4
+ import time
5
+ import webbrowser
6
+ from pathlib import Path
7
+
8
+ import uvicorn
9
+
10
+ from stilo.server import create_app
11
+
12
+ # The built web app, `stilo/web`: written there by `npm run build` in a
13
+ # checkout, shipped there in the package
14
+ WEB_DIST = Path(__file__).resolve().parents[1] / "web"
15
+
16
+
17
+ def run_server(folder: Path, host: str, port: int, web: Path = WEB_DIST, open_url: str | None = None):
18
+ """Serves `folder` until the process is stopped. With `open_url`, opens
19
+ it in the browser once the server accepts connections. Ctrl+C stops it
20
+ with a goodbye instead of a traceback."""
21
+ server = uvicorn.Server(uvicorn.Config(create_app(folder, web), host=host, port=port))
22
+ if open_url:
23
+ threading.Thread(target=_open_when_started, args=(server, open_url), daemon=True).start()
24
+ try:
25
+ server.run()
26
+ except KeyboardInterrupt:
27
+ # uvicorn has already shut down cleanly; it re-raises the interrupt
28
+ # for its caller, and asyncio raises it out of a CancelledError
29
+ print("Stilo: stopped. Goodbye!")
30
+
31
+
32
+ def _open_when_started(server, url):
33
+ while not server.should_exit:
34
+ if server.started:
35
+ webbrowser.open(url)
36
+ return
37
+ time.sleep(0.1)
@@ -46,7 +46,7 @@ def create_app(root: Path | str, web_dist: Path | str | None = None) -> FastAPI:
46
46
  """The server app for the documents under `root`. `web_dist` is the built
47
47
  web app (`stilo/web` in the CLI); without it, app pages show a notice."""
48
48
  storage = Storage(root)
49
- app = FastAPI(title="Stilo server", version="0.3.0")
49
+ app = FastAPI(title="Stilo server", version="0.4.0")
50
50
 
51
51
  @app.exception_handler(StorageError)
52
52
  async def storage_error(request: Request, error: StorageError):
@@ -109,8 +109,11 @@ class Storage:
109
109
  return target.is_file() and target.suffix != DOCUMENT_SUFFIX
110
110
 
111
111
  def create(self, path: str, content: bytes) -> str:
112
- target = self._writable(path)
113
- target.parent.mkdir(parents=True, exist_ok=True)
112
+ """Create a file, a document or any other, and its missing folders."""
113
+ target = self._item(path)
114
+ if target.is_dir():
115
+ raise Conflict(f"already exists, as a folder: {path!r}")
116
+ self._make_folder(target.parent, path)
114
117
  try:
115
118
  with open(target, "xb") as file:
116
119
  file.write(content)
@@ -119,7 +122,11 @@ class Storage:
119
122
  return etag(content)
120
123
 
121
124
  def update(self, path: str, content: bytes, if_match: str | None = None) -> str:
122
- target = self._writable(path)
125
+ target = self.resolve(path)
126
+ if target.suffix != DOCUMENT_SUFFIX:
127
+ raise BadRequest(f"only {DOCUMENT_SUFFIX} files can be updated: {path!r}")
128
+ if target.is_dir():
129
+ raise BadRequest(f"is a folder: {path!r}")
123
130
  if not target.is_file():
124
131
  raise NotFound(f"no such file: {path!r}")
125
132
  if if_match is not None and if_match != etag(target.read_bytes()):
@@ -131,28 +138,21 @@ class Storage:
131
138
  os.replace(temp, target)
132
139
  return etag(content)
133
140
 
134
- def _writable(self, path: str) -> Path:
135
- target = self.resolve(path)
136
- if target.suffix != DOCUMENT_SUFFIX:
137
- raise BadRequest(f"only {DOCUMENT_SUFFIX} files can be written: {path!r}")
138
- if target.is_dir():
139
- raise BadRequest(f"is a folder: {path!r}")
140
- return target
141
-
142
141
  def _item(self, path: str) -> Path:
143
- """The file-system path of an item to move or delete, validated as
142
+ """The file-system path of an item to create, move or delete, validated as
144
143
  `resolve` does. A symbolic link stays itself: the item is the link, not
145
144
  what it points to."""
146
145
  self.resolve(path)
147
146
  relative = path.strip("/")
148
147
  if not relative:
149
- raise BadRequest("the root folder cannot be moved or deleted")
148
+ raise BadRequest("not allowed on the root folder")
150
149
  return self.root.joinpath(*relative.split("/"))
151
150
 
152
151
  # -- move ----------------------------------------------------------------
153
152
 
154
153
  def move(self, path: str, to: str) -> str:
155
- """Move or rename a document or a folder; returns its new path."""
154
+ """Move or rename a file or a folder; returns its new path. A document
155
+ stays a document and another file stays another file."""
156
156
  source = self._item(path)
157
157
  target = self._item(to)
158
158
  if not os.path.lexists(source):
@@ -162,8 +162,8 @@ class Storage:
162
162
  raise BadRequest(f"a folder's name cannot end in {DOCUMENT_SUFFIX}: {to!r}")
163
163
  if target.resolve().is_relative_to(source.resolve()) and target != source:
164
164
  raise BadRequest(f"a folder cannot go inside itself: {to!r}")
165
- elif source.suffix != DOCUMENT_SUFFIX or target.suffix != DOCUMENT_SUFFIX:
166
- raise BadRequest(f"only {DOCUMENT_SUFFIX} files can be moved, to a {DOCUMENT_SUFFIX} name: {path!r} to {to!r}")
165
+ elif (source.suffix == DOCUMENT_SUFFIX) != (target.suffix == DOCUMENT_SUFFIX):
166
+ raise BadRequest(f"a file cannot gain or lose the {DOCUMENT_SUFFIX} extension: {path!r} to {to!r}")
167
167
  if target == source:
168
168
  return self.relative(target)
169
169
  # On a file system that ignores case, a new case of the name is the same item
@@ -176,50 +176,39 @@ class Storage:
176
176
  # -- delete --------------------------------------------------------------
177
177
 
178
178
  def delete_file(self, path: str) -> None:
179
- """Move a document to the trash. Its folder stays, even if left empty."""
179
+ """Move a file to the trash. Its folder stays, even if left empty."""
180
180
  source = self._item(path)
181
181
  if not os.path.lexists(source):
182
182
  raise NotFound(f"no such file: {path!r}")
183
183
  if source.is_dir():
184
184
  raise BadRequest(f"is a folder: {path!r}")
185
- if source.suffix != DOCUMENT_SUFFIX:
186
- raise BadRequest(f"only {DOCUMENT_SUFFIX} files can be deleted: {path!r}")
187
185
  self._to_trash(source, self._new_trash())
188
186
 
189
187
  def delete_folder(self, path: str) -> dict:
190
- """Move every document in a folder to the trash, at any depth, and remove
191
- the folders this leaves with nothing in them. Other files, hidden entries
192
- and links to folders stay, and so do the folders that hold them."""
188
+ """Move a folder to the trash with everything in it: documents, other
189
+ files and hidden entries; links go as links. `deleted` is the number of
190
+ files in it, at any depth. A folder with no files at all is removed."""
193
191
  folder = self._item(path)
194
192
  if not os.path.lexists(folder):
195
193
  raise NotFound(f"no such folder: {path!r}")
196
194
  if folder.is_symlink() or not folder.is_dir():
197
195
  raise BadRequest(f"not a folder: {path!r}")
198
- documents: list[Path] = []
199
- folders: list[Path] = []
200
- self._collect(folder, documents, folders)
201
- trash = self._new_trash() if documents else None
202
- for document in documents:
203
- self._to_trash(document, trash)
204
- for each in folders: # the deepest first
205
- try:
206
- each.rmdir()
207
- except OSError:
208
- pass # still holds something
209
- return {"deleted": len(documents), "removed": not folder.exists()}
210
-
211
- def _collect(self, folder: Path, documents: list[Path], folders: list[Path]) -> None:
212
- """Add the documents under `folder`, and its folders with the deepest
213
- first. What the tree does not list as a document or a folder is left."""
214
- for entry in folder.iterdir():
215
- if self._hidden(entry.name):
216
- continue
217
- if entry.is_dir():
218
- if not entry.is_symlink():
219
- self._collect(entry, documents, folders)
220
- elif entry.is_file() and entry.suffix == DOCUMENT_SUFFIX:
221
- documents.append(entry)
222
- folders.append(folder)
196
+ count = self._count_files(folder)
197
+ if count:
198
+ self._to_trash(folder, self._new_trash())
199
+ else:
200
+ shutil.rmtree(folder)
201
+ return {"deleted": count}
202
+
203
+ @staticmethod
204
+ def _count_files(folder: Path) -> int:
205
+ """The files under `folder`, at any depth, hidden ones and links
206
+ included; a link to a folder counts as a file and is not followed."""
207
+ count = 0
208
+ for here, dirs, files in os.walk(folder):
209
+ links = [d for d in dirs if (Path(here) / d).is_symlink()]
210
+ count += len(files) + len(links)
211
+ return count
223
212
 
224
213
  def _new_trash(self) -> Path:
225
214
  """A new folder in the trash for one deletion, named after its time."""
@@ -283,7 +272,7 @@ class Storage:
283
272
  continue
284
273
  if entry.is_dir():
285
274
  folders.append(self._folder(entry, None if depth is None else depth - 1))
286
- elif entry.is_file() and entry.suffix == DOCUMENT_SUFFIX:
275
+ elif entry.is_file():
287
276
  stat = entry.stat()
288
277
  modified = datetime.fromtimestamp(stat.st_mtime, timezone.utc)
289
278
  files.append({"name": entry.name, "path": self.relative(entry), "type": "file",
@@ -0,0 +1 @@
1
+ @font-face{font-family:Atkinson Hyperlegible Next Variable;font-style:normal;font-display:swap;font-weight:200 800;src:url(/_app/assets/atkinson-hyperlegible-next-latin-ext-wght-normal-C6vrW8VD.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Atkinson Hyperlegible Next Variable;font-style:normal;font-display:swap;font-weight:200 800;src:url(/_app/assets/atkinson-hyperlegible-next-latin-wght-normal-BcXVPD7q.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}@font-face{font-family:Atkinson Hyperlegible Next Variable;font-style:italic;font-display:swap;font-weight:200 800;src:url(/_app/assets/atkinson-hyperlegible-next-latin-ext-wght-italic-Cigfgs4r.woff2)format("woff2-variations");unicode-range:U+100-2BA,U+2BD-2C5,U+2C7-2CC,U+2CE-2D7,U+2DD-2FF,U+304,U+308,U+329,U+1D00-1DBF,U+1E00-1E9F,U+1EF2-1EFF,U+2020,U+20A0-20AB,U+20AD-20C0,U+2113,U+2C60-2C7F,U+A720-A7FF}@font-face{font-family:Atkinson Hyperlegible Next Variable;font-style:italic;font-display:swap;font-weight:200 800;src:url(/_app/assets/atkinson-hyperlegible-next-latin-wght-italic-DC5MiAaX.woff2)format("woff2-variations");unicode-range:U+??,U+131,U+152-153,U+2BB-2BC,U+2C6,U+2DA,U+2DC,U+304,U+308,U+329,U+2000-206F,U+20AC,U+2122,U+2191,U+2193,U+2212,U+2215,U+FEFF,U+FFFD}:root{--font:"Inter", system-ui, -apple-system, "Segoe UI", sans-serif;--radius:8px;--bar-height:3rem;--nav-width:16rem;--pane-width:20rem;--transition:.16s ease}:root[data-theme=light]{--lightningcss-light:initial;--lightningcss-dark: ;color-scheme:light;--bg:#f4f5f7;--surface:#fff;--surface-2:#f8f9fb;--border:#e3e6eb;--text:#1d2330;--text-muted:#687085;--text-faint:#9097a6;--hover:#0f172a0f;--active:#2563eb1a;--accent:#2563eb;--danger:#c2410c;--shadow:0 1px 3px #0000000f, 0 6px 24px #0000000f}:root[data-theme=dark]{--lightningcss-light: ;--lightningcss-dark:initial;color-scheme:dark;--bg:#14161b;--surface:#1b1e24;--surface-2:#22262e;--border:#2d323c;--text:#e4e7ec;--text-muted:#8b93a3;--text-faint:#6b7282;--hover:#ffffff0f;--active:#60a5fa24;--accent:#60a5fa;--danger:#fb923c;--shadow:0 1px 3px #0000004d, 0 6px 24px #00000040;--texl-paper:#1b1e24;--texl-line:#262a32;--texl-margin-line:#34507f;--texl-line-number:#4a5160;--texl-line-number-active:#8b93a3;--texl-accent:#60a5fa;--texl-selected-bg:#60a5fa12;--texl-selected-ring:#60a5fa66;--texl-edit-bg:#22262e;--texl-comment:#e0a64b;--texl-error:#fb923c;--texl-error-bg:#f8717126;--texl-rule:#8b93a3;--texl-text-muted:#8b93a3;--texl-hover-bg:#ffffff12;--texl-icon-active:#c4c9d4;--texl-menu-bg:#22262e;--texl-menu-border:#2d323c;--texl-menu-text:#e4e7ec;--texl-menu-icon:#8b93a3;--texl-menu-active-bg:#60a5fa24}html,body{height:100%;margin:0}body{background:var(--bg);color:var(--text);font-family:var(--font);-webkit-font-smoothing:antialiased;font-size:14px}