stilo-cli 0.3.0__tar.gz → 0.5.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 (96) hide show
  1. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/.gitignore +4 -0
  2. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/PKG-INFO +7 -2
  3. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/README.md +4 -0
  4. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/pyproject.toml +9 -4
  5. stilo_cli-0.5.0/src/stilo/cli/__init__.py +65 -0
  6. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/cli/commands.py +11 -19
  7. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/cli/project.py +26 -4
  8. stilo_cli-0.5.0/src/stilo/cli/tutor.py +155 -0
  9. stilo_cli-0.5.0/src/stilo/cli/web.py +41 -0
  10. stilo_cli-0.5.0/src/stilo/server/__init__.py +31 -0
  11. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/server/app.py +68 -30
  12. stilo_cli-0.5.0/src/stilo/server/extensions.py +67 -0
  13. stilo_cli-0.5.0/src/stilo/server/files.py +52 -0
  14. stilo_cli-0.5.0/src/stilo/server/storage.py +434 -0
  15. stilo_cli-0.5.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-ext-wght-italic-Cigfgs4r.woff2 +0 -0
  16. stilo_cli-0.5.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-ext-wght-normal-C6vrW8VD.woff2 +0 -0
  17. stilo_cli-0.5.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-wght-italic-DC5MiAaX.woff2 +0 -0
  18. stilo_cli-0.5.0/src/stilo/web/assets/atkinson-hyperlegible-next-latin-wght-normal-BcXVPD7q.woff2 +0 -0
  19. stilo_cli-0.3.0/src/stilo/web/assets/index-BT3YAPgN.js → stilo_cli-0.5.0/src/stilo/web/assets/index-BZH77VUo.js +1004 -659
  20. stilo_cli-0.5.0/src/stilo/web/assets/index-DQjFAUo6.css +1 -0
  21. stilo_cli-0.5.0/src/stilo/web/assets/texl_wasm_bg-DmpBGblw.wasm +0 -0
  22. stilo_cli-0.5.0/src/stilo/web/favicon.svg +1 -0
  23. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/index.html +4 -5
  24. stilo_cli-0.5.0/texl-lib/charts.texl +161 -0
  25. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/texl-lib/dataframe.texl +14 -10
  26. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/texl-lib/index.texl +6 -3
  27. stilo_cli-0.5.0/tutorial/01-welcome.texl +73 -0
  28. stilo_cli-0.5.0/tutorial/02-cells.texl +79 -0
  29. stilo_cli-0.5.0/tutorial/03-rich-text.texl +57 -0
  30. stilo_cli-0.5.0/tutorial/04-formulas.texl +75 -0
  31. stilo_cli-0.5.0/tutorial/05-cell-types.texl +56 -0
  32. stilo_cli-0.5.0/tutorial/06-tables-and-equations.texl +77 -0
  33. stilo_cli-0.5.0/tutorial/07-data-tables.texl +107 -0
  34. stilo_cli-0.5.0/tutorial/08-linking.texl +66 -0
  35. stilo_cli-0.5.0/tutorial/09-errors.texl +56 -0
  36. stilo_cli-0.5.0/tutorial/10-organising.texl +86 -0
  37. stilo_cli-0.5.0/tutorial/11-command-line.texl +81 -0
  38. stilo_cli-0.5.0/tutorial/12-your-first-project.texl +72 -0
  39. stilo_cli-0.5.0/tutorial/13-formula-language.texl +77 -0
  40. stilo_cli-0.5.0/tutorial/14-libraries.texl +57 -0
  41. stilo_cli-0.5.0/tutorial/files/beam-drawing.pdf +50 -0
  42. stilo_cli-0.5.0/tutorial/files/beam.svg +18 -0
  43. stilo_cli-0.5.0/tutorial/files/report.texl +15 -0
  44. stilo_cli-0.5.0/tutorial/index.texl +62 -0
  45. stilo_cli-0.5.0/tutorial/lib/steel/sections.texl +17 -0
  46. stilo_cli-0.5.0/tutorial/lib/tutorial/index.texl +36 -0
  47. stilo_cli-0.3.0/src/stilo/cli/__init__.py +0 -18
  48. stilo_cli-0.3.0/src/stilo/server/__init__.py +0 -5
  49. stilo_cli-0.3.0/src/stilo/server/storage.py +0 -293
  50. stilo_cli-0.3.0/src/stilo/web/assets/index-kR4PIGIs.css +0 -1
  51. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-ext-opsz-italic-5yUt4G_9.woff2 +0 -0
  52. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-ext-opsz-normal-C5tfwALZ.woff2 +0 -0
  53. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-opsz-italic-Bj0ndbyp.woff2 +0 -0
  54. stilo_cli-0.3.0/src/stilo/web/assets/literata-cyrillic-opsz-normal-DgmypKXX.woff2 +0 -0
  55. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-ext-opsz-italic-DFpO5j-Z.woff2 +0 -0
  56. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-ext-opsz-normal-DGm64vGR.woff2 +0 -0
  57. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-opsz-italic-CHERNRFq.woff2 +0 -0
  58. stilo_cli-0.3.0/src/stilo/web/assets/literata-greek-opsz-normal-DFglUmAd.woff2 +0 -0
  59. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-ext-opsz-italic-4y8iAqqs.woff2 +0 -0
  60. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-ext-opsz-normal-STiTPs0F.woff2 +0 -0
  61. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-opsz-italic-CJ93D38p.woff2 +0 -0
  62. stilo_cli-0.3.0/src/stilo/web/assets/literata-latin-opsz-normal-BHZsWIlc.woff2 +0 -0
  63. stilo_cli-0.3.0/src/stilo/web/assets/literata-vietnamese-opsz-italic-BdcrZMcO.woff2 +0 -0
  64. stilo_cli-0.3.0/src/stilo/web/assets/literata-vietnamese-opsz-normal-Gqw5JQlq.woff2 +0 -0
  65. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-cyrillic-ext-wght-normal-c-5QAGAI.woff2 +0 -0
  66. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-cyrillic-wght-normal-BMDVbyM7.woff2 +0 -0
  67. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-greek-ext-wght-normal-BXZfsJY4.woff2 +0 -0
  68. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-greek-wght-normal-Cc-u-6OI.woff2 +0 -0
  69. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-latin-ext-wght-normal-C8iNium2.woff2 +0 -0
  70. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-latin-wght-normal-Bo_j9asI.woff2 +0 -0
  71. stilo_cli-0.3.0/src/stilo/web/assets/source-sans-3-vietnamese-wght-normal-BDs68eHQ.woff2 +0 -0
  72. stilo_cli-0.3.0/src/stilo/web/assets/texl_wasm_bg-DXo4-iTL.wasm +0 -0
  73. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/LICENSE +0 -0
  74. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/__init__.py +0 -0
  75. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/__main__.py +0 -0
  76. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/cli/errors.py +0 -0
  77. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/server/home.py +0 -0
  78. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  79. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  80. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  81. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  82. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  83. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  84. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  85. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  86. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  87. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  88. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  89. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  90. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  91. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  92. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  93. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  94. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  95. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  96. {stilo_cli-0.3.0 → stilo_cli-0.5.0}/src/stilo/web/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
@@ -7,6 +7,7 @@ __pycache__/
7
7
 
8
8
  # Node
9
9
  web/node_modules/
10
+ web/LICENSE
10
11
  src/stilo/web/
11
12
 
12
13
  # Editors and OS
@@ -18,3 +19,6 @@ src/stilo/web/
18
19
  local/
19
20
  *.todo.md
20
21
 
22
+
23
+ # Files deleted by the server (stilo serve moves them here)
24
+ .trash/
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: stilo-cli
3
- Version: 0.3.0
3
+ Version: 0.5.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.10.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.5.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.10.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.
@@ -0,0 +1,65 @@
1
+ """The `stilo` command line: one subcommand per `Command`, Stilo's own in
2
+ `COMMANDS`, then those of other packages (docs/cli.md).
3
+
4
+ The names in `__all__` are the CLI's public API, what a plugin may use;
5
+ `tests/cli/test_plugins.py` pins the list.
6
+ """
7
+
8
+ import argparse
9
+ import sys
10
+ from importlib.metadata import entry_points
11
+
12
+ from .commands import COMMANDS, Command
13
+ from .project import create_engine
14
+ from .web import WEB_DIST, run_server
15
+
16
+ __all__ = ["Command", "COMMANDS", "main", "create_engine", "WEB_DIST", "run_server"]
17
+
18
+ # The entry-point group through which other packages add commands
19
+ PLUGIN_GROUP = "stilo.commands"
20
+
21
+
22
+ def plugin_commands(taken: set[str]) -> list[Command]:
23
+ """The commands of installed packages, from the entry-point group
24
+ `stilo.commands`, each entry point a `Command`, sorted by name. One that
25
+ fails to load, is not a `Command`, or takes a name already in `taken`
26
+ (Stilo's own commands, or a plugin's that came first) is skipped with a
27
+ warning on standard error."""
28
+ taken = set(taken)
29
+ found = []
30
+ for point in entry_points(group=PLUGIN_GROUP):
31
+ where = f"{point.name} ({point.dist.name})" if getattr(point, "dist", None) else point.name
32
+ try:
33
+ command = point.load()
34
+ except Exception as e: # a broken plugin must not break stilo
35
+ _skip(where, f"{type(e).__name__}: {e}")
36
+ continue
37
+ if not isinstance(command, Command):
38
+ _skip(where, "not a stilo.cli.Command")
39
+ continue
40
+ found.append((command.name, where, command))
41
+ plugins = []
42
+ for name, where, command in sorted(found, key=lambda entry: (entry[0], entry[1])):
43
+ if name in taken:
44
+ _skip(where, f"the command {name!r} already exists")
45
+ continue
46
+ taken.add(name)
47
+ plugins.append(command)
48
+ return plugins
49
+
50
+
51
+ def _skip(where: str, reason: str) -> None:
52
+ print(f"stilo: plugin {where} skipped: {reason}", file=sys.stderr)
53
+
54
+
55
+ def main(argv=None) -> int:
56
+ parser = argparse.ArgumentParser(
57
+ prog="stilo", description="Edit and render a folder of linked Texl documents.")
58
+ subparsers = parser.add_subparsers(dest="command", required=True)
59
+ commands = COMMANDS + plugin_commands({command.name for command in COMMANDS})
60
+ for command in commands:
61
+ sub = subparsers.add_parser(command.name, help=command.help)
62
+ command.add_arguments(sub)
63
+ sub.set_defaults(run=command.run)
64
+ args = parser.parse_args(argv)
65
+ return args.run(args)
@@ -1,28 +1,25 @@
1
1
  """The `stilo` subcommands.
2
2
 
3
3
  Each command is a `Command`: a name, a help line, a function that adds its
4
- arguments to a parser and a function that runs it. `COMMANDS` lists them in
5
- the order `stilo --help` shows them; a plugin system can later add its own.
4
+ arguments to a parser and a function that runs it. `COMMANDS` lists Stilo's own, in
5
+ the order `stilo --help` shows them; other packages add theirs through the
6
+ entry-point group `stilo.commands` (`__init__.py`, `plugin_commands`).
6
7
  """
7
8
 
8
9
  import asyncio
9
- import shutil
10
10
  import sys
11
11
  from dataclasses import dataclass
12
12
  from pathlib import Path
13
13
  from typing import Callable
14
14
 
15
15
  import pytexl
16
- import uvicorn
17
16
 
18
17
  from stilo.server import create_app
19
18
 
20
19
  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"
20
+ from .project import LIB, LIBRARY_NAME, MANIFEST, create_engine, make_project
21
+ from .tutor import tutor, tutor_arguments
22
+ from .web import WEB_DIST, run_server
26
23
 
27
24
 
28
25
  @dataclass
@@ -93,8 +90,9 @@ def serve(args) -> int:
93
90
  if not args.folder.is_dir():
94
91
  print(f"stilo: {args.folder}: not a folder", file=sys.stderr)
95
92
  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)
93
+ print(f"Stilo: serving {args.folder.resolve()} at http://{args.host}:{args.port}/ "
94
+ "(press Ctrl+C here to stop)")
95
+ run_server(create_app(args.folder, args.web), args.host, args.port)
98
96
  return 0
99
97
 
100
98
 
@@ -111,15 +109,8 @@ def init(args) -> int:
111
109
  if (folder / MANIFEST).exists():
112
110
  print(f"stilo: {args.folder}: already a project ({MANIFEST} exists)", file=sys.stderr)
113
111
  return 1
114
- library = folder / LIB / LIBRARY_NAME
115
112
  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)
113
+ kept = make_project(folder, args.name or folder.name)
123
114
  except OSError as e:
124
115
  print(f"stilo: {args.folder}: {e}", file=sys.stderr)
125
116
  return 1
@@ -133,4 +124,5 @@ COMMANDS = [
133
124
  Command("init", "make a folder a Stilo project, with the Stilo library", init_arguments, init),
134
125
  Command("render", "render a Texl document", render_arguments, render),
135
126
  Command("serve", "serve a folder of Texl documents with the web app", serve_arguments, serve),
127
+ Command("tutor", "learn Stilo: open the tutorial in the web app", tutor_arguments, tutor),
136
128
  ]
@@ -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,155 @@
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 stilo.server import create_app
21
+
22
+ from .project import MANIFEST, PACKAGE, make_project, stilo_version, swan_text
23
+ from .web import WEB_DIST, run_server
24
+
25
+ _INSTALLED_TUTORIAL = PACKAGE / "tutorial"
26
+ TUTORIAL = _INSTALLED_TUTORIAL if _INSTALLED_TUTORIAL.is_dir() else PACKAGE.parents[1] / "tutorial"
27
+
28
+ PROJECT_NAME = "Stilo tutorial"
29
+ INDEX = "index.texl"
30
+
31
+ # The value `stilo tutor` adds to the copy's project.texl: the folder of the
32
+ # copy, shown by the command-line lessons. It also tells a copy from any
33
+ # other folder.
34
+ FOLDER_NAME = "tutorial_folder"
35
+ _FOLDER_VALUE = re.compile(rf"<%\s*{FOLDER_NAME}\s*=")
36
+ _VERSION_VALUE = re.compile(r'stilo_version\s*=\s*"([^"]*)"')
37
+
38
+
39
+ def default_folder() -> Path:
40
+ """Where the copy goes by default: `tutorial` in Stilo's user data folder."""
41
+ return platformdirs.user_data_path("stilo", appauthor=False) / "tutorial"
42
+
43
+
44
+ def is_copy(folder: Path) -> bool:
45
+ """Whether `folder` is a working copy of the tutorial."""
46
+ try:
47
+ return bool(_FOLDER_VALUE.search((folder / MANIFEST).read_text(encoding="utf-8")))
48
+ except OSError:
49
+ return False
50
+
51
+
52
+ def is_empty(folder: Path) -> bool:
53
+ return not folder.exists() or (folder.is_dir() and not any(folder.iterdir()))
54
+
55
+
56
+ def create_copy(folder: Path):
57
+ """Copies the tutorial into `folder` (missing or empty) and makes it a project."""
58
+ shutil.copytree(TUTORIAL, folder, dirs_exist_ok=True)
59
+ make_project(folder, PROJECT_NAME)
60
+ with open(folder / MANIFEST, "a", encoding="utf-8") as file:
61
+ file.write(f'<% {FOLDER_NAME} = "{swan_text(str(folder))}" %>\n')
62
+
63
+
64
+ def move_aside(folder: Path) -> Path:
65
+ """Renames `folder` to a free name next to it, with the date and time."""
66
+ stamp = datetime.now().strftime("%Y%m%d-%H%M%S")
67
+ target = folder.with_name(f"{folder.name}-old-{stamp}")
68
+ n = 1
69
+ while target.exists():
70
+ n += 1
71
+ target = folder.with_name(f"{folder.name}-old-{stamp}-{n}")
72
+ folder.rename(target)
73
+ return target
74
+
75
+
76
+ def copy_version(folder: Path) -> str | None:
77
+ """The `stilo_version` written in the copy's project.texl, if any."""
78
+ try:
79
+ match = _VERSION_VALUE.search((folder / MANIFEST).read_text(encoding="utf-8"))
80
+ except OSError:
81
+ return None
82
+ return match.group(1) if match else None
83
+
84
+
85
+ def version_key(text: str) -> tuple[int, ...]:
86
+ """A version for comparison: its leading numbers, `0.3.0rc1` as (0, 3, 0)."""
87
+ numbers = []
88
+ for part in text.split("."):
89
+ digits = re.match(r"\d+", part)
90
+ if not digits:
91
+ break
92
+ numbers.append(int(digits.group()))
93
+ return tuple(numbers)
94
+
95
+
96
+ def is_older(version: str | None, than: str) -> bool:
97
+ return version_key(version or "0") < version_key(than)
98
+
99
+
100
+ def prepare(folder: Path, reset: bool, out=None, err=None) -> bool:
101
+ """Makes sure `folder` holds a working copy, as `stilo tutor` does before
102
+ serving it. Says what it did on `out` (standard output); returns False
103
+ on an error, reported on `err` (standard error)."""
104
+ out, err = out or sys.stdout, err or sys.stderr
105
+ if folder.exists() and not folder.is_dir():
106
+ print(f"stilo: {folder}: not a folder", file=err)
107
+ return False
108
+ if not is_empty(folder) and not is_copy(folder):
109
+ print(f"stilo: {folder}: not a copy of the tutorial, and not empty: "
110
+ "choose another folder with --dir", file=err)
111
+ return False
112
+ try:
113
+ if reset and not is_empty(folder):
114
+ old = move_aside(folder)
115
+ print(f"Stilo: your old copy of the tutorial is now in {old}", file=out)
116
+ if is_empty(folder):
117
+ create_copy(folder)
118
+ print(f"Stilo: a new copy of the tutorial is in {folder}", file=out)
119
+ return True
120
+ except OSError as e:
121
+ print(f"stilo: {folder}: {e}", file=err)
122
+ return False
123
+ print(f"Stilo: your copy of the tutorial is in {folder}", file=out)
124
+ version, installed = copy_version(folder), stilo_version()
125
+ if is_older(version, installed):
126
+ print(f"Stilo: this copy was made by Stilo {version or '(unknown)'}, and Stilo "
127
+ f"{installed} may have changed lessons. To start again with the new "
128
+ f"lessons, run: stilo tutor --reset (your copy will be kept, moved aside)",
129
+ file=out)
130
+ return True
131
+
132
+
133
+ def tutor_arguments(parser):
134
+ parser.add_argument("--dir", type=Path, default=None,
135
+ help="folder of your copy of the tutorial (default: "
136
+ f"{default_folder()})")
137
+ parser.add_argument("--reset", action="store_true",
138
+ help="start again from a fresh copy; the old one is moved aside, not deleted")
139
+ parser.add_argument("--port", type=int, default=8000)
140
+ parser.add_argument("--no-browser", action="store_true",
141
+ help="do not open the browser")
142
+
143
+
144
+ def tutor(args) -> int:
145
+ """Copies the tutorial if needed, serves the copy and opens its index."""
146
+ folder = (args.dir or default_folder()).expanduser().resolve()
147
+ if not prepare(folder, args.reset):
148
+ return 1
149
+ host = "127.0.0.1"
150
+ url = f"http://{host}:{args.port}/{INDEX}"
151
+ print(f"Stilo: the tutorial is at {url} (press Ctrl+C here to stop)")
152
+ sys.stdout.flush()
153
+ run_server(create_app(folder, WEB_DIST), host, args.port,
154
+ open_url=None if args.no_browser else url)
155
+ return 0
@@ -0,0 +1,41 @@
1
+ """Serving a folder with the web app, for `stilo serve`, `stilo tutor` and
2
+ the commands of plugins."""
3
+
4
+ import threading
5
+ import time
6
+ import webbrowser
7
+ from pathlib import Path
8
+
9
+ import uvicorn
10
+
11
+ from stilo.server import create_app
12
+
13
+ # The built web app, `stilo/web`: written there by `npm run build` in a
14
+ # checkout, shipped there in the package
15
+ WEB_DIST = Path(__file__).resolve().parents[1] / "web"
16
+
17
+
18
+ def run_server(app, host: str, port: int, open_url: str | None = None):
19
+ """Serves `app` (from `create_app()`, or any ASGI app) until the process
20
+ is stopped. With `open_url`, opens it in the browser once the server
21
+ accepts connections. Ctrl+C stops it with a goodbye instead of a
22
+ traceback. A plugin's command serves a folder with its own server
23
+ extensions as `run_server(create_app(folder, WEB_DIST, extensions=[...]),
24
+ host, port)`."""
25
+ server = uvicorn.Server(uvicorn.Config(app, host=host, port=port))
26
+ if open_url:
27
+ threading.Thread(target=_open_when_started, args=(server, open_url), daemon=True).start()
28
+ try:
29
+ server.run()
30
+ except KeyboardInterrupt:
31
+ # uvicorn has already shut down cleanly; it re-raises the interrupt
32
+ # for its caller, and asyncio raises it out of a CancelledError
33
+ print("Stilo: stopped. Goodbye!")
34
+
35
+
36
+ def _open_when_started(server, url):
37
+ while not server.should_exit:
38
+ if server.started:
39
+ webbrowser.open(url)
40
+ return
41
+ time.sleep(0.1)
@@ -0,0 +1,31 @@
1
+ """Stilo server: Texl documents over HTTP (docs/server.md).
2
+
3
+ The names below are the server's public API: what a server extension, a
4
+ storage of another kind or another server that speaks the protocol may use.
5
+ `tests/server/test_public_api.py` pins the list; a change to it is
6
+ deliberate.
7
+ """
8
+
9
+ from .app import CAPABILITIES, PROTOCOL, VERSION, create_app
10
+ from .extensions import ServerExtension, get_storage
11
+ from .files import (DOCUMENT_SUFFIX, FILE_TYPES, NO_CACHE, etag, is_document, media_type,
12
+ other_file_response)
13
+ from .home import HOME, MANIFEST, MAX_HOMES, HomeCycle, expand_home, has_home, home_of
14
+ from .storage import (BadRequest, Conflict, FolderStorage, Forbidden, NotFound,
15
+ PreconditionFailed, Storage, StorageError, StorageWrapper)
16
+
17
+ __all__ = [
18
+ # The app
19
+ "create_app", "PROTOCOL", "VERSION", "CAPABILITIES",
20
+ # Server extensions
21
+ "ServerExtension", "get_storage",
22
+ # Storages
23
+ "Storage", "FolderStorage", "StorageWrapper",
24
+ # Errors a storage raises, with their HTTP status
25
+ "StorageError", "BadRequest", "Forbidden", "NotFound", "Conflict", "PreconditionFailed",
26
+ # Files by their public URL
27
+ "DOCUMENT_SUFFIX", "is_document", "etag", "FILE_TYPES", "media_type",
28
+ "other_file_response", "NO_CACHE",
29
+ # The project home, `~` in paths
30
+ "MANIFEST", "HOME", "MAX_HOMES", "HomeCycle", "home_of", "expand_home", "has_home",
31
+ ]