Rebuild the UI on vendored Textual; make the checkout self-contained
The internal servers have no access to outside package repositories and run Python 3.8/3.9, so the UI moves from hand-drawn curses to Textual 6.2.1 (the last release supporting 3.8.1), vendored with its pure-Python dependencies in vendor/. The launcher puts vendor/ first on sys.path, so a plain checkout runs with no pip and no network. - dsflow/: the single script split into a package (pure moves of the backend sections); action rules moved to ops.py, free of Textual - dsflow/ui/: tabs, detail pane, live sanity-run panel, log viewer, modal dialogs, filter, themes, mouse support - tests/test_ui.py: headless UI tests through Textual's pilot - tools/vendor.py (refresh vendor/), tools/screenshots.py (README images) - README, CLAUDE.md, TODO and the feature doc updated for the new layout, the Python 3.8.1 floor and the vendoring rules Verified: 11 tests green on Python 3.12 and 3.8.20; the shipped file set runs under `python -I -S` on both. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
275d42aeb4
commit
60532a4043
926 files changed
+272979
-2540
No files matched your search
@@ -0,0 +1,2 @@
|
||||
vendor/** linguist-vendored
|
||||
docs/screenshots/*.svg linguist-generated
|
||||
@@ -1,9 +1,11 @@
|
||||
# CLAUDE.md — rules for all agents working on dsflow_tui
|
||||
|
||||
dsflow_tui is a single-file curses TUI for the `dsflow` DesignSync check-in
|
||||
flow: it lists a designer's changes and locks, runs sanity in a detached
|
||||
runner that locks the files while it runs, and checks in or tags the result.
|
||||
Read `README.md` for usage and `TODO.md` for the backlog before doing
|
||||
dsflow_tui is a Textual TUI for the `dsflow` DesignSync check-in flow: it
|
||||
lists a designer's changes and locks, runs sanity in a detached runner that
|
||||
locks the files while it runs, and checks in or tags the result. It ships as
|
||||
a self-contained checkout (dependencies vendored in `vendor/`) because the
|
||||
internal servers have no access to outside package repositories. Read
|
||||
`README.md` for usage and layout, and `TODO.md` for the backlog, before doing
|
||||
anything. `files.zip` holds the original `dsflow` plan (bash `dsflow`,
|
||||
`dsflow_ci`, `dsflow.conf`) this tool must stay compatible with.
|
||||
|
||||
@@ -37,60 +39,70 @@ anything. `files.zip` holds the original `dsflow` plan (bash `dsflow`,
|
||||
|
||||
- Prefer the boring, obvious implementation. If you're building an
|
||||
abstraction for a second user that doesn't exist yet, stop.
|
||||
- **Standard library only, Python 3.6 floor.** Designers copy one file
|
||||
onto locked-down EDA hosts with no pip. No third-party imports in
|
||||
`dsflow_tui.py`; `vermin -t=3.6-` must stay clean. Test tooling may use
|
||||
more, but the tests themselves stay on `unittest`.
|
||||
- **Nothing is installed at run time.** A plain checkout must run with no
|
||||
pip, no virtualenv and no network. Runtime dependencies live only in
|
||||
`vendor/`, pinned in `vendor/requirements.txt`, pure Python, licenses
|
||||
kept. Adding or bumping one is a lead decision with a written reason in
|
||||
the feature README; `tools/vendor.py` is the only way to change
|
||||
`vendor/`. Never edit vendored code by hand.
|
||||
- **Python 3.8.1 floor** (the oldest server Python). `vermin -t=3.8-` stays
|
||||
clean, and the pins in `vendor/requirements.txt` must support 3.8.1:
|
||||
Textual 6.2.1 is the last line that does. Only `dsflow/ui/` may import
|
||||
Textual or Rich; the runner, `status` and `ops` stay standard library so
|
||||
they keep working if the UI can't load.
|
||||
- **Bash snippets run on bash 3.2** (macOS dev machines): no `mapfile`,
|
||||
no associative arrays, no `${var,,}`.
|
||||
- Small functions, descriptive names, shallow nesting. Code should be
|
||||
readable top-to-bottom without jumping around.
|
||||
- Match the style of the surrounding code (comment density, naming,
|
||||
section layout).
|
||||
module layout).
|
||||
|
||||
## File and function size
|
||||
|
||||
The tool ships as **one file on purpose**: one file is what gets copied
|
||||
onto EDA hosts. So the unit a reader navigates is the **section**, the
|
||||
banner-commented block (`# ---- Flow: ...`), not the file.
|
||||
|
||||
- **Sections: target 300–600 production lines.** A section has to be
|
||||
describable in one sentence. Several "and" clauses mean it wants to be
|
||||
two sections.
|
||||
- **Files: target 300–600 production lines.** At 800, split. A module has
|
||||
to be describable in one sentence; several "and" clauses mean it wants
|
||||
to be two modules.
|
||||
- **Functions: 10–50 lines.** Investigate anything over 80; anything over
|
||||
150 needs a reason in a comment.
|
||||
- Looser for declarative tables and embedded fixtures (`COLOR_SPEC`,
|
||||
`FAKE_DSSC`, `DEMO_CONF`).
|
||||
- Looser for declarative tables and embedded fixtures (`FAKE_DSSC`,
|
||||
`DEMO_CONF`, `styles.tcss`).
|
||||
- A split is a **pure move**: behaviour and screen output identical, the
|
||||
test count does not drop, all tests green.
|
||||
- If the file itself becomes the problem, splitting into a package is a
|
||||
lead decision: it breaks the "copy one file" deployment and needs a
|
||||
zipapp or install story first.
|
||||
|
||||
Measured 2026-09-23 (non-blank, non-comment lines): file 2 219. Sections:
|
||||
the app (`App`) 883, demo sandbox 238, Flow 228, Runner 304, form 164,
|
||||
look & feel 158, the rest under 70. **`App` is over the mark**: split it
|
||||
into views (drawing) and actions (dialogs and background work) before
|
||||
adding a feature to it. Functions over 80: `Runner.execute` 99 and
|
||||
`App.draw_files` 90, both candidates for the next pure move.
|
||||
Measured 2026-09-24 (non-blank, non-comment lines), after the move from one
|
||||
file to the `dsflow/` package: `ui/app.py` 482, `ui/widgets.py` 380,
|
||||
`runner.py` 317, `flow.py` 267, `demo.py` 243, `ui/dialogs.py` 189,
|
||||
`ops.py` 102, `common.py` 100, `cli.py` 91. `ui/app.py` is the one to
|
||||
watch: new actions go into `ops.py` (rules) and a dialog, not into the app.
|
||||
Functions over 80: `Runner.execute` 99, the next pure-move candidate.
|
||||
|
||||
## Python standards
|
||||
|
||||
Before declaring any work finished:
|
||||
|
||||
- `python3 -m py_compile dsflow_tui.py` clean
|
||||
- `vermin --no-tips -t=3.6- --violations dsflow_tui.py` clean
|
||||
(`pip install vermin` into a dev venv; never a runtime dependency)
|
||||
- `tools/guard.py -- python3 -m unittest discover -s tests -v` green
|
||||
- `python3 -m py_compile` clean on everything you touched
|
||||
- `vermin --no-tips -t=3.8- --violations dsflow dsflow_tui.py tools tests`
|
||||
clean (`pip install vermin` into a dev venv; never a runtime dependency)
|
||||
- `tools/guard.py -- python3 -m unittest discover -s tests -v` green, on
|
||||
the newest Python you have **and on a Python 3.8** (e.g.
|
||||
`conda create -p <scratch>/py38 python=3.8`)
|
||||
- `./dsflow_tui.py --demo --demo-reset` opened and driven by hand across
|
||||
every tab you touched
|
||||
every tab you touched; for visual changes, regenerate
|
||||
`docs/screenshots/` with `tools/screenshots.py` and look at them
|
||||
|
||||
Code rules:
|
||||
|
||||
- No bare `except:`. A broad `except Exception` needs a `# noqa` comment
|
||||
that says why; the runner's is there so locks are always released.
|
||||
- Curses calls happen only on the main thread. Background threads change
|
||||
plain attributes, and the next frame draws them.
|
||||
- **Textual rules** (each one cost a bug on 2026-09-24):
|
||||
- UI changes happen on the main thread. Workers hand results back with
|
||||
`App.to_ui()`, which is a no-op once the app is shutting down.
|
||||
- Don't name attributes after Textual's own: `auto_refresh`, `rows` and
|
||||
`title` on the wrong class silently break the app.
|
||||
- Event handlers use the widget references taken in `on_mount`, not DOM
|
||||
queries; events can arrive while the app is tearing down.
|
||||
- TabbedContent follows focus. Switching tabs from a dialog callback
|
||||
must also move focus (`action_show_tab` does).
|
||||
- Every `subprocess` that can run long gets `start_new_session=True` so
|
||||
it can be killed as a process group.
|
||||
- Public classes and non-obvious functions get a one-line docstring that
|
||||
@@ -140,7 +152,8 @@ Rules:
|
||||
section and stop.
|
||||
- New behavior needs tests in the same change. Anything touching the
|
||||
runner, locking or check-in gets a `tests/test_runner.py` case that
|
||||
proves invariants 1–3 still hold for it.
|
||||
proves invariants 1–3 still hold for it; a new key, dialog or tab gets a
|
||||
`tests/test_ui.py` case driven through Textual's pilot.
|
||||
- Update `TODO.md`: check items your feature completes (leave the item
|
||||
text intact).
|
||||
|
||||
|
||||
@@ -1,24 +1,29 @@
|
||||
# dsflow_tui
|
||||
|
||||
A terminal UI for the `dsflow` DesignSync check-in flow. It lets a designer
|
||||
see their changes and locks, fire a sanity regression that locks the files
|
||||
while it runs, and check in or tag the result without typing `dssc`.
|
||||
A terminal UI for the `dsflow` DesignSync check-in flow. Designers see their
|
||||
changes and locks, fire a sanity regression that locks the files while it
|
||||
runs, and check in or tag the result without typing `dssc`. Mouse and
|
||||
keyboard both work.
|
||||
|
||||
One file, Python 3.6+ standard library only (curses), plus bash. Copy
|
||||
`dsflow_tui.py` next to `dsflow` and it runs; there is nothing to install.
|
||||

|
||||
|
||||
```
|
||||
◆ dsflow │ ws ~/ws/wifi_mac │ lucio │ Trunk:Latest │ green tag: working updated 12:03:11 (1.5s)
|
||||
1 Changes 5 2 Locks 1 3 Checked-out 4 4 Sanity run ⠹ 5 Logs
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
St File Base → Latest Lock Flags
|
||||
◉ M rtl/rx/rx_fsm.sv 1.4 latest you IN-RUN
|
||||
◉ M rtl/top/wifi_mac_top.sv 1.12 latest you HOT IN-RUN
|
||||
○ M rtl/tx/tx_ctrl.sv 1.7 → 1.8 — STALE
|
||||
○ A rtl/rx/rx_agg.sv new file —
|
||||
────────────────────────────────────────────────────────────────────────────────────────────────
|
||||
⠹ SANITY Sanity kibo_2x2 ████████░░░░░░░░ 0/2 cfg │ 3m10s │ 1 locked by run 2 selected
|
||||
spc mark a all s sanity c check in t tag n add new m rebase r refresh
|
||||
**Self-contained.** The UI library ([Textual](https://textual.textualize.io/))
|
||||
and everything it needs are vendored in `vendor/`. A plain checkout runs with
|
||||
no pip, no virtualenv and no network, which is what the internal servers
|
||||
allow.
|
||||
|
||||
**Needs:** Python 3.8.1 or newer, bash, and a UTF-8 terminal (xterm, VNC,
|
||||
SSH from any modern terminal). `status` and the sanity runner work without
|
||||
Textual, so they also run on older Python.
|
||||
|
||||
## Install
|
||||
|
||||
Clone or copy the whole repository somewhere on the shared filesystem, then
|
||||
run the launcher from a workspace root. A symlink on your `PATH` works too:
|
||||
|
||||
```bash
|
||||
git clone [email protected]:lucio/dssc.git /proj/tools/dsflow_tui
|
||||
ln -s /proj/tools/dsflow_tui/dsflow_tui.py ~/bin/dsflow_tui
|
||||
```
|
||||
|
||||
## Try it (demo)
|
||||
@@ -58,12 +63,14 @@ dsflow_tui.py --sanity-cmd 'sim/regress.sh --cfg {cfg}'
|
||||
| `--conf FILE` | `dsflow.conf` (default: `$DSFLOW_CONF`, else `<ws>/flow/dsflow.conf`) |
|
||||
| `--sanity-cmd CMD` | external sanity command; `{cfg}` and `{ws}` are substituted |
|
||||
| `--tags T1,T2` | tags offered for batch tagging (default: `DSFLOW_TAGS`) |
|
||||
| `--theme NAME` | colour theme (default `tokyo-night`; `ctrl+p` in the app switches live) |
|
||||
| `--auto-refresh SEC` | re-query DesignSync every SEC seconds (default: only on `r` and after actions) |
|
||||
|
||||
### Tabs
|
||||
|
||||
1. **Changes**: locally modified and newly added files, with base/latest
|
||||
version, lock holder and flags (`HOT`, `STALE`, `IN-RUN`, `MISSING`).
|
||||
version, lock holder and flags (`HOT`, `STALE`, `IN-RUN`, `MISSING`). The
|
||||
pane on the right shows everything about the highlighted file.
|
||||
2. **Locks**: your locks, plus every hot file and who holds it.
|
||||
3. **Checked-out**: writable copies you have not locked.
|
||||
4. **Sanity run**: each step of the current or last run, progress bars and a
|
||||
@@ -73,9 +80,13 @@ dsflow_tui.py --sanity-cmd 'sim/regress.sh --cfg {cfg}'
|
||||
|
||||
### Keys
|
||||
|
||||
The footer shows the keys that apply to the current tab; `?` lists them all.
|
||||
|
||||
| Key | Action |
|
||||
|---|---|
|
||||
| `space` / `a` / `esc` | mark a file / mark all in the tab / clear marks. With nothing marked, the cursor row is used. |
|
||||
| `space` / `enter` | mark or unmark the highlighted file. With nothing marked, actions use the highlighted row. |
|
||||
| `a` / `esc` | mark everything in the tab / clear marks |
|
||||
| `/` | filter the file tables by path |
|
||||
| `s` | run sanity on the marked changes |
|
||||
| `c` | check in marked files that a passing run already covers |
|
||||
| `t` | batch-tag the marked files with a tag from `DSFLOW_TAGS` |
|
||||
@@ -83,13 +94,22 @@ dsflow_tui.py --sanity-cmd 'sim/regress.sh --cfg {cfg}'
|
||||
| `n` | register brand-new files for check-in (same as `dsflow add`) |
|
||||
| `m` | rebase stale files onto `Trunk:Latest` (same as `dsflow rebase`) |
|
||||
| `x` | cancel the running sanity, or clean up after a lost runner |
|
||||
| `1`-`5`, `tab` | switch tabs |
|
||||
| `1`-`5` | switch tabs (or click them) |
|
||||
| `r` / `?` / `q` | refresh / help / quit |
|
||||
| `ctrl+p` | command palette: themes, keys, screenshot |
|
||||
|
||||
With the mouse: click a tab to switch, click a row to see its details, click
|
||||
the ○ column to mark it, and click buttons in dialogs.
|
||||
|
||||
## How a sanity run works
|
||||
|
||||
`s` asks for the configs, what to do on pass (check in, or unlock only),
|
||||
a comment and an optional tag, then starts a detached runner:
|
||||
`s` opens the run dialog. Type a comment and press enter to go with the
|
||||
defaults, or pick the configs, what to do on pass (check in, or unlock only)
|
||||
and an optional tag.
|
||||
|
||||

|
||||
|
||||
The TUI then starts a detached runner:
|
||||
|
||||
1. check the files are not stale on Trunk and not locked by someone else
|
||||
2. lock them (files you already held are left as they are)
|
||||
@@ -99,6 +119,8 @@ a comment and an optional tag, then starts a detached runner:
|
||||
or just stop there in unlock-only mode
|
||||
6. release every lock the run took, whatever happened
|
||||
|
||||

|
||||
|
||||
The runner does not depend on the TUI. Quit, lose the SSH session, reopen
|
||||
later: the run carries on and `status` shows where it is. If the runner
|
||||
itself dies, the TUI notices after 60 s without a heartbeat and `x` stops the
|
||||
@@ -149,12 +171,28 @@ In `<ws>/.dsflow/`, next to the bash `dsflow` state it shares (`new_files`,
|
||||
A run that covered all your changes on all configs also writes a
|
||||
`sanity.stamp` that `dsflow checkin` accepts.
|
||||
|
||||
## Repository layout
|
||||
|
||||
| Path | What |
|
||||
|---|---|
|
||||
| `dsflow_tui.py` | launcher: puts `vendor/` on `sys.path`, then runs `dsflow.cli` |
|
||||
| `dsflow/` | the tool: `flow` (dsflow.conf calls), `runner`, `ops` (action rules), `cli`, `demo` |
|
||||
| `dsflow/ui/` | the Textual front end: `app`, `widgets`, `dialogs`, `styles.tcss` |
|
||||
| `vendor/` | pinned pure-Python dependencies; see `vendor/requirements.txt` |
|
||||
| `tests/` | runner tests and headless UI tests, both against the demo sandbox |
|
||||
| `tools/` | `guard.py` (test guard), `vendor.py` (refresh `vendor/`), `screenshots.py` |
|
||||
| `files.zip` | the original `dsflow` plan scripts this tool builds on |
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
python3 -m unittest discover -s tests -v
|
||||
tools/guard.py -- python3 -m unittest discover -s tests -v
|
||||
```
|
||||
|
||||
The tests run the runner end to end against the demo sandbox. See
|
||||
`CLAUDE.md` for the rules and the dev loop. `files.zip` holds the original
|
||||
`dsflow` plan scripts this tool builds on.
|
||||
The runner tests run the sanity flow end to end; the UI tests drive the app
|
||||
headlessly with Textual's pilot. Both use the demo sandbox. See `CLAUDE.md`
|
||||
for the rules and the dev loop.
|
||||
|
||||
To update the vendored packages, edit the pins in `vendor/requirements.txt`
|
||||
and run `tools/vendor.py` on a machine with internet. It fetches wheels for
|
||||
Python 3.8 and refuses anything that is not pure Python. Commit the result.
|
||||
@@ -12,13 +12,15 @@ mismatch in `dsflow.conf`, not in the script.
|
||||
- [ ] `dssc ci` releases the lock after check-in (the run's unlock step tolerates either)
|
||||
- [ ] a stamp written by a full-coverage TUI run is accepted by `dsflow checkin` on the Linux host
|
||||
- [ ] runner survives logout on the EDA host (`start_new_session`, no SIGHUP from the batch system)
|
||||
- [ ] the servers' Python is >= 3.8.1 and `./dsflow_tui.py --demo` runs there from a plain checkout
|
||||
- [ ] Textual renders in the terminals designers use (xterm, VNC viewer, `$TERM` values, colours, mouse)
|
||||
|
||||
## §2 Structure (pure moves, see CLAUDE.md "File and function size")
|
||||
|
||||
- [ ] split the `App` section (883 lines) into views and actions
|
||||
- [x] split the `App` section (883 lines) into views and actions (superseded: the Textual rewrite split it into `ui/app.py`, `ui/widgets.py`, `ui/dialogs.py` and `ops.py`)
|
||||
- [ ] shorten `Runner.execute` (99 lines): one method per step
|
||||
- [ ] shorten `App.draw_files` (90 lines): one cell renderer per tab
|
||||
- [x] shorten `App.draw_files` (90 lines): one cell renderer per tab (superseded: `FileTable.cells` in `ui/widgets.py`)
|
||||
|
||||
## §3 Tests
|
||||
|
||||
- [ ] pty-driven TUI smoke test (open, mark, start a run, cancel), guarded, no third-party deps
|
||||
- [x] pty-driven TUI smoke test (open, mark, start a run, cancel), guarded, no third-party deps (done with Textual's pilot in `tests/test_ui.py`)
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
## Goal
|
||||
|
||||
Give designers one screen for the `dsflow` check-in flow: see local changes,
|
||||
Give designers one interactive screen (keyboard and mouse) for the `dsflow` check-in flow: see local changes,
|
||||
locks and checked-out copies; run sanity on chosen files with those files
|
||||
locked for the duration; then check in, tag, or just unlock. This replaces
|
||||
typing `dsflow precheckin` / `checkin` / `claim` / `release` by hand and
|
||||
@@ -23,6 +23,11 @@ makes "I forgot to release the lock" impossible.
|
||||
too. The run dialog warns; it does not stop the run.
|
||||
- The runner and TUI may be on different hosts sharing the workspace over
|
||||
NFS, so liveness is a heartbeat in the job file, not a pid check.
|
||||
- The servers have Python >= 3.8.1 (answer from the lead, 2026-09-24) and
|
||||
no access to outside package repositories, so Textual and its
|
||||
dependencies are vendored. **Unverified on the servers**: TODO §1.
|
||||
- Designers use a UTF-8 terminal that Textual can drive (xterm, VNC, SSH
|
||||
from a modern terminal). **Unverified**: TODO §1.
|
||||
|
||||
## Handshakes
|
||||
|
||||
@@ -39,6 +44,9 @@ Promises to bash `dsflow`: `.dsflow/new_files` stays a sorted path list;
|
||||
|
||||
Promises to `dsflow_ci`: never moves `WORKING_TAG`.
|
||||
|
||||
The runner is re-executed through `dsflow_tui.py` (`common.ENTRY`), so the
|
||||
launcher must stay at the repository root next to `dsflow/`.
|
||||
|
||||
Job file (`.dsflow/tui_job.json`): written by the runner, read by the TUI
|
||||
and `status`. A terminal `status` (`passed`, `failed`, `cancelled`,
|
||||
`error`) means lock release has finished. `heartbeat` is refreshed every
|
||||
@@ -51,6 +59,9 @@ and `status`. A terminal `status` (`passed`, `failed`, `cancelled`,
|
||||
- [x] cancel, lost-runner cleanup, later check-in with `c`, batch tag, add new, rebase
|
||||
- [x] `status` / `status --json`, `--sanity-cmd`, `SANITY_SCRIPT`
|
||||
- [x] `--demo` sandbox with a fake `dssc`; `tests/test_runner.py`
|
||||
- [x] Textual UI with mouse support, detail pane, filter, themes, command palette
|
||||
- [x] self-contained checkout: `vendor/` + `tools/vendor.py`; runs isolated (`python -I -S`)
|
||||
- [x] headless UI tests (`tests/test_ui.py`), green on Python 3.12 and 3.8
|
||||
- [ ] real-DesignSync verification: TODO §1
|
||||
|
||||
## Work log
|
||||
@@ -67,6 +78,24 @@ and `status`. A terminal `status` (`passed`, `failed`, `cancelled`,
|
||||
runner saved the terminal status before releasing locks (CLAUDE.md
|
||||
invariant 7).
|
||||
|
||||
- 2026-09-24: rebuilt the UI on Textual at the lead's request ("interactive
|
||||
and pretty", servers without outside repo access, Python 3.8-3.9).
|
||||
Textual 6.2.1 is the newest line that supports 3.8.1; it and 9 pure-Python
|
||||
dependencies are unpacked into `vendor/` (11 MB) and put first on
|
||||
`sys.path` by the launcher, so a checkout runs isolated with no pip. The
|
||||
single file became the `dsflow/` package: backend modules are pure moves
|
||||
of the old sections; action rules moved out of the UI into `ops.py` so
|
||||
they stay testable. The curses UI is gone. Bugs found on the way, all
|
||||
fixed: an `auto_refresh` attribute clobbered Textual's repaint interval
|
||||
(division by zero); start-up focus landed on the hidden filter so every
|
||||
key went into it; TabbedContent followed the restored focus back to
|
||||
Changes after the run dialog closed; a `rows` attribute shadowed
|
||||
DataTable's; rich's pulse bar divides by zero without a colour system;
|
||||
late events hit the DOM during teardown. Verified: 11 tests green on
|
||||
Python 3.12 and 3.8.20, the shipped file set runs under `python -I -S`
|
||||
through a symlink on both, and the real TUI starts and quits cleanly in
|
||||
a pty on both.
|
||||
|
||||
## QA log
|
||||
|
||||
## Review
|
||||
Generated
+211
@@ -0,0 +1,211 @@
|
||||
<svg class="rich-terminal" viewBox="0 0 1482 879.5999999999999" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Generated with Rich https://www.textualize.io -->
|
||||
<style>
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Regular"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Bold"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");
|
||||
font-style: bold;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.terminal-2797968821-matrix {
|
||||
font-family: Fira Code, monospace;
|
||||
font-size: 20px;
|
||||
line-height: 24.4px;
|
||||
font-variant-east-asian: full-width;
|
||||
}
|
||||
|
||||
.terminal-2797968821-title {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
font-family: arial;
|
||||
}
|
||||
|
||||
.terminal-2797968821-r1 { fill: #c5c8c6 }
|
||||
.terminal-2797968821-r2 { fill: #a9b1d6 }
|
||||
.terminal-2797968821-r3 { fill: #858db0 }
|
||||
.terminal-2797968821-r4 { fill: #9aa1c6 }
|
||||
.terminal-2797968821-r5 { fill: #61667e }
|
||||
.terminal-2797968821-r6 { fill: #282a37 }
|
||||
.terminal-2797968821-r7 { fill: #bb9af7 }
|
||||
.terminal-2797968821-r8 { fill: #a9abb3;font-weight: bold }
|
||||
.terminal-2797968821-r9 { fill: #a9abb3 }
|
||||
.terminal-2797968821-r10 { fill: #5a4d79 }
|
||||
.terminal-2797968821-r11 { fill: #7aa2f7;font-weight: bold }
|
||||
.terminal-2797968821-r12 { fill: #e0af68;font-weight: bold }
|
||||
.terminal-2797968821-r13 { fill: #737aa2 }
|
||||
.terminal-2797968821-r14 { fill: #a9b1d6;font-weight: bold }
|
||||
.terminal-2797968821-r15 { fill: #181420;font-weight: bold }
|
||||
.terminal-2797968821-r16 { fill: #f7768e;font-weight: bold }
|
||||
.terminal-2797968821-r17 { fill: #1a1b26;font-weight: bold }
|
||||
.terminal-2797968821-r18 { fill: #e0af68 }
|
||||
.terminal-2797968821-r19 { fill: #9ece6a;font-weight: bold }
|
||||
.terminal-2797968821-r20 { fill: #9ece6a }
|
||||
.terminal-2797968821-r21 { fill: #7aa2f7 }
|
||||
.terminal-2797968821-r22 { fill: #ff9e64;font-weight: bold }
|
||||
.terminal-2797968821-r23 { fill: #555d7e }
|
||||
</style>
|
||||
|
||||
<defs>
|
||||
<clipPath id="terminal-2797968821-clip-terminal">
|
||||
<rect x="0" y="0" width="1463.0" height="828.5999999999999" />
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-0">
|
||||
<rect x="0" y="1.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-1">
|
||||
<rect x="0" y="25.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-2">
|
||||
<rect x="0" y="50.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-3">
|
||||
<rect x="0" y="74.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-4">
|
||||
<rect x="0" y="99.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-5">
|
||||
<rect x="0" y="123.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-6">
|
||||
<rect x="0" y="147.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-7">
|
||||
<rect x="0" y="172.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-8">
|
||||
<rect x="0" y="196.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-9">
|
||||
<rect x="0" y="221.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-10">
|
||||
<rect x="0" y="245.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-11">
|
||||
<rect x="0" y="269.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-12">
|
||||
<rect x="0" y="294.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-13">
|
||||
<rect x="0" y="318.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-14">
|
||||
<rect x="0" y="343.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-15">
|
||||
<rect x="0" y="367.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-16">
|
||||
<rect x="0" y="391.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-17">
|
||||
<rect x="0" y="416.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-18">
|
||||
<rect x="0" y="440.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-19">
|
||||
<rect x="0" y="465.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-20">
|
||||
<rect x="0" y="489.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-21">
|
||||
<rect x="0" y="513.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-22">
|
||||
<rect x="0" y="538.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-23">
|
||||
<rect x="0" y="562.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-24">
|
||||
<rect x="0" y="587.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-25">
|
||||
<rect x="0" y="611.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-26">
|
||||
<rect x="0" y="635.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-27">
|
||||
<rect x="0" y="660.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-28">
|
||||
<rect x="0" y="684.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-29">
|
||||
<rect x="0" y="709.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-30">
|
||||
<rect x="0" y="733.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-31">
|
||||
<rect x="0" y="757.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-2797968821-line-32">
|
||||
<rect x="0" y="782.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="1" y="1" width="1480" height="877.6" rx="8"/><text class="terminal-2797968821-title" fill="#c5c8c6" text-anchor="middle" x="740" y="27">dsflow  ·  updated 03:20:16 (1.5s)</text>
|
||||
<g transform="translate(26,22)">
|
||||
<circle cx="0" cy="0" r="7" fill="#ff5f57"/>
|
||||
<circle cx="22" cy="0" r="7" fill="#febc2e"/>
|
||||
<circle cx="44" cy="0" r="7" fill="#28c840"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(9, 41)" clip-path="url(#terminal-2797968821-clip-terminal)">
|
||||
<rect fill="#414868" x="0" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="12.2" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="24.4" y="1.5" width="61" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="85.4" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="97.6" y="1.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="207.4" y="1.5" width="414.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="622.2" y="1.5" width="36.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="658.8" y="1.5" width="573.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="1232.2" y="1.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1342" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1354.2" y="1.5" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1451.8" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="12.2" y="25.9" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="122" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="134.2" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="146.4" y="25.9" width="85.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="231.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="244" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="256.2" y="25.9" width="158.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="414.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="427" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="439.2" y="25.9" width="122" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="561.2" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="573.4" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="585.6" y="25.9" width="48.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="634.4" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="646.6" y="25.9" width="817.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="12.2" y="50.3" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="122" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="134.2" y="50.3" width="1329.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#2a2e42" x="0" y="74.7" width="36.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#2a2e42" x="36.6" y="74.7" width="48.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#2a2e42" x="85.4" y="74.7" width="305" height="24.65" shape-rendering="crispEdges"/><rect fill="#2a2e42" x="390.4" y="74.7" width="195.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#2a2e42" x="585.6" y="74.7" width="146.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#2a2e42" x="732" y="74.7" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#2a2e42" x="841.8" y="74.7" width="134.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#22232e" x="976" y="74.7" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#22232e" x="988.2" y="74.7" width="475.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="0" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="12.2" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="24.4" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="36.6" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="48.8" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="61" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="85.4" y="99.1" width="305" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="390.4" y="99.1" width="48.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="439.2" y="99.1" width="85.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="524.6" y="99.1" width="61" height="24.65" shape-rendering="crispEdges"/><rect fill="#212538" x="585.6" y="99.1" width="Line truncated
|
||||
<g class="terminal-2797968821-matrix">
|
||||
<text class="terminal-2797968821-r2" x="12.2" y="20" textLength="12.2" clip-path="url(#terminal-2797968821-line-0)">◆</text><text class="terminal-2797968821-r2" x="207.4" y="20" textLength="414.8" clip-path="url(#terminal-2797968821-line-0)">dsflow  ·  updated 03:20:16 (1.5s)</text><text class="terminal-2797968821-r3" x="622.2" y="20" textLength="36.6" clip-path="url(#terminal-2797968821-line-0)"> — </text><text class="terminal-2797968821-r3" x="658.8" y="20" textLength="573.4" clip-path="url(#terminal-2797968821-line-0)">demo sandbox · Trunk:Latest · green tag working</text><text class="terminal-2797968821-r4" x="1354.2" y="20" textLength="97.6" clip-path="url(#terminal-2797968821-line-0)">03:20:18</text><text class="terminal-2797968821-r1" x="1464" y="20" textLength="12.2" clip-path="url(#terminal-2797968821-line-0)">
|
||||
</text><text class="terminal-2797968821-r2" x="12.2" y="44.4" textLength="109.8" clip-path="url(#terminal-2797968821-line-1)">Changes 5</text><text class="terminal-2797968821-r5" x="146.4" y="44.4" textLength="85.4" clip-path="url(#terminal-2797968821-line-1)">Locks 1</text><text class="terminal-2797968821-r5" x="256.2" y="44.4" textLength="158.6" clip-path="url(#terminal-2797968821-line-1)">Checked-out 4</text><text class="terminal-2797968821-r5" x="439.2" y="44.4" textLength="122" clip-path="url(#terminal-2797968821-line-1)">Sanity run</text><text class="terminal-2797968821-r5" x="585.6" y="44.4" textLength="48.8" clip-path="url(#terminal-2797968821-line-1)">Logs</text><text class="terminal-2797968821-r1" x="1464" y="44.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-1)">
|
||||
</text><text class="terminal-2797968821-r6" x="0" y="68.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-2)">╸</text><text class="terminal-2797968821-r7" x="12.2" y="68.8" textLength="109.8" clip-path="url(#terminal-2797968821-line-2)">━━━━━━━━━</text><text class="terminal-2797968821-r6" x="122" y="68.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-2)">╺</text><text class="terminal-2797968821-r6" x="134.2" y="68.8" textLength="1329.8" clip-path="url(#terminal-2797968821-line-2)">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</text><text class="terminal-2797968821-r1" x="1464" y="68.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-2)">
|
||||
</text><text class="terminal-2797968821-r8" x="36.6" y="93.2" textLength="48.8" clip-path="url(#terminal-2797968821-line-3)"> St </text><text class="terminal-2797968821-r8" x="85.4" y="93.2" textLength="305" clip-path="url(#terminal-2797968821-line-3)"> File                    </text><text class="terminal-2797968821-r8" x="390.4" y="93.2" textLength="195.2" clip-path="url(#terminal-2797968821-line-3)"> Base → Latest  </text><text class="terminal-2797968821-r8" x="585.6" y="93.2" textLength="146.4" clip-path="url(#terminal-2797968821-line-3)"> Lock       </text><text class="terminal-2797968821-r8" x="732" y="93.2" textLength="109.8" clip-path="url(#terminal-2797968821-line-3)"> Flags   </text><text class="terminal-2797968821-r10" x="976" y="93.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-3)">▎</text><text class="terminal-2797968821-r1" x="1464" y="93.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-3)">
|
||||
</text><text class="terminal-2797968821-r11" x="12.2" y="117.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-4)">●</text><text class="terminal-2797968821-r12" x="48.8" y="117.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-4)">M</text><text class="terminal-2797968821-r2" x="85.4" y="117.6" textLength="305" clip-path="url(#terminal-2797968821-line-4)"> rtl/rx/rx_fsm.sv        </text><text class="terminal-2797968821-r2" x="390.4" y="117.6" textLength="48.8" clip-path="url(#terminal-2797968821-line-4)"> 1.4</text><text class="terminal-2797968821-r13" x="439.2" y="117.6" textLength="85.4" clip-path="url(#terminal-2797968821-line-4)"> latest</text><text class="terminal-2797968821-r13" x="597.8" y="117.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-4)">—</text><text class="terminal-2797968821-r10" x="976" y="117.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-4)">▎</text><text class="terminal-2797968821-r14" x="1012.6" y="117.6" textLength="280.6" clip-path="url(#terminal-2797968821-line-4)">rtl/top/wifi_mac_top.sv</text><text class="terminal-2797968821-r1" x="1464" y="117.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-4)">
|
||||
</text><text class="terminal-2797968821-r15" x="0" y="142" textLength="36.6" clip-path="url(#terminal-2797968821-line-5)"> ● </text><text class="terminal-2797968821-r15" x="36.6" y="142" textLength="48.8" clip-path="url(#terminal-2797968821-line-5)"> M  </text><text class="terminal-2797968821-r15" x="85.4" y="142" textLength="305" clip-path="url(#terminal-2797968821-line-5)"> rtl/top/wifi_mac_top.sv </text><text class="terminal-2797968821-r15" x="390.4" y="142" textLength="195.2" clip-path="url(#terminal-2797968821-line-5)"> 1.12 latest    </text><text class="terminal-2797968821-r15" x="585.6" y="142" textLength="146.4" clip-path="url(#terminal-2797968821-line-5)"> you        </text><text class="terminal-2797968821-r15" x="732" y="142" textLength="109.8" clip-path="url(#terminal-2797968821-line-5)">  HOT    </text><text class="terminal-2797968821-r10" x="976" y="142" textLength="12.2" clip-path="url(#terminal-2797968821-line-5)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="142" textLength="366" clip-path="url(#terminal-2797968821-line-5)">──────────────────────────────</text><text class="terminal-2797968821-r1" x="1464" y="142" textLength="12.2" clip-path="url(#terminal-2797968821-line-5)">
|
||||
</text><text class="terminal-2797968821-r13" x="12.2" y="166.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-6)">○</text><text class="terminal-2797968821-r12" x="48.8" y="166.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-6)">M</text><text class="terminal-2797968821-r2" x="85.4" y="166.4" textLength="305" clip-path="url(#terminal-2797968821-line-6)"> rtl/tx/tx_ctrl.sv       </text><text class="terminal-2797968821-r16" x="402.6" y="166.4" textLength="109.8" clip-path="url(#terminal-2797968821-line-6)">1.7 → 1.8</text><text class="terminal-2797968821-r13" x="597.8" y="166.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-6)">—</text><text class="terminal-2797968821-r17" x="744.2" y="166.4" textLength="85.4" clip-path="url(#terminal-2797968821-line-6)"> STALE </text><text class="terminal-2797968821-r10" x="976" y="166.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-6)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="166.4" textLength="97.6" clip-path="url(#terminal-2797968821-line-6)">change  </text><text class="terminal-2797968821-r18" x="1122.4" y="166.4" textLength="244" clip-path="url(#terminal-2797968821-line-6)">modified            </text><text class="terminal-2797968821-r1" x="1464" y="166.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-6)">
|
||||
</text><text class="terminal-2797968821-r13" x="12.2" y="190.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-7)">○</text><text class="terminal-2797968821-r12" x="48.8" y="190.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-7)">M</text><text class="terminal-2797968821-r2" x="85.4" y="190.8" textLength="305" clip-path="url(#terminal-2797968821-line-7)"> rtl/tx/tx_fifo.sv       </text><text class="terminal-2797968821-r2" x="390.4" y="190.8" textLength="48.8" clip-path="url(#terminal-2797968821-line-7)"> 1.2</text><text class="terminal-2797968821-r13" x="439.2" y="190.8" textLength="85.4" clip-path="url(#terminal-2797968821-line-7)"> latest</text><text class="terminal-2797968821-r13" x="597.8" y="190.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-7)">—</text><text class="terminal-2797968821-r10" x="976" y="190.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-7)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="190.8" textLength="97.6" clip-path="url(#terminal-2797968821-line-7)">base    </text><text class="terminal-2797968821-r2" x="1122.4" y="190.8" textLength="244" clip-path="url(#terminal-2797968821-line-7)">1.12                </text><text class="terminal-2797968821-r1" x="1464" y="190.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-7)">
|
||||
</text><text class="terminal-2797968821-r13" x="12.2" y="215.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-8)">○</text><text class="terminal-2797968821-r19" x="48.8" y="215.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-8)">A</text><text class="terminal-2797968821-r2" x="85.4" y="215.2" textLength="305" clip-path="url(#terminal-2797968821-line-8)"> rtl/rx/rx_agg.sv        </text><text class="terminal-2797968821-r13" x="402.6" y="215.2" textLength="97.6" clip-path="url(#terminal-2797968821-line-8)">new file</text><text class="terminal-2797968821-r13" x="597.8" y="215.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-8)">—</text><text class="terminal-2797968821-r10" x="976" y="215.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-8)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="215.2" textLength="97.6" clip-path="url(#terminal-2797968821-line-8)">latest  </text><text class="terminal-2797968821-r2" x="1122.4" y="215.2" textLength="73.2" clip-path="url(#terminal-2797968821-line-8)">1.12  </text><text class="terminal-2797968821-r20" x="1195.6" y="215.2" textLength="85.4" clip-path="url(#terminal-2797968821-line-8)">✔ fresh</text><text class="terminal-2797968821-r1" x="1464" y="215.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-8)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="239.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-9)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="239.6" textLength="97.6" clip-path="url(#terminal-2797968821-line-9)">lock    </text><text class="terminal-2797968821-r19" x="1122.4" y="239.6" textLength="244" clip-path="url(#terminal-2797968821-line-9)">you                 </text><text class="terminal-2797968821-r1" x="1464" y="239.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-9)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="264" textLength="12.2" clip-path="url(#terminal-2797968821-line-10)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="264" textLength="97.6" clip-path="url(#terminal-2797968821-line-10)">hot file</text><text class="terminal-2797968821-r7" x="1122.4" y="264" textLength="244" clip-path="url(#terminal-2797968821-line-10)">yes - locked on edit</text><text class="terminal-2797968821-r1" x="1464" y="264" textLength="12.2" clip-path="url(#terminal-2797968821-line-10)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="288.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-11)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="288.4" textLength="97.6" clip-path="url(#terminal-2797968821-line-11)">on disk </text><text class="terminal-2797968821-r2" x="1122.4" y="288.4" textLength="244" clip-path="url(#terminal-2797968821-line-11)">99 B  03:20:16      </text><text class="terminal-2797968821-r1" x="1464" y="288.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-11)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="312.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-12)">▎</text><text class="terminal-2797968821-r13" x="1012.6" y="312.8" textLength="97.6" clip-path="url(#terminal-2797968821-line-12)">writable</text><text class="terminal-2797968821-r20" x="1122.4" y="312.8" textLength="244" clip-path="url(#terminal-2797968821-line-12)">yes                 </text><text class="terminal-2797968821-r1" x="1464" y="312.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-12)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="337.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-13)">▎</text><text class="terminal-2797968821-r1" x="1464" y="337.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-13)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="361.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-14)">▎</text><text class="terminal-2797968821-r11" x="1012.6" y="361.6" textLength="61" clip-path="url(#terminal-2797968821-line-14)">space</text><text class="terminal-2797968821-r13" x="1085.8" y="361.6" textLength="170.8" clip-path="url(#terminal-2797968821-line-14)">mark          </text><text class="terminal-2797968821-r1" x="1464" y="361.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-14)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="386" textLength="12.2" clip-path="url(#terminal-2797968821-line-15)">▎</text><text class="terminal-2797968821-r11" x="1012.6" y="386" textLength="61" clip-path="url(#terminal-2797968821-line-15)">s    </text><text class="terminal-2797968821-r13" x="1085.8" y="386" textLength="170.8" clip-path="url(#terminal-2797968821-line-15)">run sanity    </text><text class="terminal-2797968821-r1" x="1464" y="386" textLength="12.2" clip-path="url(#terminal-2797968821-line-15)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="410.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-16)">▎</text><text class="terminal-2797968821-r11" x="1012.6" y="410.4" textLength="61" clip-path="url(#terminal-2797968821-line-16)">c    </text><text class="terminal-2797968821-r13" x="1085.8" y="410.4" textLength="170.8" clip-path="url(#terminal-2797968821-line-16)">check in      </text><text class="terminal-2797968821-r1" x="1464" y="410.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-16)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="434.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-17)">▎</text><text class="terminal-2797968821-r11" x="1012.6" y="434.8" textLength="61" clip-path="url(#terminal-2797968821-line-17)">t    </text><text class="terminal-2797968821-r13" x="1085.8" y="434.8" textLength="170.8" clip-path="url(#terminal-2797968821-line-17)">tag           </text><text class="terminal-2797968821-r1" x="1464" y="434.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-17)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="459.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-18)">▎</text><text class="terminal-2797968821-r11" x="1012.6" y="459.2" textLength="61" clip-path="url(#terminal-2797968821-line-18)">m    </text><text class="terminal-2797968821-r13" x="1085.8" y="459.2" textLength="170.8" clip-path="url(#terminal-2797968821-line-18)">rebase stale  </text><text class="terminal-2797968821-r1" x="1464" y="459.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-18)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="483.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-19)">▎</text><text class="terminal-2797968821-r11" x="1012.6" y="483.6" textLength="61" clip-path="url(#terminal-2797968821-line-19)">n    </text><text class="terminal-2797968821-r13" x="1085.8" y="483.6" textLength="170.8" clip-path="url(#terminal-2797968821-line-19)">add a new file</text><text class="terminal-2797968821-r1" x="1464" y="483.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-19)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="508" textLength="12.2" clip-path="url(#terminal-2797968821-line-20)">▎</text><text class="terminal-2797968821-r1" x="1464" y="508" textLength="12.2" clip-path="url(#terminal-2797968821-line-20)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="532.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-21)">▎</text><text class="terminal-2797968821-r1" x="1464" y="532.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-21)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="556.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-22)">▎</text><text class="terminal-2797968821-r1" x="1464" y="556.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-22)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="581.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-23)">▎</text><text class="terminal-2797968821-r1" x="1464" y="581.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-23)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="605.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-24)">▎</text><text class="terminal-2797968821-r1" x="1464" y="605.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-24)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="630" textLength="12.2" clip-path="url(#terminal-2797968821-line-25)">▎</text><text class="terminal-2797968821-r1" x="1464" y="630" textLength="12.2" clip-path="url(#terminal-2797968821-line-25)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="654.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-26)">▎</text><text class="terminal-2797968821-r1" x="1464" y="654.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-26)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="678.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-27)">▎</text><text class="terminal-2797968821-r1" x="1464" y="678.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-27)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="703.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-28)">▎</text><text class="terminal-2797968821-r1" x="1464" y="703.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-28)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="727.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-29)">▎</text><text class="terminal-2797968821-r1" x="1464" y="727.6" textLength="12.2" clip-path="url(#terminal-2797968821-line-29)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="752" textLength="12.2" clip-path="url(#terminal-2797968821-line-30)">▎</text><text class="terminal-2797968821-r1" x="1464" y="752" textLength="12.2" clip-path="url(#terminal-2797968821-line-30)">
|
||||
</text><text class="terminal-2797968821-r10" x="976" y="776.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-31)">▎</text><text class="terminal-2797968821-r1" x="1464" y="776.4" textLength="12.2" clip-path="url(#terminal-2797968821-line-31)">
|
||||
</text><text class="terminal-2797968821-r13" x="12.2" y="800.8" textLength="1342" clip-path="url(#terminal-2797968821-line-32)">○ no sanity run yet                                                                                           </text><text class="terminal-2797968821-r21" x="1354.2" y="800.8" textLength="97.6" clip-path="url(#terminal-2797968821-line-32)">2 marked</text><text class="terminal-2797968821-r1" x="1464" y="800.8" textLength="12.2" clip-path="url(#terminal-2797968821-line-32)">
|
||||
</text><text class="terminal-2797968821-r22" x="0" y="825.2" textLength="85.4" clip-path="url(#terminal-2797968821-line-33)"> space </text><text class="terminal-2797968821-r2" x="85.4" y="825.2" textLength="61" clip-path="url(#terminal-2797968821-line-33)">Mark </text><text class="terminal-2797968821-r22" x="146.4" y="825.2" textLength="36.6" clip-path="url(#terminal-2797968821-line-33)"> s </text><text class="terminal-2797968821-r2" x="183" y="825.2" textLength="85.4" clip-path="url(#terminal-2797968821-line-33)">Sanity </text><text class="terminal-2797968821-r22" x="268.4" y="825.2" textLength="36.6" clip-path="url(#terminal-2797968821-line-33)"> c </text><text class="terminal-2797968821-r2" x="305" y="825.2" textLength="109.8" clip-path="url(#terminal-2797968821-line-33)">Check in </text><text class="terminal-2797968821-r22" x="414.8" y="825.2" textLength="36.6" clip-path="url(#terminal-2797968821-line-33)"> t </text><text class="terminal-2797968821-r2" x="451.4" y="825.2" textLength="48.8" clip-path="url(#terminal-2797968821-line-33)">Tag </text><text class="terminal-2797968821-r22" x="500.2" y="825.2" textLength="36.6" clip-path="url(#terminal-2797968821-line-33)"> / </text><text class="terminal-2797968821-r2" x="536.8" y="825.2" textLength="85.4" clip-path="url(#terminal-2797968821-line-33)">Filter </text><text class="terminal-2797968821-r22" x="622.2" y="825.2" textLength="36.6" clip-path="url(#terminal-2797968821-line-33)"> r </text><text class="terminal-2797968821-r2" x="658.8" y="825.2" textLength="97.6" clip-path="url(#terminal-2797968821-line-33)">Refresh </text><text class="terminal-2797968821-r22" x="756.4" y="825.2" textLength="36.6" clip-path="url(#terminal-2797968821-line-33)"> ? </text><text class="terminal-2797968821-r2" x="793" y="825.2" textLength="61" clip-path="url(#terminal-2797968821-line-33)">Help </text><text class="terminal-2797968821-r22" x="854" y="825.2" textLength="36.6" clip-path="url(#terminal-2797968821-line-33)"> q </text><text class="terminal-2797968821-r2" x="890.6" y="825.2" textLength="61" clip-path="url(#terminal-2797968821-line-33)">Quit </text><text class="terminal-2797968821-r23" x="1317.6" y="825.2" textLength="12.2" clip-path="url(#terminal-2797968821-line-33)">▏</text><text class="terminal-2797968821-r22" x="1329.8" y="825.2" textLength="24.4" clip-path="url(#terminal-2797968821-line-33)">^p</text><text class="terminal-2797968821-r2" x="1354.2" y="825.2" textLength="97.6" clip-path="url(#terminal-2797968821-line-33)"> palette</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 60 KiB |
Generated
+218
@@ -0,0 +1,218 @@
|
||||
<svg class="rich-terminal" viewBox="0 0 1482 879.5999999999999" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Generated with Rich https://www.textualize.io -->
|
||||
<style>
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Regular"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Bold"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");
|
||||
font-style: bold;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.terminal-451286626-matrix {
|
||||
font-family: Fira Code, monospace;
|
||||
font-size: 20px;
|
||||
line-height: 24.4px;
|
||||
font-variant-east-asian: full-width;
|
||||
}
|
||||
|
||||
.terminal-451286626-title {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
font-family: arial;
|
||||
}
|
||||
|
||||
.terminal-451286626-r1 { fill: #a9b1d6 }
|
||||
.terminal-451286626-r2 { fill: #53576c }
|
||||
.terminal-451286626-r3 { fill: #44485d }
|
||||
.terminal-451286626-r4 { fill: #4d5066 }
|
||||
.terminal-451286626-r5 { fill: #c5c8c6 }
|
||||
.terminal-451286626-r6 { fill: #363949 }
|
||||
.terminal-451286626-r7 { fill: #8a73b8 }
|
||||
.terminal-451286626-r8 { fill: #1f212c }
|
||||
.terminal-451286626-r9 { fill: #5a4d79 }
|
||||
.terminal-451286626-r10 { fill: #53545e;font-weight: bold }
|
||||
.terminal-451286626-r11 { fill: #fe9e64;font-weight: bold }
|
||||
.terminal-451286626-r12 { fill: #405179;font-weight: bold }
|
||||
.terminal-451286626-r13 { fill: #695640;font-weight: bold }
|
||||
.terminal-451286626-r14 { fill: #53576c;font-weight: bold }
|
||||
.terminal-451286626-r15 { fill: #191823;font-weight: bold }
|
||||
.terminal-451286626-r16 { fill: #a9b1d6;font-weight: bold }
|
||||
.terminal-451286626-r17 { fill: #3d4157 }
|
||||
.terminal-451286626-r18 { fill: #695640 }
|
||||
.terminal-451286626-r19 { fill: #4e6241;font-weight: bold }
|
||||
.terminal-451286626-r20 { fill: #dfaf68 }
|
||||
.terminal-451286626-r21 { fill: #a7a9b0;font-weight: bold }
|
||||
.terminal-451286626-r22 { fill: #4e6241 }
|
||||
.terminal-451286626-r23 { fill: #414868 }
|
||||
.terminal-451286626-r24 { fill: #bede9c }
|
||||
.terminal-451286626-r25 { fill: #1e2744 }
|
||||
.terminal-451286626-r26 { fill: #24283b }
|
||||
.terminal-451286626-r27 { fill: #bb9af7 }
|
||||
.terminal-451286626-r28 { fill: #1a1b26 }
|
||||
.terminal-451286626-r29 { fill: #f6768e;font-weight: bold }
|
||||
.terminal-451286626-r30 { fill: #405179 }
|
||||
</style>
|
||||
|
||||
<defs>
|
||||
<clipPath id="terminal-451286626-clip-terminal">
|
||||
<rect x="0" y="0" width="1463.0" height="828.5999999999999" />
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-0">
|
||||
<rect x="0" y="1.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-1">
|
||||
<rect x="0" y="25.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-2">
|
||||
<rect x="0" y="50.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-3">
|
||||
<rect x="0" y="74.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-4">
|
||||
<rect x="0" y="99.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-5">
|
||||
<rect x="0" y="123.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-6">
|
||||
<rect x="0" y="147.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-7">
|
||||
<rect x="0" y="172.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-8">
|
||||
<rect x="0" y="196.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-9">
|
||||
<rect x="0" y="221.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-10">
|
||||
<rect x="0" y="245.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-11">
|
||||
<rect x="0" y="269.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-12">
|
||||
<rect x="0" y="294.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-13">
|
||||
<rect x="0" y="318.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-14">
|
||||
<rect x="0" y="343.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-15">
|
||||
<rect x="0" y="367.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-16">
|
||||
<rect x="0" y="391.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-17">
|
||||
<rect x="0" y="416.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-18">
|
||||
<rect x="0" y="440.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-19">
|
||||
<rect x="0" y="465.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-20">
|
||||
<rect x="0" y="489.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-21">
|
||||
<rect x="0" y="513.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-22">
|
||||
<rect x="0" y="538.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-23">
|
||||
<rect x="0" y="562.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-24">
|
||||
<rect x="0" y="587.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-25">
|
||||
<rect x="0" y="611.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-26">
|
||||
<rect x="0" y="635.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-27">
|
||||
<rect x="0" y="660.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-28">
|
||||
<rect x="0" y="684.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-29">
|
||||
<rect x="0" y="709.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-30">
|
||||
<rect x="0" y="733.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-31">
|
||||
<rect x="0" y="757.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-451286626-line-32">
|
||||
<rect x="0" y="782.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="1" y="1" width="1480" height="877.6" rx="8"/><text class="terminal-451286626-title" fill="#c5c8c6" text-anchor="middle" x="740" y="27">dsflow  ·  updated 03:20:16 (1.5s)</text>
|
||||
<g transform="translate(26,22)">
|
||||
<circle cx="0" cy="0" r="7" fill="#ff5f57"/>
|
||||
<circle cx="22" cy="0" r="7" fill="#febc2e"/>
|
||||
<circle cx="44" cy="0" r="7" fill="#28c840"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(9, 41)" clip-path="url(#terminal-451286626-clip-terminal)">
|
||||
<rect fill="#292d40" x="0" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="12.2" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="24.4" y="1.5" width="61" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="85.4" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="97.6" y="1.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="207.4" y="1.5" width="414.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="622.2" y="1.5" width="36.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="658.8" y="1.5" width="573.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#292d40" x="1232.2" y="1.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#2b2e42" x="1342" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#2b2e42" x="1354.2" y="1.5" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#2b2e42" x="1451.8" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="12.2" y="25.9" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="122" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="134.2" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="146.4" y="25.9" width="36.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="183" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="195.2" y="25.9" width="1073.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="1268.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1281" y="25.9" width="183" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="12.2" y="50.3" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="122" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="134.2" y="50.3" width="48.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="183" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="195.2" y="50.3" width="1073.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="1268.8" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1281" y="50.3" width="183" height="24.65" shape-rendering="crispEdges"/><rect fill="#202231" x="0" y="74.7" width="36.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#202231" x="36.6" y="74.7" width="48.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#202231" x="85.4" y="74.7" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="183" y="74.7" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="195.2" y="74.7" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="219.6" y="74.7" width="122" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="341.6" y="74.7" width="902.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="1244.4" y="74.7" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="1268.8" y="74.7" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1d1e29" x="1281" y="74.7" width="183" height="24.65" shape-rendering="crispEdges"/><rect fill="#1c1f2d" x="0" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1c1f2d" x="12.2" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1c1f2d" x="24.4" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1c1f2d" x="36.6" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1c1f2d" x="48.8" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1c1f2d" x="61" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1c1f2d" x="85.4" y="99.1" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="183" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="195.2" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="219.6" y="99.1" width="1024.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="1244.4" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#24283b" x="1268.8" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1d1e29" x="1281" y="99.1" width=Line truncated
|
||||
<g class="terminal-451286626-matrix">
|
||||
<text class="terminal-451286626-r2" x="12.2" y="20" textLength="12.2" clip-path="url(#terminal-451286626-line-0)">◆</text><text class="terminal-451286626-r2" x="207.4" y="20" textLength="414.8" clip-path="url(#terminal-451286626-line-0)">dsflow  ·  updated 03:20:16 (1.5s)</text><text class="terminal-451286626-r3" x="622.2" y="20" textLength="36.6" clip-path="url(#terminal-451286626-line-0)"> — </text><text class="terminal-451286626-r3" x="658.8" y="20" textLength="573.4" clip-path="url(#terminal-451286626-line-0)">demo sandbox · Trunk:Latest · green tag working</text><text class="terminal-451286626-r4" x="1354.2" y="20" textLength="97.6" clip-path="url(#terminal-451286626-line-0)">03:20:20</text><text class="terminal-451286626-r5" x="1464" y="20" textLength="12.2" clip-path="url(#terminal-451286626-line-0)">
|
||||
</text><text class="terminal-451286626-r2" x="12.2" y="44.4" textLength="109.8" clip-path="url(#terminal-451286626-line-1)">Changes 5</text><text class="terminal-451286626-r6" x="146.4" y="44.4" textLength="36.6" clip-path="url(#terminal-451286626-line-1)">Loc</text><text class="terminal-451286626-r7" x="183" y="44.4" textLength="12.2" clip-path="url(#terminal-451286626-line-1)">█</text><text class="terminal-451286626-r7" x="195.2" y="44.4" textLength="1073.6" clip-path="url(#terminal-451286626-line-1)">▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀</text><text class="terminal-451286626-r7" x="1268.8" y="44.4" textLength="12.2" clip-path="url(#terminal-451286626-line-1)">█</text><text class="terminal-451286626-r5" x="1464" y="44.4" textLength="12.2" clip-path="url(#terminal-451286626-line-1)">
|
||||
</text><text class="terminal-451286626-r8" x="0" y="68.8" textLength="12.2" clip-path="url(#terminal-451286626-line-2)">╸</text><text class="terminal-451286626-r9" x="12.2" y="68.8" textLength="109.8" clip-path="url(#terminal-451286626-line-2)">━━━━━━━━━</text><text class="terminal-451286626-r8" x="122" y="68.8" textLength="12.2" clip-path="url(#terminal-451286626-line-2)">╺</text><text class="terminal-451286626-r8" x="134.2" y="68.8" textLength="48.8" clip-path="url(#terminal-451286626-line-2)">━━━━</text><text class="terminal-451286626-r7" x="183" y="68.8" textLength="12.2" clip-path="url(#terminal-451286626-line-2)">█</text><text class="terminal-451286626-r7" x="1268.8" y="68.8" textLength="12.2" clip-path="url(#terminal-451286626-line-2)">█</text><text class="terminal-451286626-r8" x="1281" y="68.8" textLength="183" clip-path="url(#terminal-451286626-line-2)">━━━━━━━━━━━━━━━</text><text class="terminal-451286626-r5" x="1464" y="68.8" textLength="12.2" clip-path="url(#terminal-451286626-line-2)">
|
||||
</text><text class="terminal-451286626-r10" x="36.6" y="93.2" textLength="48.8" clip-path="url(#terminal-451286626-line-3)"> St </text><text class="terminal-451286626-r10" x="85.4" y="93.2" textLength="97.6" clip-path="url(#terminal-451286626-line-3)"> File   </text><text class="terminal-451286626-r7" x="183" y="93.2" textLength="12.2" clip-path="url(#terminal-451286626-line-3)">█</text><text class="terminal-451286626-r11" x="219.6" y="93.2" textLength="122" clip-path="url(#terminal-451286626-line-3)">Run sanity</text><text class="terminal-451286626-r7" x="1268.8" y="93.2" textLength="12.2" clip-path="url(#terminal-451286626-line-3)">█</text><text class="terminal-451286626-r5" x="1464" y="93.2" textLength="12.2" clip-path="url(#terminal-451286626-line-3)">
|
||||
</text><text class="terminal-451286626-r12" x="12.2" y="117.6" textLength="12.2" clip-path="url(#terminal-451286626-line-4)">●</text><text class="terminal-451286626-r13" x="48.8" y="117.6" textLength="12.2" clip-path="url(#terminal-451286626-line-4)">M</text><text class="terminal-451286626-r2" x="85.4" y="117.6" textLength="97.6" clip-path="url(#terminal-451286626-line-4)"> rtl/rx/</text><text class="terminal-451286626-r7" x="183" y="117.6" textLength="12.2" clip-path="url(#terminal-451286626-line-4)">█</text><text class="terminal-451286626-r7" x="1268.8" y="117.6" textLength="12.2" clip-path="url(#terminal-451286626-line-4)">█</text><text class="terminal-451286626-r14" x="1281" y="117.6" textLength="12.2" clip-path="url(#terminal-451286626-line-4)">v</text><text class="terminal-451286626-r5" x="1464" y="117.6" textLength="12.2" clip-path="url(#terminal-451286626-line-4)">
|
||||
</text><text class="terminal-451286626-r15" x="0" y="142" textLength="36.6" clip-path="url(#terminal-451286626-line-5)"> ● </text><text class="terminal-451286626-r15" x="36.6" y="142" textLength="48.8" clip-path="url(#terminal-451286626-line-5)"> M  </text><text class="terminal-451286626-r15" x="85.4" y="142" textLength="97.6" clip-path="url(#terminal-451286626-line-5)"> rtl/top</text><text class="terminal-451286626-r7" x="183" y="142" textLength="12.2" clip-path="url(#terminal-451286626-line-5)">█</text><text class="terminal-451286626-r16" x="219.6" y="142" textLength="793" clip-path="url(#terminal-451286626-line-5)">2 file(s) are locked while sanity runs and released when it ends.</text><text class="terminal-451286626-r7" x="1268.8" y="142" textLength="12.2" clip-path="url(#terminal-451286626-line-5)">█</text><text class="terminal-451286626-r17" x="1281" y="142" textLength="97.6" clip-path="url(#terminal-451286626-line-5)">────────</text><text class="terminal-451286626-r5" x="1464" y="142" textLength="12.2" clip-path="url(#terminal-451286626-line-5)">
|
||||
</text><text class="terminal-451286626-r17" x="12.2" y="166.4" textLength="12.2" clip-path="url(#terminal-451286626-line-6)">○</text><text class="terminal-451286626-r13" x="48.8" y="166.4" textLength="12.2" clip-path="url(#terminal-451286626-line-6)">M</text><text class="terminal-451286626-r2" x="85.4" y="166.4" textLength="97.6" clip-path="url(#terminal-451286626-line-6)"> rtl/tx/</text><text class="terminal-451286626-r7" x="183" y="166.4" textLength="12.2" clip-path="url(#terminal-451286626-line-6)">█</text><text class="terminal-451286626-r1" x="219.6" y="166.4" textLength="244" clip-path="url(#terminal-451286626-line-6)">  • rtl/rx/rx_fsm.sv</text><text class="terminal-451286626-r7" x="1268.8" y="166.4" textLength="12.2" clip-path="url(#terminal-451286626-line-6)">█</text><text class="terminal-451286626-r5" x="1464" y="166.4" textLength="12.2" clip-path="url(#terminal-451286626-line-6)">
|
||||
</text><text class="terminal-451286626-r17" x="12.2" y="190.8" textLength="12.2" clip-path="url(#terminal-451286626-line-7)">○</text><text class="terminal-451286626-r13" x="48.8" y="190.8" textLength="12.2" clip-path="url(#terminal-451286626-line-7)">M</text><text class="terminal-451286626-r2" x="85.4" y="190.8" textLength="97.6" clip-path="url(#terminal-451286626-line-7)"> rtl/tx/</text><text class="terminal-451286626-r7" x="183" y="190.8" textLength="12.2" clip-path="url(#terminal-451286626-line-7)">█</text><text class="terminal-451286626-r1" x="219.6" y="190.8" textLength="329.4" clip-path="url(#terminal-451286626-line-7)">  • rtl/top/wifi_mac_top.sv</text><text class="terminal-451286626-r7" x="1268.8" y="190.8" textLength="12.2" clip-path="url(#terminal-451286626-line-7)">█</text><text class="terminal-451286626-r5" x="1464" y="190.8" textLength="12.2" clip-path="url(#terminal-451286626-line-7)">
|
||||
</text><text class="terminal-451286626-r17" x="12.2" y="215.2" textLength="12.2" clip-path="url(#terminal-451286626-line-8)">○</text><text class="terminal-451286626-r19" x="48.8" y="215.2" textLength="12.2" clip-path="url(#terminal-451286626-line-8)">A</text><text class="terminal-451286626-r2" x="85.4" y="215.2" textLength="97.6" clip-path="url(#terminal-451286626-line-8)"> rtl/rx/</text><text class="terminal-451286626-r7" x="183" y="215.2" textLength="12.2" clip-path="url(#terminal-451286626-line-8)">█</text><text class="terminal-451286626-r7" x="1268.8" y="215.2" textLength="12.2" clip-path="url(#terminal-451286626-line-8)">█</text><text class="terminal-451286626-r5" x="1464" y="215.2" textLength="12.2" clip-path="url(#terminal-451286626-line-8)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="239.6" textLength="12.2" clip-path="url(#terminal-451286626-line-9)">█</text><text class="terminal-451286626-r20" x="219.6" y="239.6" textLength="963.8" clip-path="url(#terminal-451286626-line-9)">▲ 3 other local change(s) are not marked. They stay in the workspace, so sanity</text><text class="terminal-451286626-r7" x="1268.8" y="239.6" textLength="12.2" clip-path="url(#terminal-451286626-line-9)">█</text><text class="terminal-451286626-r5" x="1464" y="239.6" textLength="12.2" clip-path="url(#terminal-451286626-line-9)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="264" textLength="12.2" clip-path="url(#terminal-451286626-line-10)">█</text><text class="terminal-451286626-r20" x="219.6" y="264" textLength="549" clip-path="url(#terminal-451286626-line-10)">tests them too, but they won't be checked in.</text><text class="terminal-451286626-r7" x="1268.8" y="264" textLength="12.2" clip-path="url(#terminal-451286626-line-10)">█</text><text class="terminal-451286626-r9" x="1281" y="264" textLength="85.4" clip-path="url(#terminal-451286626-line-10)">on edit</text><text class="terminal-451286626-r5" x="1464" y="264" textLength="12.2" clip-path="url(#terminal-451286626-line-10)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="288.4" textLength="12.2" clip-path="url(#terminal-451286626-line-11)">█</text><text class="terminal-451286626-r7" x="1268.8" y="288.4" textLength="12.2" clip-path="url(#terminal-451286626-line-11)">█</text><text class="terminal-451286626-r2" x="1281" y="288.4" textLength="85.4" clip-path="url(#terminal-451286626-line-11)">6      </text><text class="terminal-451286626-r5" x="1464" y="288.4" textLength="12.2" clip-path="url(#terminal-451286626-line-11)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="312.8" textLength="12.2" clip-path="url(#terminal-451286626-line-12)">█</text><text class="terminal-451286626-r21" x="219.6" y="312.8" textLength="170.8" clip-path="url(#terminal-451286626-line-12)">Sanity configs</text><text class="terminal-451286626-r7" x="1268.8" y="312.8" textLength="12.2" clip-path="url(#terminal-451286626-line-12)">█</text><text class="terminal-451286626-r5" x="1464" y="312.8" textLength="12.2" clip-path="url(#terminal-451286626-line-12)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="337.2" textLength="12.2" clip-path="url(#terminal-451286626-line-13)">█</text><text class="terminal-451286626-r23" x="219.6" y="337.2" textLength="12.2" clip-path="url(#terminal-451286626-line-13)">▐</text><text class="terminal-451286626-r24" x="231.8" y="337.2" textLength="12.2" clip-path="url(#terminal-451286626-line-13)">X</text><text class="terminal-451286626-r23" x="244" y="337.2" textLength="12.2" clip-path="url(#terminal-451286626-line-13)">▌</text><text class="terminal-451286626-r1" x="268.4" y="337.2" textLength="97.6" clip-path="url(#terminal-451286626-line-13)">kibo_2x2</text><text class="terminal-451286626-r7" x="1268.8" y="337.2" textLength="12.2" clip-path="url(#terminal-451286626-line-13)">█</text><text class="terminal-451286626-r5" x="1464" y="337.2" textLength="12.2" clip-path="url(#terminal-451286626-line-13)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="361.6" textLength="12.2" clip-path="url(#terminal-451286626-line-14)">█</text><text class="terminal-451286626-r23" x="219.6" y="361.6" textLength="12.2" clip-path="url(#terminal-451286626-line-14)">▐</text><text class="terminal-451286626-r24" x="231.8" y="361.6" textLength="12.2" clip-path="url(#terminal-451286626-line-14)">X</text><text class="terminal-451286626-r23" x="244" y="361.6" textLength="12.2" clip-path="url(#terminal-451286626-line-14)">▌</text><text class="terminal-451286626-r1" x="268.4" y="361.6" textLength="122" clip-path="url(#terminal-451286626-line-14)">jaguar_1x1</text><text class="terminal-451286626-r7" x="1268.8" y="361.6" textLength="12.2" clip-path="url(#terminal-451286626-line-14)">█</text><text class="terminal-451286626-r5" x="1464" y="361.6" textLength="12.2" clip-path="url(#terminal-451286626-line-14)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="386" textLength="12.2" clip-path="url(#terminal-451286626-line-15)">█</text><text class="terminal-451286626-r7" x="1268.8" y="386" textLength="12.2" clip-path="url(#terminal-451286626-line-15)">█</text><text class="terminal-451286626-r5" x="1464" y="386" textLength="12.2" clip-path="url(#terminal-451286626-line-15)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="410.4" textLength="12.2" clip-path="url(#terminal-451286626-line-16)">█</text><text class="terminal-451286626-r21" x="219.6" y="410.4" textLength="85.4" clip-path="url(#terminal-451286626-line-16)">On pass</text><text class="terminal-451286626-r7" x="1268.8" y="410.4" textLength="12.2" clip-path="url(#terminal-451286626-line-16)">█</text><text class="terminal-451286626-r5" x="1464" y="410.4" textLength="12.2" clip-path="url(#terminal-451286626-line-16)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">█</text><text class="terminal-451286626-r23" x="219.6" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">▐</text><text class="terminal-451286626-r24" x="231.8" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">●</text><text class="terminal-451286626-r23" x="244" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">▌</text><text class="terminal-451286626-r1" x="268.4" y="434.8" textLength="97.6" clip-path="url(#terminal-451286626-line-17)">Check in</text><text class="terminal-451286626-r23" x="732" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">▐</text><text class="terminal-451286626-r25" x="744.2" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">●</text><text class="terminal-451286626-r23" x="756.4" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">▌</text><text class="terminal-451286626-r1" x="780.8" y="434.8" textLength="341.6" clip-path="url(#terminal-451286626-line-17)">Unlock only (check in later)</text><text class="terminal-451286626-r7" x="1268.8" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">█</text><text class="terminal-451286626-r5" x="1464" y="434.8" textLength="12.2" clip-path="url(#terminal-451286626-line-17)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="459.2" textLength="12.2" clip-path="url(#terminal-451286626-line-18)">█</text><text class="terminal-451286626-r7" x="1268.8" y="459.2" textLength="12.2" clip-path="url(#terminal-451286626-line-18)">█</text><text class="terminal-451286626-r5" x="1464" y="459.2" textLength="12.2" clip-path="url(#terminal-451286626-line-18)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="483.6" textLength="12.2" clip-path="url(#terminal-451286626-line-19)">█</text><text class="terminal-451286626-r21" x="219.6" y="483.6" textLength="195.2" clip-path="url(#terminal-451286626-line-19)">Check-in comment</text><text class="terminal-451286626-r7" x="1268.8" y="483.6" textLength="12.2" clip-path="url(#terminal-451286626-line-19)">█</text><text class="terminal-451286626-r5" x="1464" y="483.6" textLength="12.2" clip-path="url(#terminal-451286626-line-19)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="508" textLength="12.2" clip-path="url(#terminal-451286626-line-20)">█</text><text class="terminal-451286626-r26" x="219.6" y="508" textLength="12.2" clip-path="url(#terminal-451286626-line-20)">▊</text><text class="terminal-451286626-r27" x="231.8" y="508" textLength="1000.4" clip-path="url(#terminal-451286626-line-20)">▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔▔</text><text class="terminal-451286626-r27" x="1232.2" y="508" textLength="12.2" clip-path="url(#terminal-451286626-line-20)">▎</text><text class="terminal-451286626-r7" x="1268.8" y="508" textLength="12.2" clip-path="url(#terminal-451286626-line-20)">█</text><text class="terminal-451286626-r5" x="1464" y="508" textLength="12.2" clip-path="url(#terminal-451286626-line-20)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="532.4" textLength="12.2" clip-path="url(#terminal-451286626-line-21)">█</text><text class="terminal-451286626-r26" x="219.6" y="532.4" textLength="12.2" clip-path="url(#terminal-451286626-line-21)">▊</text><text class="terminal-451286626-r1" x="256.2" y="532.4" textLength="268.4" clip-path="url(#terminal-451286626-line-21)">fix rx fsm corner case</text><text class="terminal-451286626-r27" x="1232.2" y="532.4" textLength="12.2" clip-path="url(#terminal-451286626-line-21)">▎</text><text class="terminal-451286626-r7" x="1268.8" y="532.4" textLength="12.2" clip-path="url(#terminal-451286626-line-21)">█</text><text class="terminal-451286626-r5" x="1464" y="532.4" textLength="12.2" clip-path="url(#terminal-451286626-line-21)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="556.8" textLength="12.2" clip-path="url(#terminal-451286626-line-22)">█</text><text class="terminal-451286626-r26" x="219.6" y="556.8" textLength="12.2" clip-path="url(#terminal-451286626-line-22)">▊</text><text class="terminal-451286626-r27" x="231.8" y="556.8" textLength="1000.4" clip-path="url(#terminal-451286626-line-22)">▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁▁</text><text class="terminal-451286626-r27" x="1232.2" y="556.8" textLength="12.2" clip-path="url(#terminal-451286626-line-22)">▎</text><text class="terminal-451286626-r7" x="1268.8" y="556.8" textLength="12.2" clip-path="url(#terminal-451286626-line-22)">█</text><text class="terminal-451286626-r5" x="1464" y="556.8" textLength="12.2" clip-path="url(#terminal-451286626-line-22)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="581.2" textLength="12.2" clip-path="url(#terminal-451286626-line-23)">█</text><text class="terminal-451286626-r7" x="1268.8" y="581.2" textLength="12.2" clip-path="url(#terminal-451286626-line-23)">█</text><text class="terminal-451286626-r5" x="1464" y="581.2" textLength="12.2" clip-path="url(#terminal-451286626-line-23)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="605.6" textLength="12.2" clip-path="url(#terminal-451286626-line-24)">█</text><text class="terminal-451286626-r21" x="219.6" y="605.6" textLength="97.6" clip-path="url(#terminal-451286626-line-24)">Then tag</text><text class="terminal-451286626-r7" x="1268.8" y="605.6" textLength="12.2" clip-path="url(#terminal-451286626-line-24)">█</text><text class="terminal-451286626-r5" x="1464" y="605.6" textLength="12.2" clip-path="url(#terminal-451286626-line-24)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">█</text><text class="terminal-451286626-r23" x="219.6" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">▐</text><text class="terminal-451286626-r24" x="231.8" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">●</text><text class="terminal-451286626-r23" x="244" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">▌</text><text class="terminal-451286626-r1" x="268.4" y="630" textLength="48.8" clip-path="url(#terminal-451286626-line-25)">none</text><text class="terminal-451286626-r23" x="561.2" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">▐</text><text class="terminal-451286626-r25" x="573.4" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">●</text><text class="terminal-451286626-r23" x="585.6" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">▌</text><text class="terminal-451286626-r1" x="610" y="630" textLength="146.4" clip-path="url(#terminal-451286626-line-25)">wmac_working</text><text class="terminal-451286626-r23" x="902.8" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">▐</text><text class="terminal-451286626-r25" x="915" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">●</text><text class="terminal-451286626-r23" x="927.2" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">▌</text><text class="terminal-451286626-r1" x="951.6" y="630" textLength="146.4" clip-path="url(#terminal-451286626-line-25)">wmac_rx_drop</text><text class="terminal-451286626-r7" x="1268.8" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">█</text><text class="terminal-451286626-r5" x="1464" y="630" textLength="12.2" clip-path="url(#terminal-451286626-line-25)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="654.4" textLength="12.2" clip-path="url(#terminal-451286626-line-26)">█</text><text class="terminal-451286626-r7" x="1268.8" y="654.4" textLength="12.2" clip-path="url(#terminal-451286626-line-26)">█</text><text class="terminal-451286626-r5" x="1464" y="654.4" textLength="12.2" clip-path="url(#terminal-451286626-line-26)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="678.8" textLength="12.2" clip-path="url(#terminal-451286626-line-27)">█</text><text class="terminal-451286626-r23" x="219.6" y="678.8" textLength="12.2" clip-path="url(#terminal-451286626-line-27)">▐</text><text class="terminal-451286626-r24" x="231.8" y="678.8" textLength="12.2" clip-path="url(#terminal-451286626-line-27)">X</text><text class="terminal-451286626-r23" x="244" y="678.8" textLength="12.2" clip-path="url(#terminal-451286626-line-27)">▌</text><text class="terminal-451286626-r1" x="268.4" y="678.8" textLength="561.2" clip-path="url(#terminal-451286626-line-27)">Refresh unmodified files to Trunk:Latest first</text><text class="terminal-451286626-r7" x="1268.8" y="678.8" textLength="12.2" clip-path="url(#terminal-451286626-line-27)">█</text><text class="terminal-451286626-r5" x="1464" y="678.8" textLength="12.2" clip-path="url(#terminal-451286626-line-27)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="703.2" textLength="12.2" clip-path="url(#terminal-451286626-line-28)">█</text><text class="terminal-451286626-r7" x="1268.8" y="703.2" textLength="12.2" clip-path="url(#terminal-451286626-line-28)">█</text><text class="terminal-451286626-r5" x="1464" y="703.2" textLength="12.2" clip-path="url(#terminal-451286626-line-28)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="727.6" textLength="12.2" clip-path="url(#terminal-451286626-line-29)">█</text><text class="terminal-451286626-r7" x="1268.8" y="727.6" textLength="12.2" clip-path="url(#terminal-451286626-line-29)">█</text><text class="terminal-451286626-r5" x="1464" y="727.6" textLength="12.2" clip-path="url(#terminal-451286626-line-29)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="752" textLength="12.2" clip-path="url(#terminal-451286626-line-30)">█</text><text class="terminal-451286626-r7" x="1268.8" y="752" textLength="12.2" clip-path="url(#terminal-451286626-line-30)">█</text><text class="terminal-451286626-r5" x="1464" y="752" textLength="12.2" clip-path="url(#terminal-451286626-line-30)">
|
||||
</text><text class="terminal-451286626-r7" x="183" y="776.4" textLength="12.2" clip-path="url(#terminal-451286626-line-31)">█</text><text class="terminal-451286626-r7" x="195.2" y="776.4" textLength="1073.6" clip-path="url(#terminal-451286626-line-31)">▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄</text><text class="terminal-451286626-r7" x="1268.8" y="776.4" textLength="12.2" clip-path="url(#terminal-451286626-line-31)">█</text><text class="terminal-451286626-r5" x="1464" y="776.4" textLength="12.2" clip-path="url(#terminal-451286626-line-31)">
|
||||
</text><text class="terminal-451286626-r17" x="12.2" y="800.8" textLength="1342" clip-path="url(#terminal-451286626-line-32)">○ no sanity run yet                                                                                           </text><text class="terminal-451286626-r30" x="1354.2" y="800.8" textLength="97.6" clip-path="url(#terminal-451286626-line-32)">2 marked</text><text class="terminal-451286626-r5" x="1464" y="800.8" textLength="12.2" clip-path="url(#terminal-451286626-line-32)">
|
||||
</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 68 KiB |
Generated
+208
@@ -0,0 +1,208 @@
|
||||
<svg class="rich-terminal" viewBox="0 0 1482 879.5999999999999" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Generated with Rich https://www.textualize.io -->
|
||||
<style>
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Regular"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Bold"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");
|
||||
font-style: bold;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.terminal-1615560248-matrix {
|
||||
font-family: Fira Code, monospace;
|
||||
font-size: 20px;
|
||||
line-height: 24.4px;
|
||||
font-variant-east-asian: full-width;
|
||||
}
|
||||
|
||||
.terminal-1615560248-title {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
font-family: arial;
|
||||
}
|
||||
|
||||
.terminal-1615560248-r1 { fill: #c5c8c6 }
|
||||
.terminal-1615560248-r2 { fill: #a9b1d6 }
|
||||
.terminal-1615560248-r3 { fill: #858db0 }
|
||||
.terminal-1615560248-r4 { fill: #9aa1c6 }
|
||||
.terminal-1615560248-r5 { fill: #61667e }
|
||||
.terminal-1615560248-r6 { fill: #282a37 }
|
||||
.terminal-1615560248-r7 { fill: #bb9af7 }
|
||||
.terminal-1615560248-r8 { fill: #a9b1d6;font-weight: bold }
|
||||
.terminal-1615560248-r9 { fill: #1a1b26;font-weight: bold }
|
||||
.terminal-1615560248-r10 { fill: #737aa2 }
|
||||
.terminal-1615560248-r11 { fill: #9ece6a;font-weight: bold }
|
||||
.terminal-1615560248-r12 { fill: #7aa2f7 }
|
||||
.terminal-1615560248-r13 { fill: #4a4164 }
|
||||
.terminal-1615560248-r14 { fill: #9ece6a }
|
||||
.terminal-1615560248-r15 { fill: #5a4d79 }
|
||||
.terminal-1615560248-r16 { fill: #a9abb3 }
|
||||
.terminal-1615560248-r17 { fill: #4f4270 }
|
||||
.terminal-1615560248-r18 { fill: #2a2e42 }
|
||||
.terminal-1615560248-r19 { fill: #ff9e64;font-weight: bold }
|
||||
.terminal-1615560248-r20 { fill: #555d7e }
|
||||
</style>
|
||||
|
||||
<defs>
|
||||
<clipPath id="terminal-1615560248-clip-terminal">
|
||||
<rect x="0" y="0" width="1463.0" height="828.5999999999999" />
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-0">
|
||||
<rect x="0" y="1.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-1">
|
||||
<rect x="0" y="25.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-2">
|
||||
<rect x="0" y="50.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-3">
|
||||
<rect x="0" y="74.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-4">
|
||||
<rect x="0" y="99.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-5">
|
||||
<rect x="0" y="123.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-6">
|
||||
<rect x="0" y="147.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-7">
|
||||
<rect x="0" y="172.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-8">
|
||||
<rect x="0" y="196.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-9">
|
||||
<rect x="0" y="221.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-10">
|
||||
<rect x="0" y="245.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-11">
|
||||
<rect x="0" y="269.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-12">
|
||||
<rect x="0" y="294.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-13">
|
||||
<rect x="0" y="318.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-14">
|
||||
<rect x="0" y="343.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-15">
|
||||
<rect x="0" y="367.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-16">
|
||||
<rect x="0" y="391.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-17">
|
||||
<rect x="0" y="416.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-18">
|
||||
<rect x="0" y="440.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-19">
|
||||
<rect x="0" y="465.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-20">
|
||||
<rect x="0" y="489.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-21">
|
||||
<rect x="0" y="513.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-22">
|
||||
<rect x="0" y="538.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-23">
|
||||
<rect x="0" y="562.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-24">
|
||||
<rect x="0" y="587.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-25">
|
||||
<rect x="0" y="611.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-26">
|
||||
<rect x="0" y="635.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-27">
|
||||
<rect x="0" y="660.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-28">
|
||||
<rect x="0" y="684.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-29">
|
||||
<rect x="0" y="709.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-30">
|
||||
<rect x="0" y="733.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-31">
|
||||
<rect x="0" y="757.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-1615560248-line-32">
|
||||
<rect x="0" y="782.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="1" y="1" width="1480" height="877.6" rx="8"/><text class="terminal-1615560248-title" fill="#c5c8c6" text-anchor="middle" x="740" y="27">dsflow  ·  querying DesignSync…</text>
|
||||
<g transform="translate(26,22)">
|
||||
<circle cx="0" cy="0" r="7" fill="#ff5f57"/>
|
||||
<circle cx="22" cy="0" r="7" fill="#febc2e"/>
|
||||
<circle cx="44" cy="0" r="7" fill="#28c840"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(9, 41)" clip-path="url(#terminal-1615560248-clip-terminal)">
|
||||
<rect fill="#414868" x="0" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="12.2" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="24.4" y="1.5" width="61" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="85.4" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="97.6" y="1.5" width="122" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="219.6" y="1.5" width="378.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="597.8" y="1.5" width="36.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="634.4" y="1.5" width="573.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="1207.8" y="1.5" width="134.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1342" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1354.2" y="1.5" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1451.8" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="12.2" y="25.9" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="122" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="134.2" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="146.4" y="25.9" width="85.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="231.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="244" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="256.2" y="25.9" width="158.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="414.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="427" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="439.2" y="25.9" width="146.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="585.6" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="597.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="610" y="25.9" width="48.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="658.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="671" y="25.9" width="793" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="50.3" width="427" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="427" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="439.2" y="50.3" width="146.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="585.6" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="597.8" y="50.3" width="866.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="74.7" width="1464" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="24.4" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="36.6" y="99.1" width="256.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#9ece6a" x="292.8" y="99.1" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="390.4" y="99.1" width="341.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="732" y="99.1" width="695.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1427.4" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1439.6" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="123.5" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="24.4" y="123.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="36.6" y="123.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="146.4" y="123.5" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="244" y="123.5" width="329.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="573.4" y="123.5" width="854" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1427.4" y="123.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1439.6" y="123.5" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="147.9" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="24.4" y="147.9" Line truncated
|
||||
<g class="terminal-1615560248-matrix">
|
||||
<text class="terminal-1615560248-r2" x="12.2" y="20" textLength="12.2" clip-path="url(#terminal-1615560248-line-0)">◆</text><text class="terminal-1615560248-r2" x="219.6" y="20" textLength="378.2" clip-path="url(#terminal-1615560248-line-0)">dsflow  ·  querying DesignSync…</text><text class="terminal-1615560248-r3" x="597.8" y="20" textLength="36.6" clip-path="url(#terminal-1615560248-line-0)"> — </text><text class="terminal-1615560248-r3" x="634.4" y="20" textLength="573.4" clip-path="url(#terminal-1615560248-line-0)">demo sandbox · Trunk:Latest · green tag working</text><text class="terminal-1615560248-r4" x="1354.2" y="20" textLength="97.6" clip-path="url(#terminal-1615560248-line-0)">03:20:31</text><text class="terminal-1615560248-r1" x="1464" y="20" textLength="12.2" clip-path="url(#terminal-1615560248-line-0)">
|
||||
</text><text class="terminal-1615560248-r5" x="12.2" y="44.4" textLength="109.8" clip-path="url(#terminal-1615560248-line-1)">Changes 5</text><text class="terminal-1615560248-r5" x="146.4" y="44.4" textLength="85.4" clip-path="url(#terminal-1615560248-line-1)">Locks 2</text><text class="terminal-1615560248-r5" x="256.2" y="44.4" textLength="158.6" clip-path="url(#terminal-1615560248-line-1)">Checked-out 3</text><text class="terminal-1615560248-r2" x="439.2" y="44.4" textLength="146.4" clip-path="url(#terminal-1615560248-line-1)">Sanity run ✔</text><text class="terminal-1615560248-r5" x="610" y="44.4" textLength="48.8" clip-path="url(#terminal-1615560248-line-1)">Logs</text><text class="terminal-1615560248-r1" x="1464" y="44.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-1)">
|
||||
</text><text class="terminal-1615560248-r6" x="0" y="68.8" textLength="427" clip-path="url(#terminal-1615560248-line-2)">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</text><text class="terminal-1615560248-r6" x="427" y="68.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-2)">╸</text><text class="terminal-1615560248-r7" x="439.2" y="68.8" textLength="146.4" clip-path="url(#terminal-1615560248-line-2)">━━━━━━━━━━━━</text><text class="terminal-1615560248-r6" x="585.6" y="68.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-2)">╺</text><text class="terminal-1615560248-r6" x="597.8" y="68.8" textLength="866.2" clip-path="url(#terminal-1615560248-line-2)">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</text><text class="terminal-1615560248-r1" x="1464" y="68.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-2)">
|
||||
</text><text class="terminal-1615560248-r1" x="1464" y="93.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-3)">
|
||||
</text><text class="terminal-1615560248-r8" x="36.6" y="117.6" textLength="256.2" clip-path="url(#terminal-1615560248-line-4)">Run 20260924-032021  </text><text class="terminal-1615560248-r9" x="292.8" y="117.6" textLength="97.6" clip-path="url(#terminal-1615560248-line-4)"> PASSED </text><text class="terminal-1615560248-r10" x="732" y="117.6" textLength="695.4" clip-path="url(#terminal-1615560248-line-4)">                           started 03:20:21 · elapsed 10s</text><text class="terminal-1615560248-r1" x="1464" y="117.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-4)">
|
||||
</text><text class="terminal-1615560248-r10" x="36.6" y="142" textLength="109.8" clip-path="url(#terminal-1615560248-line-5)">on pass  </text><text class="terminal-1615560248-r11" x="146.4" y="142" textLength="97.6" clip-path="url(#terminal-1615560248-line-5)">check in</text><text class="terminal-1615560248-r2" x="244" y="142" textLength="329.4" clip-path="url(#terminal-1615560248-line-5)">   “fix rx fsm corner case”</text><text class="terminal-1615560248-r1" x="1464" y="142" textLength="12.2" clip-path="url(#terminal-1615560248-line-5)">
|
||||
</text><text class="terminal-1615560248-r10" x="36.6" y="166.4" textLength="85.4" clip-path="url(#terminal-1615560248-line-6)">files  </text><text class="terminal-1615560248-r2" x="122" y="166.4" textLength="500.2" clip-path="url(#terminal-1615560248-line-6)">rtl/rx/rx_fsm.sv, rtl/top/wifi_mac_top.sv</text><text class="terminal-1615560248-r12" x="622.2" y="166.4" textLength="231.8" clip-path="url(#terminal-1615560248-line-6)">   locked by run: 1</text><text class="terminal-1615560248-r1" x="1464" y="166.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-6)">
|
||||
</text><text class="terminal-1615560248-r1" x="1464" y="190.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-7)">
|
||||
</text><text class="terminal-1615560248-r13" x="24.4" y="215.2" textLength="1415.2" clip-path="url(#terminal-1615560248-line-8)">────────────────────────────────────────────────────────────────────────────────────────────────────────────────────</text><text class="terminal-1615560248-r1" x="1464" y="215.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-8)">
|
||||
</text><text class="terminal-1615560248-r1" x="1464" y="239.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-9)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="264" textLength="12.2" clip-path="url(#terminal-1615560248-line-10)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="264" textLength="280.6" clip-path="url(#terminal-1615560248-line-10)">Check freshness & locks</text><text class="terminal-1615560248-r10" x="719.8" y="264" textLength="24.4" clip-path="url(#terminal-1615560248-line-10)">0s</text><text class="terminal-1615560248-r10" x="768.6" y="264" textLength="341.6" clip-path="url(#terminal-1615560248-line-10)">2 modified, 0 new           </text><text class="terminal-1615560248-r1" x="1464" y="264" textLength="12.2" clip-path="url(#terminal-1615560248-line-10)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="288.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-11)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="288.4" textLength="280.6" clip-path="url(#terminal-1615560248-line-11)">Lock 2 file(s)         </text><text class="terminal-1615560248-r10" x="719.8" y="288.4" textLength="24.4" clip-path="url(#terminal-1615560248-line-11)">0s</text><text class="terminal-1615560248-r10" x="768.6" y="288.4" textLength="341.6" clip-path="url(#terminal-1615560248-line-11)">1 locked, 1 already yours   </text><text class="terminal-1615560248-r1" x="1464" y="288.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-11)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="312.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-12)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="312.8" textLength="280.6" clip-path="url(#terminal-1615560248-line-12)">Refresh to Trunk:Latest</text><text class="terminal-1615560248-r10" x="719.8" y="312.8" textLength="24.4" clip-path="url(#terminal-1615560248-line-12)">0s</text><text class="terminal-1615560248-r1" x="1464" y="312.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-12)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="337.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-13)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="337.2" textLength="280.6" clip-path="url(#terminal-1615560248-line-13)">Sanity kibo_2x2        </text><text class="terminal-1615560248-r14" x="378.2" y="337.2" textLength="317.2" clip-path="url(#terminal-1615560248-line-13)">━━━━━━━━━━━━━━━━━━━━━━━━━━</text><text class="terminal-1615560248-r10" x="719.8" y="337.2" textLength="24.4" clip-path="url(#terminal-1615560248-line-13)">4s</text><text class="terminal-1615560248-r10" x="768.6" y="337.2" textLength="341.6" clip-path="url(#terminal-1615560248-line-13)">passed in 4s                </text><text class="terminal-1615560248-r1" x="1464" y="337.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-13)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="361.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-14)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="361.6" textLength="280.6" clip-path="url(#terminal-1615560248-line-14)">Sanity jaguar_1x1      </text><text class="terminal-1615560248-r14" x="378.2" y="361.6" textLength="317.2" clip-path="url(#terminal-1615560248-line-14)">━━━━━━━━━━━━━━━━━━━━━━━━━━</text><text class="terminal-1615560248-r10" x="719.8" y="361.6" textLength="24.4" clip-path="url(#terminal-1615560248-line-14)">4s</text><text class="terminal-1615560248-r10" x="768.6" y="361.6" textLength="341.6" clip-path="url(#terminal-1615560248-line-14)">passed in 4s                </text><text class="terminal-1615560248-r1" x="1464" y="361.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-14)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="386" textLength="12.2" clip-path="url(#terminal-1615560248-line-15)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="386" textLength="280.6" clip-path="url(#terminal-1615560248-line-15)">Verify files unchanged </text><text class="terminal-1615560248-r10" x="719.8" y="386" textLength="24.4" clip-path="url(#terminal-1615560248-line-15)">0s</text><text class="terminal-1615560248-r1" x="1464" y="386" textLength="12.2" clip-path="url(#terminal-1615560248-line-15)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="410.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-16)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="410.4" textLength="280.6" clip-path="url(#terminal-1615560248-line-16)">Check in 2 file(s)     </text><text class="terminal-1615560248-r10" x="719.8" y="410.4" textLength="24.4" clip-path="url(#terminal-1615560248-line-16)">0s</text><text class="terminal-1615560248-r10" x="768.6" y="410.4" textLength="341.6" clip-path="url(#terminal-1615560248-line-16)">checked in 2 file(s)        </text><text class="terminal-1615560248-r1" x="1464" y="410.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-16)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="434.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-17)">✔</text><text class="terminal-1615560248-r2" x="73.2" y="434.8" textLength="280.6" clip-path="url(#terminal-1615560248-line-17)">Release run locks      </text><text class="terminal-1615560248-r10" x="719.8" y="434.8" textLength="24.4" clip-path="url(#terminal-1615560248-line-17)">0s</text><text class="terminal-1615560248-r10" x="768.6" y="434.8" textLength="341.6" clip-path="url(#terminal-1615560248-line-17)">already released by check-in</text><text class="terminal-1615560248-r1" x="1464" y="434.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-17)">
|
||||
</text><text class="terminal-1615560248-r1" x="1464" y="459.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-18)">
|
||||
</text><text class="terminal-1615560248-r11" x="36.6" y="483.6" textLength="719.8" clip-path="url(#terminal-1615560248-line-19)">sanity passed on kibo_2x2 jaguar_1x1 - checked in 2 file(s)</text><text class="terminal-1615560248-r1" x="1464" y="483.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-19)">
|
||||
</text><text class="terminal-1615560248-r1" x="1464" y="508" textLength="12.2" clip-path="url(#terminal-1615560248-line-20)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="532.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-21)">╭</text><text class="terminal-1615560248-r15" x="36.6" y="532.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-21)">─</text><text class="terminal-1615560248-r16" x="48.8" y="532.4" textLength="353.8" clip-path="url(#terminal-1615560248-line-21)"> log · sanity_jaguar_1x1.log </text><text class="terminal-1615560248-r15" x="402.6" y="532.4" textLength="1024.8" clip-path="url(#terminal-1615560248-line-21)">────────────────────────────────────────────────────────────────────────────────────</text><text class="terminal-1615560248-r15" x="1427.4" y="532.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-21)">╮</text><text class="terminal-1615560248-r1" x="1464" y="532.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-21)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="556.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-22)">│</text><text class="terminal-1615560248-r14" x="36.6" y="556.8" textLength="463.6" clip-path="url(#terminal-1615560248-line-22)">[jaguar_1x1] 03:20:26 test_01 ... PASS</text><text class="terminal-1615560248-r15" x="1427.4" y="556.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-22)">│</text><text class="terminal-1615560248-r1" x="1464" y="556.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-22)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="581.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-23)">│</text><text class="terminal-1615560248-r14" x="36.6" y="581.2" textLength="463.6" clip-path="url(#terminal-1615560248-line-23)">[jaguar_1x1] 03:20:27 test_02 ... PASS</text><text class="terminal-1615560248-r15" x="1427.4" y="581.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-23)">│</text><text class="terminal-1615560248-r1" x="1464" y="581.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-23)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="605.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-24)">│</text><text class="terminal-1615560248-r14" x="36.6" y="605.6" textLength="463.6" clip-path="url(#terminal-1615560248-line-24)">[jaguar_1x1] 03:20:28 test_03 ... PASS</text><text class="terminal-1615560248-r17" x="1415.2" y="605.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-24)">▆</text><text class="terminal-1615560248-r15" x="1427.4" y="605.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-24)">│</text><text class="terminal-1615560248-r1" x="1464" y="605.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-24)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="630" textLength="12.2" clip-path="url(#terminal-1615560248-line-25)">│</text><text class="terminal-1615560248-r14" x="36.6" y="630" textLength="463.6" clip-path="url(#terminal-1615560248-line-25)">[jaguar_1x1] 03:20:28 test_04 ... PASS</text><text class="terminal-1615560248-r15" x="1427.4" y="630" textLength="12.2" clip-path="url(#terminal-1615560248-line-25)">│</text><text class="terminal-1615560248-r1" x="1464" y="630" textLength="12.2" clip-path="url(#terminal-1615560248-line-25)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="654.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-26)">│</text><text class="terminal-1615560248-r14" x="36.6" y="654.4" textLength="463.6" clip-path="url(#terminal-1615560248-line-26)">[jaguar_1x1] 03:20:29 test_05 ... PASS</text><text class="terminal-1615560248-r15" x="1427.4" y="654.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-26)">│</text><text class="terminal-1615560248-r1" x="1464" y="654.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-26)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="678.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-27)">│</text><text class="terminal-1615560248-r14" x="36.6" y="678.8" textLength="463.6" clip-path="url(#terminal-1615560248-line-27)">[jaguar_1x1] 03:20:29 test_06 ... PASS</text><text class="terminal-1615560248-r15" x="1427.4" y="678.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-27)">│</text><text class="terminal-1615560248-r1" x="1464" y="678.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-27)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="703.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-28)">│</text><text class="terminal-1615560248-r14" x="36.6" y="703.2" textLength="463.6" clip-path="url(#terminal-1615560248-line-28)">[jaguar_1x1] 03:20:30 test_07 ... PASS</text><text class="terminal-1615560248-r15" x="1427.4" y="703.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-28)">│</text><text class="terminal-1615560248-r1" x="1464" y="703.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-28)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="727.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-29)">│</text><text class="terminal-1615560248-r14" x="36.6" y="727.6" textLength="463.6" clip-path="url(#terminal-1615560248-line-29)">[jaguar_1x1] 03:20:30 test_08 ... PASS</text><text class="terminal-1615560248-r15" x="1427.4" y="727.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-29)">│</text><text class="terminal-1615560248-r1" x="1464" y="727.6" textLength="12.2" clip-path="url(#terminal-1615560248-line-29)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="752" textLength="12.2" clip-path="url(#terminal-1615560248-line-30)">│</text><text class="terminal-1615560248-r14" x="36.6" y="752" textLength="378.2" clip-path="url(#terminal-1615560248-line-30)">[jaguar_1x1] all 8 tests passed</text><text class="terminal-1615560248-r15" x="1427.4" y="752" textLength="12.2" clip-path="url(#terminal-1615560248-line-30)">│</text><text class="terminal-1615560248-r1" x="1464" y="752" textLength="12.2" clip-path="url(#terminal-1615560248-line-30)">
|
||||
</text><text class="terminal-1615560248-r15" x="24.4" y="776.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-31)">╰</text><text class="terminal-1615560248-r15" x="36.6" y="776.4" textLength="1390.8" clip-path="url(#terminal-1615560248-line-31)">──────────────────────────────────────────────────────────────────────────────────────────────────────────────────</text><text class="terminal-1615560248-r15" x="1427.4" y="776.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-31)">╯</text><text class="terminal-1615560248-r1" x="1464" y="776.4" textLength="12.2" clip-path="url(#terminal-1615560248-line-31)">
|
||||
</text><text class="terminal-1615560248-r10" x="12.2" y="800.8" textLength="109.8" clip-path="url(#terminal-1615560248-line-32)">last run </text><text class="terminal-1615560248-r9" x="122" y="800.8" textLength="97.6" clip-path="url(#terminal-1615560248-line-32)"> PASSED </text><text class="terminal-1615560248-r10" x="219.6" y="800.8" textLength="122" clip-path="url(#terminal-1615560248-line-32)">  0s ago  </text><text class="terminal-1615560248-r10" x="341.6" y="800.8" textLength="719.8" clip-path="url(#terminal-1615560248-line-32)">sanity passed on kibo_2x2 jaguar_1x1 - checked in 2 file(s)</text><text class="terminal-1615560248-r10" x="1354.2" y="800.8" textLength="97.6" clip-path="url(#terminal-1615560248-line-32)">0 marked</text><text class="terminal-1615560248-r1" x="1464" y="800.8" textLength="12.2" clip-path="url(#terminal-1615560248-line-32)">
|
||||
</text><text class="terminal-1615560248-r19" x="0" y="825.2" textLength="36.6" clip-path="url(#terminal-1615560248-line-33)"> c </text><text class="terminal-1615560248-r2" x="36.6" y="825.2" textLength="109.8" clip-path="url(#terminal-1615560248-line-33)">Check in </text><text class="terminal-1615560248-r19" x="146.4" y="825.2" textLength="36.6" clip-path="url(#terminal-1615560248-line-33)"> r </text><text class="terminal-1615560248-r2" x="183" y="825.2" textLength="97.6" clip-path="url(#terminal-1615560248-line-33)">Refresh </text><text class="terminal-1615560248-r19" x="280.6" y="825.2" textLength="36.6" clip-path="url(#terminal-1615560248-line-33)"> ? </text><text class="terminal-1615560248-r2" x="317.2" y="825.2" textLength="61" clip-path="url(#terminal-1615560248-line-33)">Help </text><text class="terminal-1615560248-r19" x="378.2" y="825.2" textLength="36.6" clip-path="url(#terminal-1615560248-line-33)"> q </text><text class="terminal-1615560248-r2" x="414.8" y="825.2" textLength="61" clip-path="url(#terminal-1615560248-line-33)">Quit </text><text class="terminal-1615560248-r20" x="1317.6" y="825.2" textLength="12.2" clip-path="url(#terminal-1615560248-line-33)">▏</text><text class="terminal-1615560248-r19" x="1329.8" y="825.2" textLength="24.4" clip-path="url(#terminal-1615560248-line-33)">^p</text><text class="terminal-1615560248-r2" x="1354.2" y="825.2" textLength="97.6" clip-path="url(#terminal-1615560248-line-33)"> palette</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 57 KiB |
Generated
+208
@@ -0,0 +1,208 @@
|
||||
<svg class="rich-terminal" viewBox="0 0 1482 879.5999999999999" xmlns="http://www.w3.org/2000/svg">
|
||||
<!-- Generated with Rich https://www.textualize.io -->
|
||||
<style>
|
||||
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Regular"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Regular.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Regular.woff") format("woff");
|
||||
font-style: normal;
|
||||
font-weight: 400;
|
||||
}
|
||||
@font-face {
|
||||
font-family: "Fira Code";
|
||||
src: local("FiraCode-Bold"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff2/FiraCode-Bold.woff2") format("woff2"),
|
||||
url("https://cdnjs.cloudflare.com/ajax/libs/firacode/6.2.0/woff/FiraCode-Bold.woff") format("woff");
|
||||
font-style: bold;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.terminal-3078246834-matrix {
|
||||
font-family: Fira Code, monospace;
|
||||
font-size: 20px;
|
||||
line-height: 24.4px;
|
||||
font-variant-east-asian: full-width;
|
||||
}
|
||||
|
||||
.terminal-3078246834-title {
|
||||
font-size: 18px;
|
||||
font-weight: bold;
|
||||
font-family: arial;
|
||||
}
|
||||
|
||||
.terminal-3078246834-r1 { fill: #c5c8c6 }
|
||||
.terminal-3078246834-r2 { fill: #a9b1d6 }
|
||||
.terminal-3078246834-r3 { fill: #858db0 }
|
||||
.terminal-3078246834-r4 { fill: #9aa1c6 }
|
||||
.terminal-3078246834-r5 { fill: #61667e }
|
||||
.terminal-3078246834-r6 { fill: #282a37 }
|
||||
.terminal-3078246834-r7 { fill: #bb9af7 }
|
||||
.terminal-3078246834-r8 { fill: #a9b1d6;font-weight: bold }
|
||||
.terminal-3078246834-r9 { fill: #1a1b26;font-weight: bold }
|
||||
.terminal-3078246834-r10 { fill: #737aa2 }
|
||||
.terminal-3078246834-r11 { fill: #9ece6a;font-weight: bold }
|
||||
.terminal-3078246834-r12 { fill: #7aa2f7 }
|
||||
.terminal-3078246834-r13 { fill: #4a4164 }
|
||||
.terminal-3078246834-r14 { fill: #7aa2f7;font-weight: bold }
|
||||
.terminal-3078246834-r15 { fill: #3a3a3a }
|
||||
.terminal-3078246834-r16 { fill: #5a4d79 }
|
||||
.terminal-3078246834-r17 { fill: #a9abb3 }
|
||||
.terminal-3078246834-r18 { fill: #9ece6a }
|
||||
.terminal-3078246834-r19 { fill: #ff9e64;font-weight: bold }
|
||||
.terminal-3078246834-r20 { fill: #555d7e }
|
||||
</style>
|
||||
|
||||
<defs>
|
||||
<clipPath id="terminal-3078246834-clip-terminal">
|
||||
<rect x="0" y="0" width="1463.0" height="828.5999999999999" />
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-0">
|
||||
<rect x="0" y="1.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-1">
|
||||
<rect x="0" y="25.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-2">
|
||||
<rect x="0" y="50.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-3">
|
||||
<rect x="0" y="74.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-4">
|
||||
<rect x="0" y="99.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-5">
|
||||
<rect x="0" y="123.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-6">
|
||||
<rect x="0" y="147.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-7">
|
||||
<rect x="0" y="172.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-8">
|
||||
<rect x="0" y="196.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-9">
|
||||
<rect x="0" y="221.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-10">
|
||||
<rect x="0" y="245.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-11">
|
||||
<rect x="0" y="269.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-12">
|
||||
<rect x="0" y="294.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-13">
|
||||
<rect x="0" y="318.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-14">
|
||||
<rect x="0" y="343.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-15">
|
||||
<rect x="0" y="367.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-16">
|
||||
<rect x="0" y="391.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-17">
|
||||
<rect x="0" y="416.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-18">
|
||||
<rect x="0" y="440.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-19">
|
||||
<rect x="0" y="465.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-20">
|
||||
<rect x="0" y="489.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-21">
|
||||
<rect x="0" y="513.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-22">
|
||||
<rect x="0" y="538.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-23">
|
||||
<rect x="0" y="562.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-24">
|
||||
<rect x="0" y="587.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-25">
|
||||
<rect x="0" y="611.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-26">
|
||||
<rect x="0" y="635.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-27">
|
||||
<rect x="0" y="660.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-28">
|
||||
<rect x="0" y="684.7" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-29">
|
||||
<rect x="0" y="709.1" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-30">
|
||||
<rect x="0" y="733.5" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-31">
|
||||
<rect x="0" y="757.9" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
<clipPath id="terminal-3078246834-line-32">
|
||||
<rect x="0" y="782.3" width="1464" height="24.65"/>
|
||||
</clipPath>
|
||||
</defs>
|
||||
|
||||
<rect fill="#292929" stroke="rgba(255,255,255,0.35)" stroke-width="1" x="1" y="1" width="1480" height="877.6" rx="8"/><text class="terminal-3078246834-title" fill="#c5c8c6" text-anchor="middle" x="740" y="27">dsflow  ·  updated 03:20:21 (1.5s)</text>
|
||||
<g transform="translate(26,22)">
|
||||
<circle cx="0" cy="0" r="7" fill="#ff5f57"/>
|
||||
<circle cx="22" cy="0" r="7" fill="#febc2e"/>
|
||||
<circle cx="44" cy="0" r="7" fill="#28c840"/>
|
||||
</g>
|
||||
|
||||
<g transform="translate(9, 41)" clip-path="url(#terminal-3078246834-clip-terminal)">
|
||||
<rect fill="#414868" x="0" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="12.2" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="24.4" y="1.5" width="61" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="85.4" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="97.6" y="1.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="207.4" y="1.5" width="414.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="622.2" y="1.5" width="36.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="658.8" y="1.5" width="573.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#414868" x="1232.2" y="1.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1342" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1354.2" y="1.5" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#454c6c" x="1451.8" y="1.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="12.2" y="25.9" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="122" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="134.2" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="146.4" y="25.9" width="85.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="231.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="244" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="256.2" y="25.9" width="158.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="414.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="427" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="439.2" y="25.9" width="146.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="585.6" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="597.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="610" y="25.9" width="48.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="658.8" y="25.9" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="671" y="25.9" width="793" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="50.3" width="427" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="427" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="439.2" y="50.3" width="146.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="585.6" y="50.3" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="597.8" y="50.3" width="866.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="74.7" width="1464" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="24.4" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="36.6" y="99.1" width="256.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#7aa2f7" x="292.8" y="99.1" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="402.6" y="99.1" width="341.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="744.2" y="99.1" width="683.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1427.4" y="99.1" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1439.6" y="99.1" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="123.5" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="24.4" y="123.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="36.6" y="123.5" width="109.8" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="146.4" y="123.5" width="97.6" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="244" y="123.5" width="329.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="573.4" y="123.5" width="854" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1427.4" y="123.5" width="12.2" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="1439.6" y="123.5" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="0" y="147.9" width="24.4" height="24.65" shape-rendering="crispEdges"/><rect fill="#1a1b26" x="24.4" y="14Line truncated
|
||||
<g class="terminal-3078246834-matrix">
|
||||
<text class="terminal-3078246834-r2" x="12.2" y="20" textLength="12.2" clip-path="url(#terminal-3078246834-line-0)">◆</text><text class="terminal-3078246834-r2" x="207.4" y="20" textLength="414.8" clip-path="url(#terminal-3078246834-line-0)">dsflow  ·  updated 03:20:21 (1.5s)</text><text class="terminal-3078246834-r3" x="622.2" y="20" textLength="36.6" clip-path="url(#terminal-3078246834-line-0)"> — </text><text class="terminal-3078246834-r3" x="658.8" y="20" textLength="573.4" clip-path="url(#terminal-3078246834-line-0)">demo sandbox · Trunk:Latest · green tag working</text><text class="terminal-3078246834-r4" x="1354.2" y="20" textLength="97.6" clip-path="url(#terminal-3078246834-line-0)">03:20:24</text><text class="terminal-3078246834-r1" x="1464" y="20" textLength="12.2" clip-path="url(#terminal-3078246834-line-0)">
|
||||
</text><text class="terminal-3078246834-r5" x="12.2" y="44.4" textLength="109.8" clip-path="url(#terminal-3078246834-line-1)">Changes 5</text><text class="terminal-3078246834-r5" x="146.4" y="44.4" textLength="85.4" clip-path="url(#terminal-3078246834-line-1)">Locks 2</text><text class="terminal-3078246834-r5" x="256.2" y="44.4" textLength="158.6" clip-path="url(#terminal-3078246834-line-1)">Checked-out 3</text><text class="terminal-3078246834-r2" x="439.2" y="44.4" textLength="146.4" clip-path="url(#terminal-3078246834-line-1)">Sanity run ⟳</text><text class="terminal-3078246834-r5" x="610" y="44.4" textLength="48.8" clip-path="url(#terminal-3078246834-line-1)">Logs</text><text class="terminal-3078246834-r1" x="1464" y="44.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-1)">
|
||||
</text><text class="terminal-3078246834-r6" x="0" y="68.8" textLength="427" clip-path="url(#terminal-3078246834-line-2)">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</text><text class="terminal-3078246834-r6" x="427" y="68.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-2)">╸</text><text class="terminal-3078246834-r7" x="439.2" y="68.8" textLength="146.4" clip-path="url(#terminal-3078246834-line-2)">━━━━━━━━━━━━</text><text class="terminal-3078246834-r6" x="585.6" y="68.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-2)">╺</text><text class="terminal-3078246834-r6" x="597.8" y="68.8" textLength="866.2" clip-path="url(#terminal-3078246834-line-2)">━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━</text><text class="terminal-3078246834-r1" x="1464" y="68.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-2)">
|
||||
</text><text class="terminal-3078246834-r1" x="1464" y="93.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-3)">
|
||||
</text><text class="terminal-3078246834-r8" x="36.6" y="117.6" textLength="256.2" clip-path="url(#terminal-3078246834-line-4)">Run 20260924-032021  </text><text class="terminal-3078246834-r9" x="292.8" y="117.6" textLength="109.8" clip-path="url(#terminal-3078246834-line-4)"> RUNNING </text><text class="terminal-3078246834-r10" x="744.2" y="117.6" textLength="683.2" clip-path="url(#terminal-3078246834-line-4)">                           started 03:20:21 · elapsed 3s</text><text class="terminal-3078246834-r1" x="1464" y="117.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-4)">
|
||||
</text><text class="terminal-3078246834-r10" x="36.6" y="142" textLength="109.8" clip-path="url(#terminal-3078246834-line-5)">on pass  </text><text class="terminal-3078246834-r11" x="146.4" y="142" textLength="97.6" clip-path="url(#terminal-3078246834-line-5)">check in</text><text class="terminal-3078246834-r2" x="244" y="142" textLength="329.4" clip-path="url(#terminal-3078246834-line-5)">   “fix rx fsm corner case”</text><text class="terminal-3078246834-r1" x="1464" y="142" textLength="12.2" clip-path="url(#terminal-3078246834-line-5)">
|
||||
</text><text class="terminal-3078246834-r10" x="36.6" y="166.4" textLength="85.4" clip-path="url(#terminal-3078246834-line-6)">files  </text><text class="terminal-3078246834-r2" x="122" y="166.4" textLength="500.2" clip-path="url(#terminal-3078246834-line-6)">rtl/rx/rx_fsm.sv, rtl/top/wifi_mac_top.sv</text><text class="terminal-3078246834-r12" x="622.2" y="166.4" textLength="231.8" clip-path="url(#terminal-3078246834-line-6)">   locked by run: 1</text><text class="terminal-3078246834-r1" x="1464" y="166.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-6)">
|
||||
</text><text class="terminal-3078246834-r1" x="1464" y="190.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-7)">
|
||||
</text><text class="terminal-3078246834-r13" x="24.4" y="215.2" textLength="1415.2" clip-path="url(#terminal-3078246834-line-8)">────────────────────────────────────────────────────────────────────────────────────────────────────────────────────</text><text class="terminal-3078246834-r1" x="1464" y="215.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-8)">
|
||||
</text><text class="terminal-3078246834-r1" x="1464" y="239.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-9)">
|
||||
</text><text class="terminal-3078246834-r11" x="36.6" y="264" textLength="12.2" clip-path="url(#terminal-3078246834-line-10)">✔</text><text class="terminal-3078246834-r2" x="73.2" y="264" textLength="280.6" clip-path="url(#terminal-3078246834-line-10)">Check freshness & locks</text><text class="terminal-3078246834-r10" x="719.8" y="264" textLength="24.4" clip-path="url(#terminal-3078246834-line-10)">0s</text><text class="terminal-3078246834-r10" x="768.6" y="264" textLength="305" clip-path="url(#terminal-3078246834-line-10)">2 modified, 0 new        </text><text class="terminal-3078246834-r1" x="1464" y="264" textLength="12.2" clip-path="url(#terminal-3078246834-line-10)">
|
||||
</text><text class="terminal-3078246834-r11" x="36.6" y="288.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-11)">✔</text><text class="terminal-3078246834-r2" x="73.2" y="288.4" textLength="280.6" clip-path="url(#terminal-3078246834-line-11)">Lock 2 file(s)         </text><text class="terminal-3078246834-r10" x="719.8" y="288.4" textLength="24.4" clip-path="url(#terminal-3078246834-line-11)">0s</text><text class="terminal-3078246834-r10" x="768.6" y="288.4" textLength="305" clip-path="url(#terminal-3078246834-line-11)">1 locked, 1 already yours</text><text class="terminal-3078246834-r1" x="1464" y="288.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-11)">
|
||||
</text><text class="terminal-3078246834-r11" x="36.6" y="312.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-12)">✔</text><text class="terminal-3078246834-r2" x="73.2" y="312.8" textLength="280.6" clip-path="url(#terminal-3078246834-line-12)">Refresh to Trunk:Latest</text><text class="terminal-3078246834-r10" x="719.8" y="312.8" textLength="24.4" clip-path="url(#terminal-3078246834-line-12)">0s</text><text class="terminal-3078246834-r1" x="1464" y="312.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-12)">
|
||||
</text><text class="terminal-3078246834-r14" x="36.6" y="337.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-13)">⠸</text><text class="terminal-3078246834-r8" x="73.2" y="337.2" textLength="280.6" clip-path="url(#terminal-3078246834-line-13)">Sanity kibo_2x2        </text><text class="terminal-3078246834-r15" x="378.2" y="337.2" textLength="170.8" clip-path="url(#terminal-3078246834-line-13)">━━━━━━━━━━━━━━</text><text class="terminal-3078246834-r12" x="549" y="337.2" textLength="61" clip-path="url(#terminal-3078246834-line-13)">━━━━━</text><text class="terminal-3078246834-r15" x="610" y="337.2" textLength="85.4" clip-path="url(#terminal-3078246834-line-13)">━━━━━━━</text><text class="terminal-3078246834-r12" x="719.8" y="337.2" textLength="24.4" clip-path="url(#terminal-3078246834-line-13)">2s</text><text class="terminal-3078246834-r1" x="1464" y="337.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-13)">
|
||||
</text><text class="terminal-3078246834-r10" x="36.6" y="361.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-14)">·</text><text class="terminal-3078246834-r10" x="73.2" y="361.6" textLength="280.6" clip-path="url(#terminal-3078246834-line-14)">Sanity jaguar_1x1      </text><text class="terminal-3078246834-r1" x="1464" y="361.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-14)">
|
||||
</text><text class="terminal-3078246834-r10" x="36.6" y="386" textLength="12.2" clip-path="url(#terminal-3078246834-line-15)">·</text><text class="terminal-3078246834-r10" x="73.2" y="386" textLength="280.6" clip-path="url(#terminal-3078246834-line-15)">Verify files unchanged </text><text class="terminal-3078246834-r1" x="1464" y="386" textLength="12.2" clip-path="url(#terminal-3078246834-line-15)">
|
||||
</text><text class="terminal-3078246834-r10" x="36.6" y="410.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-16)">·</text><text class="terminal-3078246834-r10" x="73.2" y="410.4" textLength="280.6" clip-path="url(#terminal-3078246834-line-16)">Check in 2 file(s)     </text><text class="terminal-3078246834-r1" x="1464" y="410.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-16)">
|
||||
</text><text class="terminal-3078246834-r10" x="36.6" y="434.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-17)">·</text><text class="terminal-3078246834-r10" x="73.2" y="434.8" textLength="280.6" clip-path="url(#terminal-3078246834-line-17)">Release run locks      </text><text class="terminal-3078246834-r1" x="1464" y="434.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-17)">
|
||||
</text><text class="terminal-3078246834-r1" x="1464" y="459.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-18)">
|
||||
</text><text class="terminal-3078246834-r1" x="1464" y="483.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-19)">
|
||||
</text><text class="terminal-3078246834-r1" x="1464" y="508" textLength="12.2" clip-path="url(#terminal-3078246834-line-20)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="532.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-21)">╭</text><text class="terminal-3078246834-r16" x="36.6" y="532.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-21)">─</text><text class="terminal-3078246834-r17" x="48.8" y="532.4" textLength="329.4" clip-path="url(#terminal-3078246834-line-21)"> log · sanity_kibo_2x2.log </text><text class="terminal-3078246834-r16" x="378.2" y="532.4" textLength="1049.2" clip-path="url(#terminal-3078246834-line-21)">──────────────────────────────────────────────────────────────────────────────────────</text><text class="terminal-3078246834-r16" x="1427.4" y="532.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-21)">╮</text><text class="terminal-3078246834-r1" x="1464" y="532.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-21)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="556.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-22)">│</text><text class="terminal-3078246834-r2" x="36.6" y="556.8" textLength="756.4" clip-path="url(#terminal-3078246834-line-22)"># dsflow_tui sanity [kibo_2x2] 2026-09-24 03:20:21 by designer</text><text class="terminal-3078246834-r16" x="1427.4" y="556.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-22)">│</text><text class="terminal-3078246834-r1" x="1464" y="556.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-22)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="581.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-23)">│</text><text class="terminal-3078246834-r2" x="36.6" y="581.2" textLength="256.2" clip-path="url(#terminal-3078246834-line-23)"># run_sanity kibo_2x2</text><text class="terminal-3078246834-r16" x="1427.4" y="581.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-23)">│</text><text class="terminal-3078246834-r1" x="1464" y="581.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-23)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="605.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-24)">│</text><text class="terminal-3078246834-r2" x="36.6" y="605.6" textLength="366" clip-path="url(#terminal-3078246834-line-24)">=== sanity kibo_2x2 (demo) ===</text><text class="terminal-3078246834-r16" x="1427.4" y="605.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-24)">│</text><text class="terminal-3078246834-r1" x="1464" y="605.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-24)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="630" textLength="12.2" clip-path="url(#terminal-3078246834-line-25)">│</text><text class="terminal-3078246834-r18" x="36.6" y="630" textLength="439.2" clip-path="url(#terminal-3078246834-line-25)">[kibo_2x2] 03:20:22 test_01 ... PASS</text><text class="terminal-3078246834-r16" x="1427.4" y="630" textLength="12.2" clip-path="url(#terminal-3078246834-line-25)">│</text><text class="terminal-3078246834-r1" x="1464" y="630" textLength="12.2" clip-path="url(#terminal-3078246834-line-25)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="654.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-26)">│</text><text class="terminal-3078246834-r18" x="36.6" y="654.4" textLength="439.2" clip-path="url(#terminal-3078246834-line-26)">[kibo_2x2] 03:20:22 test_02 ... PASS</text><text class="terminal-3078246834-r16" x="1427.4" y="654.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-26)">│</text><text class="terminal-3078246834-r1" x="1464" y="654.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-26)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="678.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-27)">│</text><text class="terminal-3078246834-r18" x="36.6" y="678.8" textLength="439.2" clip-path="url(#terminal-3078246834-line-27)">[kibo_2x2] 03:20:23 test_03 ... PASS</text><text class="terminal-3078246834-r16" x="1427.4" y="678.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-27)">│</text><text class="terminal-3078246834-r1" x="1464" y="678.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-27)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="703.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-28)">│</text><text class="terminal-3078246834-r18" x="36.6" y="703.2" textLength="439.2" clip-path="url(#terminal-3078246834-line-28)">[kibo_2x2] 03:20:23 test_04 ... PASS</text><text class="terminal-3078246834-r16" x="1427.4" y="703.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-28)">│</text><text class="terminal-3078246834-r1" x="1464" y="703.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-28)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="727.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-29)">│</text><text class="terminal-3078246834-r16" x="1427.4" y="727.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-29)">│</text><text class="terminal-3078246834-r1" x="1464" y="727.6" textLength="12.2" clip-path="url(#terminal-3078246834-line-29)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="752" textLength="12.2" clip-path="url(#terminal-3078246834-line-30)">│</text><text class="terminal-3078246834-r16" x="1427.4" y="752" textLength="12.2" clip-path="url(#terminal-3078246834-line-30)">│</text><text class="terminal-3078246834-r1" x="1464" y="752" textLength="12.2" clip-path="url(#terminal-3078246834-line-30)">
|
||||
</text><text class="terminal-3078246834-r16" x="24.4" y="776.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-31)">╰</text><text class="terminal-3078246834-r16" x="36.6" y="776.4" textLength="1390.8" clip-path="url(#terminal-3078246834-line-31)">──────────────────────────────────────────────────────────────────────────────────────────────────────────────────</text><text class="terminal-3078246834-r16" x="1427.4" y="776.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-31)">╯</text><text class="terminal-3078246834-r1" x="1464" y="776.4" textLength="12.2" clip-path="url(#terminal-3078246834-line-31)">
|
||||
</text><text class="terminal-3078246834-r9" x="12.2" y="800.8" textLength="122" clip-path="url(#terminal-3078246834-line-32)"> ⠸ SANITY </text><text class="terminal-3078246834-r8" x="134.2" y="800.8" textLength="231.8" clip-path="url(#terminal-3078246834-line-32)">  Sanity kibo_2x2  </text><text class="terminal-3078246834-r15" x="366" y="800.8" textLength="24.4" clip-path="url(#terminal-3078246834-line-32)">━━</text><text class="terminal-3078246834-r12" x="390.4" y="800.8" textLength="61" clip-path="url(#terminal-3078246834-line-32)">━━━━━</text><text class="terminal-3078246834-r15" x="451.4" y="800.8" textLength="109.8" clip-path="url(#terminal-3078246834-line-32)">━━━━━━━━━</text><text class="terminal-3078246834-r12" x="561.2" y="800.8" textLength="109.8" clip-path="url(#terminal-3078246834-line-32)">  0/2 cfg</text><text class="terminal-3078246834-r10" x="671" y="800.8" textLength="85.4" clip-path="url(#terminal-3078246834-line-32)">  ·  3s</text><text class="terminal-3078246834-r10" x="756.4" y="800.8" textLength="244" clip-path="url(#terminal-3078246834-line-32)">  ·  1 locked by run</text><text class="terminal-3078246834-r12" x="1354.2" y="800.8" textLength="97.6" clip-path="url(#terminal-3078246834-line-32)">2 marked</text><text class="terminal-3078246834-r1" x="1464" y="800.8" textLength="12.2" clip-path="url(#terminal-3078246834-line-32)">
|
||||
</text><text class="terminal-3078246834-r19" x="0" y="825.2" textLength="36.6" clip-path="url(#terminal-3078246834-line-33)"> c </text><text class="terminal-3078246834-r2" x="36.6" y="825.2" textLength="109.8" clip-path="url(#terminal-3078246834-line-33)">Check in </text><text class="terminal-3078246834-r19" x="146.4" y="825.2" textLength="36.6" clip-path="url(#terminal-3078246834-line-33)"> x </text><text class="terminal-3078246834-r2" x="183" y="825.2" textLength="134.2" clip-path="url(#terminal-3078246834-line-33)">Cancel run </text><text class="terminal-3078246834-r19" x="317.2" y="825.2" textLength="36.6" clip-path="url(#terminal-3078246834-line-33)"> r </text><text class="terminal-3078246834-r2" x="353.8" y="825.2" textLength="97.6" clip-path="url(#terminal-3078246834-line-33)">Refresh </text><text class="terminal-3078246834-r19" x="451.4" y="825.2" textLength="36.6" clip-path="url(#terminal-3078246834-line-33)"> ? </text><text class="terminal-3078246834-r2" x="488" y="825.2" textLength="61" clip-path="url(#terminal-3078246834-line-33)">Help </text><text class="terminal-3078246834-r19" x="549" y="825.2" textLength="36.6" clip-path="url(#terminal-3078246834-line-33)"> q </text><text class="terminal-3078246834-r2" x="585.6" y="825.2" textLength="61" clip-path="url(#terminal-3078246834-line-33)">Quit </text><text class="terminal-3078246834-r20" x="1317.6" y="825.2" textLength="12.2" clip-path="url(#terminal-3078246834-line-33)">▏</text><text class="terminal-3078246834-r19" x="1329.8" y="825.2" textLength="24.4" clip-path="url(#terminal-3078246834-line-33)">^p</text><text class="terminal-3078246834-r2" x="1354.2" y="825.2" textLength="97.6" clip-path="url(#terminal-3078246834-line-33)"> palette</text>
|
||||
</g>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 56 KiB |
@@ -0,0 +1 @@
|
||||
"""dsflow_tui: a terminal UI for the dsflow DesignSync check-in flow."""
|
||||
@@ -0,0 +1,97 @@
|
||||
"""Command line: argument parsing, `status`, and dispatch to the UI or the runner."""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
from .common import JOB_FILE, ME, VERSION, FlowError, fmt_dur, job_state, read_json
|
||||
from .demo import setup_demo
|
||||
from .flow import Flow
|
||||
from .runner import Runner
|
||||
|
||||
|
||||
def cmd_status(flow, as_json):
|
||||
job = read_json(flow.path(JOB_FILE))
|
||||
if as_json:
|
||||
print(json.dumps(dict(state=job_state(job), job=job), indent=1, sort_keys=True))
|
||||
return 0 if job and job.get("status") in ("passed", "running", "queued") else 1
|
||||
if not job:
|
||||
print("no sanity run recorded in %s" % flow.ws)
|
||||
return 1
|
||||
st = job_state(job)
|
||||
label = "RUNNER LOST" if st == "orphaned" else job["status"].upper()
|
||||
start = job.get("started") or job["created"]
|
||||
print("run %s %s (%s, elapsed %s)" % (job["id"], label, job.get("host", "?"),
|
||||
fmt_dur((job.get("finished") or time.time()) - start)))
|
||||
print("mode: %s%s" % ("check in" if job["mode"] == "checkin" else "unlock only",
|
||||
", tag %s" % job["tag"] if job.get("tag") else ""))
|
||||
print("files: %s" % " ".join(job["files"] + job["new_files"]))
|
||||
if job.get("locked_by_job"):
|
||||
print("locked by run: %s" % " ".join(job["locked_by_job"]))
|
||||
for s in job["steps"]:
|
||||
mark = {"pending": ".", "running": ">", "done": "+", "failed": "x", "cancelled": "-", "skipped": "-"}[s["status"]]
|
||||
el = ((s.get("t1") or time.time()) - s["t0"]) if s.get("t0") else None
|
||||
print(" [%s] %-34s %-9s %s" % (mark, s["label"], fmt_dur(el), s.get("detail", "")))
|
||||
if job.get("summary"):
|
||||
print(job["summary"])
|
||||
return 0 if job["status"] in ("passed", "running", "queued") and st != "orphaned" else 1
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
ap = argparse.ArgumentParser(
|
||||
prog="dsflow_tui.py", description="Terminal UI for the dsflow DesignSync check-in flow.",
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
epilog="examples:\n"
|
||||
" dsflow_tui.py # from the workspace root\n"
|
||||
" dsflow_tui.py status # progress of the current sanity run\n"
|
||||
" dsflow_tui.py --sanity-cmd 'sim/regress.sh --cfg {cfg}'\n"
|
||||
" dsflow_tui.py --demo # sandbox with a fake dssc\n"
|
||||
" DEMO_FAIL=jaguar_1x1 dsflow_tui.py --demo # watch a failing run release its locks")
|
||||
ap.add_argument("command", nargs="?", default="tui", choices=("tui", "status", "_runjob"),
|
||||
help="tui (default) or status")
|
||||
ap.add_argument("--ws", default=os.getcwd(), help="workspace root (default: current directory)")
|
||||
ap.add_argument("--conf", help="dsflow.conf (default: $DSFLOW_CONF or <ws>/flow/dsflow.conf)")
|
||||
ap.add_argument("--sanity-cmd", help="external sanity command; {cfg} and {ws} are substituted "
|
||||
"(default: SANITY_SCRIPT from dsflow.conf, else run_sanity)")
|
||||
ap.add_argument("--tags", help="comma-separated tags offered for batch tagging (default: DSFLOW_TAGS)")
|
||||
ap.add_argument("--auto-refresh", type=int, default=0, metavar="SEC",
|
||||
help="re-query DesignSync every SEC seconds (default: only on r / after actions)")
|
||||
ap.add_argument("--json", action="store_true", help="status: print JSON")
|
||||
ap.add_argument("--theme", default="tokyo-night",
|
||||
help="colour theme (default tokyo-night; ctrl+p in the app lists the others)")
|
||||
ap.add_argument("--demo", action="store_true", help="run against a sandbox workspace with a fake dssc")
|
||||
ap.add_argument("--demo-dir", default=os.path.join(tempfile.gettempdir(), "dsflow_tui_demo-" + ME))
|
||||
ap.add_argument("--demo-reset", action="store_true", help="rebuild the demo sandbox from scratch")
|
||||
ap.add_argument("--version", action="version", version="dsflow_tui " + VERSION)
|
||||
args = ap.parse_args(argv)
|
||||
|
||||
if args.demo:
|
||||
args.ws, args.conf = setup_demo(args.demo_dir, args.demo_reset)
|
||||
conf = args.conf or os.environ.get("DSFLOW_CONF") or os.path.join(args.ws, "flow", "dsflow.conf")
|
||||
tags = [t for t in (args.tags or "").replace(",", " ").split() if t] or None
|
||||
try:
|
||||
flow = Flow(args.ws, conf, args.sanity_cmd, tags)
|
||||
flow.load_vars()
|
||||
except FlowError as e:
|
||||
print("dsflow_tui: %s" % e, file=sys.stderr)
|
||||
return 2
|
||||
if args.command == "_runjob":
|
||||
return Runner(flow).main()
|
||||
if args.command == "status":
|
||||
return cmd_status(flow, args.json)
|
||||
if not sys.stdout.isatty():
|
||||
print("dsflow_tui: the TUI needs a terminal (use `status` for scripts)", file=sys.stderr)
|
||||
return 2
|
||||
if sys.version_info < (3, 8, 1):
|
||||
print("dsflow_tui: the TUI needs Python >= 3.8.1 (this is %s); `status` still works"
|
||||
% sys.version.split()[0], file=sys.stderr)
|
||||
return 2
|
||||
from .ui.app import DsflowApp # imported late: status and the runner don't need Textual
|
||||
DsflowApp(flow, auto_refresh=args.auto_refresh, theme=args.theme).run()
|
||||
job = read_json(flow.path(JOB_FILE))
|
||||
if job_state(job) == "active":
|
||||
print("dsflow_tui: sanity run %s is still going in the background." % job["id"])
|
||||
print(" follow it with: %s status (or reopen the TUI)" % os.path.basename(sys.argv[0]))
|
||||
return 0
|
||||
@@ -0,0 +1,131 @@
|
||||
"""Constants and small helpers shared by the runner, the CLI and the UI."""
|
||||
import getpass
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import signal
|
||||
import time
|
||||
|
||||
VERSION = "2.0"
|
||||
# the launcher the runner is re-executed through (it sets up vendor/ on sys.path)
|
||||
ENTRY = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "dsflow_tui.py")
|
||||
ME = os.environ.get("USER") or getpass.getuser()
|
||||
|
||||
JOB_FILE = "tui_job.json" # state of the current/last sanity run
|
||||
JOB_LOCK = "tui_job.lock" # flock held by the runner while it lives
|
||||
JOB_CANCEL = "tui_job.cancel" # touch to ask the runner to stop
|
||||
RUNNER_LOG = "tui_runner.log" # what the runner did, step by step
|
||||
RUNNER_OUT = "tui_runner.out" # runner stdout/stderr (crash traces)
|
||||
HISTORY = "tui_history.json" # last passing duration per config
|
||||
TERMINAL = ("passed", "failed", "cancelled", "error")
|
||||
HEARTBEAT_STALE = 60 # s without a runner heartbeat => runner gone
|
||||
|
||||
|
||||
class FlowError(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class StepFailed(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class Cancelled(Exception):
|
||||
pass
|
||||
|
||||
|
||||
def read_json(path, default=None):
|
||||
try:
|
||||
with open(path) as fh:
|
||||
return json.load(fh)
|
||||
except (OSError, ValueError):
|
||||
return default
|
||||
|
||||
|
||||
def write_json(path, data):
|
||||
tmp = "%s.%d.tmp" % (path, os.getpid())
|
||||
with open(tmp, "w") as fh:
|
||||
json.dump(data, fh, indent=1, sort_keys=True)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def sha1_file(path):
|
||||
h = hashlib.sha1()
|
||||
try:
|
||||
with open(path, "rb") as fh:
|
||||
for chunk in iter(lambda: fh.read(1 << 20), b""):
|
||||
h.update(chunk)
|
||||
except OSError:
|
||||
return None
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
def norm(path):
|
||||
path = path.strip()
|
||||
while path.startswith("./"):
|
||||
path = path[2:]
|
||||
return path
|
||||
|
||||
|
||||
def fmt_dur(sec):
|
||||
if sec is None:
|
||||
return ""
|
||||
sec = int(max(0, sec))
|
||||
if sec < 60:
|
||||
return "%ds" % sec
|
||||
if sec < 3600:
|
||||
return "%dm%02ds" % (sec // 60, sec % 60)
|
||||
return "%dh%02dm" % (sec // 3600, sec % 3600 // 60)
|
||||
|
||||
|
||||
def fmt_ago(epoch):
|
||||
return "%s ago" % fmt_dur(time.time() - epoch) if epoch else "never"
|
||||
|
||||
|
||||
def fmt_clock(epoch):
|
||||
return time.strftime("%H:%M:%S", time.localtime(epoch)) if epoch else "--:--:--"
|
||||
|
||||
|
||||
def last_line(text):
|
||||
lines = [l for l in (text or "").strip().splitlines() if l.strip()]
|
||||
return lines[-1].strip() if lines else ""
|
||||
|
||||
|
||||
def tail_lines(path, max_bytes=256 * 1024):
|
||||
try:
|
||||
with open(path, "rb") as fh:
|
||||
fh.seek(0, os.SEEK_END)
|
||||
size = fh.tell()
|
||||
fh.seek(max(0, size - max_bytes))
|
||||
data = fh.read()
|
||||
except OSError:
|
||||
return None
|
||||
lines = data.decode("utf-8", "replace").replace("\r", "").expandtabs(4).split("\n")
|
||||
if size > max_bytes:
|
||||
lines = lines[1:]
|
||||
if lines and lines[-1] == "":
|
||||
lines.pop()
|
||||
return lines
|
||||
|
||||
|
||||
def job_state(job):
|
||||
"""none | active | orphaned | done"""
|
||||
if not job:
|
||||
return "none"
|
||||
if job.get("status") in TERMINAL:
|
||||
return "done"
|
||||
if time.time() - job.get("heartbeat", job.get("created", 0)) > HEARTBEAT_STALE:
|
||||
return "orphaned"
|
||||
return "active"
|
||||
|
||||
|
||||
def kill_group(p, grace=10):
|
||||
for sig, wait in ((signal.SIGTERM, grace), (signal.SIGKILL, 5)):
|
||||
try:
|
||||
os.killpg(p.pid, sig)
|
||||
except OSError:
|
||||
return
|
||||
t_end = time.time() + wait
|
||||
while time.time() < t_end:
|
||||
if p.poll() is not None:
|
||||
return
|
||||
time.sleep(0.2)
|
||||
+254
@@ -0,0 +1,254 @@
|
||||
"""--demo: a sandbox workspace driven by a fake dssc, so every action can be tried without a vault."""
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
|
||||
from .common import ME, sha1_file
|
||||
|
||||
FAKE_DSSC = r'''#!/usr/bin/env python3
|
||||
"""Fake dssc for the dsflow_tui demo. Vault state lives in $DSSC_FAKE_VAULT."""
|
||||
import hashlib, json, os, sys, time, getpass
|
||||
VAULT = os.environ["DSSC_FAKE_VAULT"]
|
||||
ROOT = os.path.dirname(os.path.realpath(VAULT))
|
||||
ME = os.environ.get("USER") or getpass.getuser()
|
||||
time.sleep(0.03)
|
||||
|
||||
def load():
|
||||
with open(VAULT) as fh:
|
||||
return json.load(fh)
|
||||
def save(v):
|
||||
with open(VAULT + ".tmp", "w") as fh:
|
||||
json.dump(v, fh, indent=1)
|
||||
os.replace(VAULT + ".tmp", VAULT)
|
||||
def ab(f): return os.path.join(ROOT, f)
|
||||
def sha(f):
|
||||
try:
|
||||
with open(ab(f), "rb") as fh:
|
||||
return hashlib.sha1(fh.read()).hexdigest()
|
||||
except OSError:
|
||||
return None
|
||||
def modified(v, f): return sha(f) != v["files"][f]["hash"]
|
||||
def bump(ver):
|
||||
a, b = ver.rsplit(".", 1)
|
||||
return "%s.%d" % (a, int(b) + 1)
|
||||
def die(msg):
|
||||
sys.stderr.write("dssc: %s\n" % msg)
|
||||
sys.exit(1)
|
||||
def parse(argv, valued):
|
||||
flags, vals, pos, i = set(), {}, [], 0
|
||||
while i < len(argv):
|
||||
a = argv[i]
|
||||
if a.startswith("-") and len(a) > 1:
|
||||
if a in valued:
|
||||
vals[a] = argv[i + 1]
|
||||
i += 2
|
||||
continue
|
||||
flags.add(a)
|
||||
else:
|
||||
pos.append(a)
|
||||
i += 1
|
||||
return flags, vals, pos
|
||||
def targets(v, pos):
|
||||
out = []
|
||||
for p in pos or ["."]:
|
||||
r = os.path.relpath(os.path.realpath(p), ROOT)
|
||||
if r == ".":
|
||||
out += sorted(v["files"])
|
||||
elif r in v["files"]:
|
||||
out.append(r)
|
||||
else:
|
||||
out += [f for f in sorted(v["files"]) if f.startswith(r.rstrip("/") + "/")]
|
||||
return out
|
||||
def fetch(v, f, ver, note):
|
||||
e, mode = v["files"][f], os.stat(ab(f)).st_mode & 0o777
|
||||
os.chmod(ab(f), 0o644)
|
||||
with open(ab(f), "a") as fh:
|
||||
fh.write("// %s %s\n" % (note, ver))
|
||||
os.chmod(ab(f), mode)
|
||||
e["base"] = ver
|
||||
|
||||
cmd, argv = sys.argv[1], sys.argv[2:]
|
||||
v = load()
|
||||
if cmd == "ls":
|
||||
fl, vals, pos = parse(argv, {"-report"})
|
||||
rep = vals.get("-report", "N")
|
||||
for f in targets(v, pos):
|
||||
e = v["files"][f]
|
||||
if "-modified" in fl and not modified(v, f):
|
||||
continue
|
||||
print({"N": f, "V": e["base"], "L": e["locker"]}.get(rep, f))
|
||||
elif cmd == "vhistory":
|
||||
fl, vals, pos = parse(argv, {"-max", "-branch"})
|
||||
for f in targets(v, pos):
|
||||
e = v["files"][f]
|
||||
print("%s %s 2026-09-22 17:04 %s" % (e["latest"], e.get("author", "bob"), "Trunk"))
|
||||
elif cmd in ("co", "lock"):
|
||||
fl, vals, pos = parse(argv, {"-version", "-comment"})
|
||||
for f in targets(v, pos):
|
||||
e = v["files"][f]
|
||||
if e["locker"] and e["locker"] != ME:
|
||||
die("%s is locked by %s" % (f, e["locker"]))
|
||||
if cmd == "lock" or "-lock" in fl:
|
||||
e["locker"] = ME
|
||||
if cmd == "co":
|
||||
if not modified(v, f) and e["base"] != e["latest"]:
|
||||
fetch(v, f, e["latest"], "fetched")
|
||||
e["hash"] = sha(f)
|
||||
os.chmod(ab(f), 0o644)
|
||||
print("%s : Success - %s" % (f, "locked" if e["locker"] == ME else "checked out"))
|
||||
save(v)
|
||||
elif cmd == "unlock":
|
||||
fl, vals, pos = parse(argv, set())
|
||||
for f in targets(v, pos):
|
||||
e = v["files"][f]
|
||||
if e["locker"] and e["locker"] != ME:
|
||||
die("%s is locked by %s" % (f, e["locker"]))
|
||||
e["locker"] = ""
|
||||
print("%s : Success - unlocked" % f)
|
||||
save(v)
|
||||
elif cmd == "ci":
|
||||
fl, vals, pos = parse(argv, {"-comment"})
|
||||
if "-new" in fl:
|
||||
for p in pos:
|
||||
f = os.path.relpath(os.path.realpath(p), ROOT)
|
||||
if f in v["files"]:
|
||||
die("%s is already managed" % f)
|
||||
v["files"][f] = dict(base="1.1", latest="1.1", hash=sha(f), locker="", tags={}, author=ME)
|
||||
os.chmod(ab(f), 0o444)
|
||||
print("%s : Success - new version 1.1" % f)
|
||||
else:
|
||||
for f in targets(v, pos):
|
||||
e = v["files"][f]
|
||||
if e["locker"] and e["locker"] != ME:
|
||||
die("%s is locked by %s" % (f, e["locker"]))
|
||||
if e["base"] != e["latest"]:
|
||||
die("%s: not based on Latest (%s vs %s) - merge first" % (f, e["base"], e["latest"]))
|
||||
if not modified(v, f):
|
||||
print("%s : unchanged, skipped" % f)
|
||||
continue
|
||||
new = bump(e["latest"])
|
||||
e.update(base=new, latest=new, hash=sha(f), locker="", author=ME)
|
||||
os.chmod(ab(f), 0o444)
|
||||
print("%s : Success - checked in %s" % (f, new))
|
||||
save(v)
|
||||
elif cmd == "tag":
|
||||
fl, vals, pos = parse(argv, set())
|
||||
tag = pos[0]
|
||||
for f in targets(v, pos[1:]):
|
||||
e = v["files"][f]
|
||||
e["tags"][tag] = e["base"]
|
||||
print("%s;%s : Success - tagged %s" % (f, e["base"], tag))
|
||||
save(v)
|
||||
elif cmd in ("pop", "populate"):
|
||||
fl, vals, pos = parse(argv, {"-version"})
|
||||
for f in targets(v, pos):
|
||||
e = v["files"][f]
|
||||
if e["base"] == e["latest"]:
|
||||
continue
|
||||
if "-merge" in fl:
|
||||
fetch(v, f, e["latest"], "merged with")
|
||||
print("%s : merged %s" % (f, e["latest"]))
|
||||
elif not modified(v, f):
|
||||
fetch(v, f, e["latest"], "fetched")
|
||||
e["hash"] = sha(f)
|
||||
print("%s : fetched %s" % (f, e["latest"]))
|
||||
save(v)
|
||||
else:
|
||||
die("fake dssc: unsupported command '%s'" % cmd)
|
||||
'''
|
||||
|
||||
DEMO_CONF = r'''# dsflow.conf for the dsflow_tui demo sandbox (fake dssc on PATH)
|
||||
TRUNK_SEL="Trunk:Latest"
|
||||
WORKING_TAG="working"
|
||||
SANITY_CONFIGS="kibo_2x2 jaguar_1x1"
|
||||
CI_EXTRA_CONFIGS=""
|
||||
MAX_STAMP_AGE=$((4*3600))
|
||||
HOT_FILES="${WS_ROOT:-.}/flow/hot_files.txt"
|
||||
CHECKIN_LOG="@SHARE@/dsflow_checkins.log"
|
||||
CI_STATE="@SHARE@/ci_state"
|
||||
CI_NOTIFY="[email protected]"
|
||||
DSFLOW_TAGS="wmac_working wmac_rx_drop"
|
||||
|
||||
# Fake regression: DEMO_FAIL="jaguar_1x1" makes that config fail.
|
||||
run_sanity() {
|
||||
local n=${DEMO_SANITY_TESTS:-12} i
|
||||
echo "=== sanity $1 (demo) ==="
|
||||
for ((i=1; i<=n; i++)); do
|
||||
sleep "${DEMO_STEP_SECS:-1.5}"
|
||||
echo "[$1] $(date +%T) test_$(printf %02d $i) ... PASS"
|
||||
done
|
||||
if [[ " ${DEMO_FAIL:-} " == *" $1 "* ]]; then
|
||||
echo "[$1] ERROR: scoreboard mismatch in rx path"; return 1
|
||||
fi
|
||||
echo "[$1] all $n tests passed"
|
||||
}
|
||||
|
||||
ds_list_modified() { dssc ls -rec -modified -report N . 2>/dev/null | awk 'NF'; }
|
||||
ds_base_version() { dssc ls -report V "$1" 2>/dev/null | awk 'NF{v=$NF} END{print v}'; }
|
||||
ds_latest_version() { dssc vhistory -max 1 -branch Trunk "$1" 2>/dev/null | awk '/^[0-9.]+/{print $1; exit}'; }
|
||||
ds_lock_holder() { dssc ls -report L "$1" 2>/dev/null | awk 'NF{u=$NF} END{print u}'; }
|
||||
ds_unlock() { dssc unlock "$@"; }
|
||||
'''
|
||||
|
||||
|
||||
def setup_demo(base, reset):
|
||||
base = os.path.realpath(base) # macOS: /var -> /private/var would skew relative paths
|
||||
ws, bindir, share = os.path.join(base, "ws"), os.path.join(base, "bin"), os.path.join(base, "share")
|
||||
vault = os.path.join(ws, ".fakevault.json")
|
||||
if reset and os.path.isdir(base):
|
||||
for root, dirs, files in os.walk(base):
|
||||
for n in dirs + files:
|
||||
try:
|
||||
os.chmod(os.path.join(root, n), 0o755)
|
||||
except OSError:
|
||||
pass
|
||||
shutil.rmtree(base)
|
||||
if not os.path.exists(vault):
|
||||
for d in (ws, bindir, share, os.path.join(ws, "flow")):
|
||||
if not os.path.isdir(d):
|
||||
os.makedirs(d)
|
||||
with open(os.path.join(bindir, "dssc"), "w") as fh:
|
||||
fh.write(FAKE_DSSC)
|
||||
os.chmod(os.path.join(bindir, "dssc"), 0o755)
|
||||
with open(os.path.join(ws, "flow", "dsflow.conf"), "w") as fh:
|
||||
fh.write(DEMO_CONF.replace("@SHARE@", share))
|
||||
with open(os.path.join(ws, "flow", "hot_files.txt"), "w") as fh:
|
||||
fh.write("# One workspace-relative path per line. Locked on edit.\n"
|
||||
"rtl/top/wifi_mac_top.sv\nrtl/pkg/wifi_mac_pkg.sv\nrtl/regs/mac_regs.sv\n")
|
||||
# path: (base, latest, locker, state) - state: ro | co (writable) | mod (edited)
|
||||
layout = {
|
||||
"rtl/top/wifi_mac_top.sv": ("1.12", "1.12", ME, "mod"),
|
||||
"rtl/pkg/wifi_mac_pkg.sv": ("1.31", "1.31", "", "ro"),
|
||||
"rtl/regs/mac_regs.sv": ("1.9", "1.9", "alice", "ro"),
|
||||
"rtl/rx/rx_fsm.sv": ("1.4", "1.4", "", "mod"),
|
||||
"rtl/rx/rx_buf.sv": ("1.6", "1.6", "", "ro"),
|
||||
"rtl/tx/tx_ctrl.sv": ("1.7", "1.8", "", "mod"),
|
||||
"rtl/tx/tx_crc.sv": ("1.3", "1.3", "", "co"),
|
||||
"rtl/tx/tx_fifo.sv": ("1.2", "1.2", "", "mod"),
|
||||
"sim/tb/tb_top.sv": ("1.20", "1.20", "", "ro"),
|
||||
}
|
||||
files = {}
|
||||
for rel, (b, l, locker, state) in sorted(layout.items()):
|
||||
p = os.path.join(ws, rel)
|
||||
if not os.path.isdir(os.path.dirname(p)):
|
||||
os.makedirs(os.path.dirname(p))
|
||||
mod = os.path.splitext(os.path.basename(rel))[0]
|
||||
with open(p, "w") as fh:
|
||||
fh.write("// %s - version %s\nmodule %s;\nendmodule\n" % (rel, b, mod))
|
||||
files[rel] = dict(base=b, latest=l, hash=sha1_file(p), locker=locker, tags={}, author="bob")
|
||||
if state == "mod":
|
||||
with open(p, "a") as fh:
|
||||
fh.write("// local edit by %s\n" % ME)
|
||||
os.chmod(p, 0o444 if state == "ro" else 0o644)
|
||||
with open(vault, "w") as fh:
|
||||
json.dump(dict(files=files), fh, indent=1)
|
||||
newf = os.path.join(ws, "rtl/rx/rx_agg.sv")
|
||||
with open(newf, "w") as fh:
|
||||
fh.write("module rx_agg;\nendmodule\n")
|
||||
if not os.path.isdir(os.path.join(ws, ".dsflow")):
|
||||
os.makedirs(os.path.join(ws, ".dsflow"))
|
||||
with open(os.path.join(ws, ".dsflow", "new_files"), "w") as fh:
|
||||
fh.write("rtl/rx/rx_agg.sv\n")
|
||||
os.environ["PATH"] = bindir + os.pathsep + os.environ.get("PATH", "")
|
||||
os.environ["DSSC_FAKE_VAULT"] = vault
|
||||
return ws, os.path.join(ws, "flow", "dsflow.conf")
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
"""Flow: the workspace plus every call into dsflow.conf.
|
||||
|
||||
All DesignSync access goes through the ds_* helpers in dsflow.conf, like the
|
||||
bash flow. Helpers the TUI needs that dsflow.conf does not define get the
|
||||
defaults in BASH_DEFAULTS; verify them against your dssc version and
|
||||
override any of them in dsflow.conf.
|
||||
"""
|
||||
import hashlib
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from .common import FlowError, ME, kill_group, last_line, norm, sha1_file
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# bash side. Everything below is appended after `source dsflow.conf`, and only
|
||||
# defines a helper when dsflow.conf did not. VERIFY against your dssc version.
|
||||
# ---------------------------------------------------------------------------
|
||||
BASH_DEFAULTS = r'''
|
||||
command -v sha1sum >/dev/null 2>&1 || sha1sum() { shasum -a 1 "$@"; }
|
||||
_dsflow_has() { [ -n "$(type -t "$1" 2>/dev/null)" ]; }
|
||||
|
||||
# Every managed file in the workspace, one workspace-relative path per line.
|
||||
_dsflow_has ds_list_managed || ds_list_managed() { dssc ls -rec -report N . 2>/dev/null | awk 'NF'; }
|
||||
|
||||
# "path<TAB>lock-holder" for every writable managed file. DesignSync fetches
|
||||
# read-only copies unless a file is checked out, so writable == checked out.
|
||||
_dsflow_has ds_list_writable || ds_list_writable() {
|
||||
local f
|
||||
ds_list_managed | while IFS= read -r f; do
|
||||
[[ -f $f && -w $f && ! -L $f ]] || continue
|
||||
printf '%s\t%s\n' "$f" "$(ds_lock_holder "$f")"
|
||||
done
|
||||
}
|
||||
|
||||
# Take the vault lock WITHOUT touching the local copy (it may hold edits).
|
||||
_dsflow_has ds_lock || ds_lock() { dssc lock "$@"; }
|
||||
_dsflow_has ds_unlock || ds_unlock() { dssc unlock "$@"; }
|
||||
_dsflow_has ds_checkin || ds_checkin() { local m=$1; shift; dssc ci -comment "$m" "$@"; }
|
||||
_dsflow_has ds_checkin_new || ds_checkin_new() { local m=$1; shift; dssc ci -new -comment "$m" "$@"; }
|
||||
_dsflow_has ds_tag || ds_tag() { local t=$1; shift; dssc tag -replace "$t" "$@"; }
|
||||
_dsflow_has ds_refresh || ds_refresh() { dssc pop -rec -version "$TRUNK_SEL" .; }
|
||||
_dsflow_has ds_rebase || ds_rebase() { local f; for f; do dssc pop -merge -version "$TRUNK_SEL" "$f"; done; }
|
||||
'''
|
||||
|
||||
CONF_VARS = ("TRUNK_SEL", "WORKING_TAG", "SANITY_CONFIGS", "MAX_STAMP_AGE",
|
||||
"HOT_FILES", "CHECKIN_LOG", "DSFLOW_TAGS", "SANITY_SCRIPT")
|
||||
|
||||
SNAPSHOT_SH = r'''
|
||||
ds_list_modified | sort -u | while IFS= read -r f; do
|
||||
[[ -n $f ]] || continue
|
||||
printf 'M\t%s\t%s\t%s\t%s\n' "$f" "$(ds_base_version "$f")" "$(ds_latest_version "$f")" "$(ds_lock_holder "$f")"
|
||||
done
|
||||
ds_list_writable | while IFS=$'\t' read -r f h; do
|
||||
[[ -n $f ]] && printf 'W\t%s\t%s\n' "$f" "$h"
|
||||
done
|
||||
if [[ -f $HOT_FILES ]]; then
|
||||
grep -v '^[[:space:]]*#' "$HOT_FILES" | awk 'NF{print $1}' | while IFS= read -r f; do
|
||||
printf 'H\t%s\t%s\n' "$f" "$(ds_lock_holder "$f")"
|
||||
done
|
||||
fi
|
||||
'''
|
||||
|
||||
VERSIONS_SH = r'''for f; do printf '%s\t%s\t%s\n' "$f" "$(ds_base_version "$f")" "$(ds_latest_version "$f")"; done'''
|
||||
HOLDERS_SH = r'''for f; do printf '%s\t%s\n' "$f" "$(ds_lock_holder "$f")"; done'''
|
||||
# Same list as all_changes() in dsflow, so the stamp we write is one dsflow accepts.
|
||||
ALL_CHANGES_SH = r'''{ ds_list_modified; cat "$WS_ROOT/.dsflow/new_files" 2>/dev/null; } | awk 'NF' | sort -u'''
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Flow: the workspace plus every call into dsflow.conf
|
||||
# ---------------------------------------------------------------------------
|
||||
class Flow(object):
|
||||
def __init__(self, ws, conf, sanity_cmd=None, tags=None):
|
||||
self.ws = os.path.abspath(ws)
|
||||
self.conf = os.path.abspath(conf)
|
||||
self.sdir = os.path.join(self.ws, ".dsflow")
|
||||
self.cli_sanity_cmd = sanity_cmd
|
||||
self.cli_tags = tags
|
||||
self.vars = {}
|
||||
if not os.path.isfile(self.conf):
|
||||
raise FlowError("config not found: %s\n(run from the workspace root, or pass --conf / set DSFLOW_CONF)" % self.conf)
|
||||
if not os.path.isdir(self.sdir):
|
||||
os.makedirs(self.sdir)
|
||||
if not os.path.exists(self.path("new_files")):
|
||||
open(self.path("new_files"), "a").close()
|
||||
|
||||
def path(self, name):
|
||||
return os.path.join(self.sdir, name)
|
||||
|
||||
def wpath(self, rel):
|
||||
return os.path.join(self.ws, rel)
|
||||
|
||||
# -- bash plumbing ------------------------------------------------------
|
||||
def argv(self, snippet, args=()):
|
||||
script = 'export WS_ROOT=%s\ncd "$WS_ROOT" || exit 97\nsource %s || exit 98\n%s\n%s\n' % (
|
||||
shlex.quote(self.ws), shlex.quote(self.conf), BASH_DEFAULTS, snippet)
|
||||
return ["bash", "-c", script, "dsflow-tui"] + [str(a) for a in args]
|
||||
|
||||
def env(self, extra=None):
|
||||
env = dict(os.environ)
|
||||
env["DSFLOW_CONF"] = self.conf
|
||||
env["WS_ROOT"] = self.ws
|
||||
env.update(extra or {})
|
||||
return env
|
||||
|
||||
def run(self, snippet, args=(), timeout=900):
|
||||
p = subprocess.Popen(self.argv(snippet, args), stdin=subprocess.DEVNULL,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=self.ws,
|
||||
env=self.env(), start_new_session=True,
|
||||
universal_newlines=True, encoding="utf-8", errors="replace")
|
||||
try:
|
||||
out, err = p.communicate(timeout=timeout)
|
||||
except subprocess.TimeoutExpired:
|
||||
kill_group(p)
|
||||
out, err = p.communicate()
|
||||
return 124, out, err + "\n(timed out after %ds)" % timeout
|
||||
return p.returncode, out, err
|
||||
|
||||
def act(self, fn, *args, **kw):
|
||||
"""Run one ds_* helper; returns (rc, combined output)."""
|
||||
rc, out, err = self.run('%s "$@"' % fn, args, timeout=kw.get("timeout", 1800))
|
||||
return rc, (out + err).strip()
|
||||
|
||||
# -- configuration --------------------------------------------------------
|
||||
def load_vars(self):
|
||||
snippet = 'for v in %s; do printf "%%s=%%s\\0" "$v" "${!v-}"; done' % " ".join(CONF_VARS)
|
||||
rc, out, err = self.run(snippet, timeout=60)
|
||||
if rc != 0:
|
||||
raise FlowError("cannot source %s:\n%s" % (self.conf, err.strip()))
|
||||
for item in out.split("\0"):
|
||||
if "=" in item:
|
||||
k, v = item.split("=", 1)
|
||||
self.vars[k] = v
|
||||
|
||||
@property
|
||||
def trunk(self):
|
||||
return self.vars.get("TRUNK_SEL") or "Trunk:Latest"
|
||||
|
||||
@property
|
||||
def working_tag(self):
|
||||
return self.vars.get("WORKING_TAG") or "working"
|
||||
|
||||
@property
|
||||
def configs(self):
|
||||
return self.vars.get("SANITY_CONFIGS", "").split()
|
||||
|
||||
@property
|
||||
def max_age(self):
|
||||
try:
|
||||
return int(self.vars.get("MAX_STAMP_AGE") or 4 * 3600)
|
||||
except ValueError:
|
||||
return 4 * 3600
|
||||
|
||||
@property
|
||||
def tags(self):
|
||||
tags = self.cli_tags or self.vars.get("DSFLOW_TAGS", "").split() or ["wmac_working"]
|
||||
# the working tag belongs to CI: moving it by hand defeats the green gate
|
||||
return [t for t in tags if t != self.working_tag]
|
||||
|
||||
@property
|
||||
def sanity_cmd(self):
|
||||
return self.cli_sanity_cmd or self.vars.get("SANITY_SCRIPT") or ""
|
||||
|
||||
# -- local state shared with bash dsflow ------------------------------------
|
||||
def hot_files(self):
|
||||
out = []
|
||||
try:
|
||||
with open(self.vars.get("HOT_FILES") or self.wpath("flow/hot_files.txt")) as fh:
|
||||
for line in fh:
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
out.append(norm(line.split()[0]))
|
||||
except OSError:
|
||||
pass
|
||||
return out
|
||||
|
||||
def new_files(self):
|
||||
try:
|
||||
with open(self.path("new_files")) as fh:
|
||||
return sorted(set(norm(l) for l in fh if l.strip()))
|
||||
except OSError:
|
||||
return []
|
||||
|
||||
def _write_new(self, paths):
|
||||
with open(self.path("new_files"), "w") as fh:
|
||||
for p in sorted(set(paths)):
|
||||
fh.write(p + "\n")
|
||||
|
||||
def add_new(self, paths):
|
||||
self._write_new(self.new_files() + [norm(p) for p in paths])
|
||||
self.drop_stamp()
|
||||
|
||||
def remove_new(self, paths):
|
||||
gone = set(paths)
|
||||
self._write_new([p for p in self.new_files() if p not in gone])
|
||||
|
||||
def drop_stamp(self):
|
||||
try:
|
||||
os.remove(self.path("sanity.stamp"))
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
# -- queries --------------------------------------------------------------
|
||||
def snapshot(self):
|
||||
t0 = time.time()
|
||||
snap = Snapshot()
|
||||
rc, out, err = self.run(SNAPSHOT_SH, timeout=1800)
|
||||
if rc != 0 and not out.strip():
|
||||
snap.err = last_line(err) or "dssc query failed (rc=%d)" % rc
|
||||
mods, writable, hot_holder = {}, {}, {}
|
||||
for line in out.splitlines():
|
||||
p = line.split("\t")
|
||||
if p[0] == "M" and len(p) >= 5:
|
||||
mods[norm(p[1])] = (p[2].strip(), p[3].strip(), p[4].strip())
|
||||
elif p[0] == "W" and len(p) >= 3:
|
||||
writable[norm(p[1])] = p[2].strip()
|
||||
elif p[0] == "H" and len(p) >= 3:
|
||||
hot_holder[norm(p[1])] = p[2].strip()
|
||||
hot = set(self.hot_files())
|
||||
|
||||
for path in sorted(mods):
|
||||
base, latest, holder = mods[path]
|
||||
snap.changes.append(dict(
|
||||
path=path, kind="M", base=base, latest=latest, holder=holder,
|
||||
stale=bool(base and latest and base != latest), unknown=not (base and latest),
|
||||
hot=path in hot, exists=True))
|
||||
for path in self.new_files():
|
||||
if path not in mods:
|
||||
snap.changes.append(dict(
|
||||
path=path, kind="A", base="", latest="", holder="", stale=False,
|
||||
unknown=False, hot=path in hot, exists=os.path.exists(self.wpath(path))))
|
||||
|
||||
holders = {}
|
||||
for src in (hot_holder, writable, dict((p, v[2]) for p, v in mods.items())):
|
||||
for p, h in src.items():
|
||||
if h:
|
||||
holders[p] = h
|
||||
for p in sorted(set(holders) | hot):
|
||||
h = holders.get(p, hot_holder.get(p, ""))
|
||||
snap.locks.append(dict(path=p, holder=h, hot=p in hot, modified=p in mods))
|
||||
snap.locks.sort(key=lambda r: (0 if r["holder"] == ME else 1 if r["holder"] else 2, r["path"]))
|
||||
|
||||
for p in sorted(writable):
|
||||
if not writable[p]:
|
||||
snap.checkout.append(dict(path=p, holder="", hot=p in hot, modified=p in mods))
|
||||
snap.took = time.time() - t0
|
||||
return snap
|
||||
|
||||
def versions(self, files):
|
||||
if not files:
|
||||
return {}
|
||||
rc, out, err = self.run(VERSIONS_SH, files)
|
||||
res = {}
|
||||
for line in out.splitlines():
|
||||
p = line.split("\t")
|
||||
if len(p) >= 3:
|
||||
res[norm(p[0])] = (p[1].strip(), p[2].strip())
|
||||
return res
|
||||
|
||||
def stale_of(self, files):
|
||||
return dict((f, v) for f, v in self.versions(files).items() if v[0] and v[1] and v[0] != v[1])
|
||||
|
||||
def holders(self, files):
|
||||
if not files:
|
||||
return {}
|
||||
rc, out, err = self.run(HOLDERS_SH, files)
|
||||
res = {}
|
||||
for line in out.splitlines():
|
||||
p = line.split("\t")
|
||||
if p and p[0]:
|
||||
res[norm(p[0])] = p[1].strip() if len(p) > 1 else ""
|
||||
return res
|
||||
|
||||
def content_hash(self, files):
|
||||
"""sha1 of `sha1sum files... | sha1sum`, i.e. dsflow's content_hash."""
|
||||
if not files:
|
||||
return "none"
|
||||
text = "".join("%s %s\n" % (sha1_file(self.wpath(f)) or "0" * 40, f) for f in files)
|
||||
return hashlib.sha1(text.encode("utf-8")).hexdigest()
|
||||
|
||||
# -- actions --------------------------------------------------------------
|
||||
def checkin(self, msg, mods, news, log):
|
||||
"""Check in modified + new files the way `dsflow checkin` does."""
|
||||
for fn, files in (("ds_checkin", mods), ("ds_checkin_new", news)):
|
||||
if not files:
|
||||
continue
|
||||
rc, out = self.act(fn, msg, *files, timeout=3600)
|
||||
for line in out.splitlines():
|
||||
log(" " + line)
|
||||
if rc != 0:
|
||||
return False, "check-in failed (%s): %s" % (fn, last_line(out) or "rc=%d" % rc)
|
||||
self.remove_new(news)
|
||||
self.drop_stamp()
|
||||
files = list(mods) + list(news)
|
||||
logpath = self.vars.get("CHECKIN_LOG")
|
||||
if logpath:
|
||||
try:
|
||||
with open(logpath, "a") as fh:
|
||||
fh.write("%s\t%s\t%s\t%s\n" % (time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), ME,
|
||||
self.content_hash(files), " ".join(files)))
|
||||
except OSError as e:
|
||||
log(" warning: could not append to %s: %s" % (logpath, e))
|
||||
return True, "checked in %d file(s)" % len(files)
|
||||
|
||||
def write_bash_stamp(self, files, configs):
|
||||
"""Write .dsflow/sanity.stamp only if this run covered exactly what dsflow would check in."""
|
||||
if list(configs) != self.configs:
|
||||
return False
|
||||
rc, out, err = self.run(ALL_CHANGES_SH)
|
||||
allc = [norm(l) for l in out.splitlines() if l.strip()]
|
||||
if rc != 0 or set(allc) != set(files):
|
||||
return False
|
||||
with open(self.path("sanity.stamp"), "w") as fh:
|
||||
fh.write("stamp_hash=%s\nstamp_epoch=%d\nstamp_when=%s\nstamp_configs=\"%s\"\n" % (
|
||||
self.content_hash(allc), int(time.time()),
|
||||
time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), " ".join(configs)))
|
||||
return True
|
||||
|
||||
|
||||
class Snapshot(object):
|
||||
def __init__(self):
|
||||
self.changes, self.locks, self.checkout = [], [], []
|
||||
self.err = None
|
||||
self.ts = time.time()
|
||||
self.took = 0.0
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
"""The rules behind each UI action, kept free of Textual so they can be tested directly.
|
||||
|
||||
Every function takes plain rows from a Snapshot and returns data or
|
||||
(ok, message); the UI decides how to show it.
|
||||
"""
|
||||
import os
|
||||
import signal
|
||||
import socket
|
||||
import time
|
||||
|
||||
from .common import JOB_CANCEL, JOB_FILE, ME, fmt_dur, last_line, sha1_file, write_json
|
||||
|
||||
|
||||
def sanity_blockers(rows):
|
||||
"""Reasons the marked changes can't go into a sanity run (empty list = fine)."""
|
||||
out = []
|
||||
for r in rows:
|
||||
if r["stale"]:
|
||||
out.append("%s: %s -> %s on Trunk - rebase first (m)" % (r["path"], r["base"], r["latest"]))
|
||||
if r["holder"] and r["holder"] != ME:
|
||||
out.append("%s: locked by %s" % (r["path"], r["holder"]))
|
||||
if not r["exists"]:
|
||||
out.append("%s: registered as new but missing on disk" % r["path"])
|
||||
return out
|
||||
|
||||
|
||||
def split_kinds(rows):
|
||||
"""(modified paths, new paths) of Changes rows."""
|
||||
return ([r["path"] for r in rows if r.get("kind") == "M"],
|
||||
[r["path"] for r in rows if r.get("kind") == "A"])
|
||||
|
||||
|
||||
def sanity_form_error(values, all_configs):
|
||||
"""Validation for the Run sanity dialog; None when the values are usable."""
|
||||
if not values["configs"]:
|
||||
return "pick at least one config"
|
||||
if values["mode"] == "checkin":
|
||||
if not values["msg"].strip():
|
||||
return "a check-in comment is required"
|
||||
if list(values["configs"]) != list(all_configs):
|
||||
return "check-in needs every config (%s)" % " ".join(all_configs)
|
||||
elif values["tag"]:
|
||||
return "tagging needs 'check in' (tagging now would tag the old vault versions)"
|
||||
return None
|
||||
|
||||
|
||||
def stamp_problems(flow, job, rows):
|
||||
"""Why the last run does not cover these files as they are now (empty list = ok)."""
|
||||
if not job or job.get("status") != "passed" or not job.get("sanity_ok"):
|
||||
return ["no passing sanity run on record"]
|
||||
probs = []
|
||||
if list(job["configs"]) != flow.configs:
|
||||
probs.append("last run covered %s, check-in needs %s" % (" ".join(job["configs"]), " ".join(flow.configs)))
|
||||
age = time.time() - job.get("sanity_epoch", 0)
|
||||
if age > flow.max_age:
|
||||
probs.append("last pass is %s old (limit %s)" % (fmt_dur(age), fmt_dur(flow.max_age)))
|
||||
for r in rows:
|
||||
h = job.get("hashes", {}).get(r["path"])
|
||||
if h is None:
|
||||
probs.append("%s was not part of the last run" % r["path"])
|
||||
elif sha1_file(flow.wpath(r["path"])) != h:
|
||||
probs.append("%s changed since the last run" % r["path"])
|
||||
return probs
|
||||
|
||||
|
||||
def checkin_now(flow, job, rows, msg, tag, log):
|
||||
"""Check in files a passing run covers, re-checking freshness and contents first."""
|
||||
mods, news = split_kinds(rows)
|
||||
stale = flow.stale_of(mods)
|
||||
if stale:
|
||||
return False, "went stale on Trunk: %s - rebase first" % ", ".join(sorted(stale))
|
||||
probs = stamp_problems(flow, job, rows)
|
||||
if probs:
|
||||
return False, probs[0]
|
||||
ok, text = flow.checkin(msg, mods, news, log)
|
||||
if ok and tag:
|
||||
rc, out = flow.act("ds_tag", tag, *(mods + news))
|
||||
ok = rc == 0
|
||||
text += " and tagged %s" % tag if ok else "; tagging failed: %s" % last_line(out)
|
||||
return ok, text
|
||||
|
||||
|
||||
def run_action(flow, fn, paths, label, log, lead=()):
|
||||
"""One batch ds_* call (lock, unlock, tag, rebase) with its output logged; `lead` args go first (the tag)."""
|
||||
rc, out = flow.act(fn, *(list(lead) + list(paths)))
|
||||
for line in out.splitlines():
|
||||
log(" " + line)
|
||||
if rc == 0:
|
||||
return True, "%s %d file(s): done" % (label, len(paths))
|
||||
return False, "%s failed: %s" % (label, last_line(out) or "rc=%d" % rc)
|
||||
|
||||
|
||||
def request_cancel(flow):
|
||||
"""Ask the runner to stop; it kills sanity and releases its locks itself."""
|
||||
with open(flow.path(JOB_CANCEL), "w") as fh:
|
||||
fh.write(ME)
|
||||
|
||||
|
||||
def release_orphan(flow, job):
|
||||
"""Clean up after a runner that stopped heart-beating: stop its sanity, release its locks."""
|
||||
if job.get("child_pid") and job.get("host") == socket.gethostname():
|
||||
try:
|
||||
os.killpg(job["child_pid"], signal.SIGTERM)
|
||||
except OSError:
|
||||
pass
|
||||
locked = job.get("locked_by_job", [])
|
||||
holders = flow.holders(locked)
|
||||
mine = [f for f in locked if holders.get(f) == ME]
|
||||
rc, out = flow.act("ds_unlock", *mine) if mine else (0, "")
|
||||
for s in job["steps"]:
|
||||
if s["status"] == "running":
|
||||
s.update(status="failed", t1=time.time(), detail="runner lost")
|
||||
elif s["status"] == "pending":
|
||||
s["status"] = "skipped"
|
||||
if s["key"] == "unlock" and rc == 0:
|
||||
s.update(status="done", detail="%d released from the TUI" % len(mine))
|
||||
job.update(status="error", finished=time.time(), phase="finished",
|
||||
summary="runner lost; %d lock(s) released from the TUI" % len(mine))
|
||||
write_json(flow.path(JOB_FILE), job)
|
||||
return rc == 0, job["summary"] if rc == 0 else "unlock failed: %s" % last_line(out)
|
||||
@@ -0,0 +1,351 @@
|
||||
"""Runner: the detached process that owns one sanity run, and the helpers that start it."""
|
||||
import fcntl
|
||||
import os
|
||||
import shlex
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import traceback
|
||||
|
||||
from .common import (ENTRY, HISTORY, JOB_CANCEL, JOB_FILE, JOB_LOCK, ME, RUNNER_LOG, RUNNER_OUT, Cancelled,
|
||||
StepFailed, fmt_dur, kill_group, last_line, read_json, sha1_file, write_json)
|
||||
|
||||
class Runner(object):
|
||||
def __init__(self, flow):
|
||||
self.flow = flow
|
||||
self.jp = flow.path(JOB_FILE)
|
||||
self.lk = threading.RLock()
|
||||
self.job = None
|
||||
self.child = None
|
||||
self.stop = False
|
||||
self.done = False
|
||||
|
||||
def log(self, msg):
|
||||
line = "%s %s" % (time.strftime("%H:%M:%S"), msg)
|
||||
with open(self.flow.path(RUNNER_LOG), "a") as fh:
|
||||
fh.write(line + "\n")
|
||||
|
||||
def save(self):
|
||||
with self.lk:
|
||||
self.job["heartbeat"] = time.time()
|
||||
write_json(self.jp, self.job)
|
||||
|
||||
def step(self, key):
|
||||
for s in self.job["steps"]:
|
||||
if s["key"] == key:
|
||||
return s
|
||||
return {}
|
||||
|
||||
def begin(self, key, detail=""):
|
||||
with self.lk:
|
||||
s = self.step(key)
|
||||
s.update(status="running", t0=time.time(), detail=detail)
|
||||
self.job["phase"] = key
|
||||
self.log(">> %s" % s.get("label", key))
|
||||
self.save()
|
||||
|
||||
def end(self, key, status="done", detail=None):
|
||||
with self.lk:
|
||||
s = self.step(key)
|
||||
s.update(status=status, t1=time.time())
|
||||
if detail is not None:
|
||||
s["detail"] = detail
|
||||
self.log("<< %s: %s%s" % (s.get("label", key), status, " (%s)" % detail if detail else ""))
|
||||
self.save()
|
||||
|
||||
def fail(self, key, detail):
|
||||
self.end(key, "failed", detail)
|
||||
raise StepFailed(detail)
|
||||
|
||||
def cancelled(self):
|
||||
return self.stop or os.path.exists(self.flow.path(JOB_CANCEL))
|
||||
|
||||
def check_cancel(self):
|
||||
if self.cancelled():
|
||||
raise Cancelled()
|
||||
|
||||
def cmd(self, fn, *args, **kw):
|
||||
self.log(" $ %s %s" % (fn, " ".join(shlex.quote(a) for a in args)))
|
||||
rc, out = self.flow.act(fn, *args, **kw)
|
||||
for line in out.splitlines():
|
||||
self.log(" " + line)
|
||||
return rc, out
|
||||
|
||||
def _signal(self, signum, frame):
|
||||
self.stop = True
|
||||
if self.child is not None:
|
||||
try:
|
||||
os.killpg(self.child.pid, signal.SIGTERM)
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def _heartbeat(self):
|
||||
while not self.done:
|
||||
time.sleep(5)
|
||||
if not self.done:
|
||||
try:
|
||||
self.save()
|
||||
except OSError:
|
||||
pass
|
||||
|
||||
def main(self):
|
||||
lockfh = open(self.flow.path(JOB_LOCK), "a")
|
||||
try:
|
||||
fcntl.flock(lockfh, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except OSError:
|
||||
print("dsflow_tui: another sanity runner is active in this workspace")
|
||||
return 1
|
||||
self.job = read_json(self.jp)
|
||||
if not self.job or self.job.get("status") != "queued":
|
||||
print("dsflow_tui: no queued job in %s" % self.jp)
|
||||
return 1
|
||||
for sig in (signal.SIGTERM, signal.SIGINT, signal.SIGHUP):
|
||||
signal.signal(sig, self._signal)
|
||||
open(self.flow.path(RUNNER_LOG), "w").close()
|
||||
self.job.update(status="running", pid=os.getpid(), host=socket.gethostname(), started=time.time())
|
||||
self.log("run %s by %s on %s" % (self.job["id"], ME, socket.gethostname()))
|
||||
self.save()
|
||||
threading.Thread(target=self._heartbeat, daemon=True).start()
|
||||
|
||||
# The terminal status is saved last: readers treat it as "locks are settled".
|
||||
final = "error"
|
||||
try:
|
||||
self.execute()
|
||||
final = "passed"
|
||||
except Cancelled:
|
||||
final, self.job["summary"] = "cancelled", "cancelled by user"
|
||||
except StepFailed as e:
|
||||
final, self.job["summary"] = "failed", str(e)
|
||||
except Exception as e: # noqa - the runner must always release locks
|
||||
self.job["summary"] = "runner error: %s" % e
|
||||
self.log(traceback.format_exc())
|
||||
finally:
|
||||
with self.lk:
|
||||
for s in self.job["steps"]:
|
||||
if s["status"] == "running":
|
||||
s.update(status="cancelled" if final == "cancelled" else "failed", t1=time.time())
|
||||
self.release_locks()
|
||||
with self.lk:
|
||||
for s in self.job["steps"]:
|
||||
if s["status"] == "pending":
|
||||
s["status"] = "skipped"
|
||||
self.job["finished"] = time.time()
|
||||
self.job["phase"] = "finished"
|
||||
self.job["status"] = final
|
||||
self.done = True
|
||||
self.log("finished: %s - %s" % (final, self.job.get("summary", "")))
|
||||
self.save()
|
||||
try:
|
||||
os.remove(self.flow.path(JOB_CANCEL))
|
||||
except OSError:
|
||||
pass
|
||||
return 0 if final == "passed" else 1
|
||||
|
||||
def execute(self):
|
||||
j, flow = self.job, self.flow
|
||||
mods, news = j["files"], j["new_files"]
|
||||
|
||||
self.begin("validate")
|
||||
missing = [f for f in news if not os.path.exists(flow.wpath(f))]
|
||||
if missing:
|
||||
self.fail("validate", "new file(s) missing: %s" % ", ".join(missing))
|
||||
if mods:
|
||||
stale = flow.stale_of(mods)
|
||||
if stale:
|
||||
self.fail("validate", "checked in by someone else since you started (dsflow rebase): %s" %
|
||||
", ".join("%s %s->%s" % (f, v[0], v[1]) for f, v in sorted(stale.items())))
|
||||
holders = flow.holders(mods)
|
||||
others = dict((f, h) for f, h in holders.items() if h and h != ME)
|
||||
if others:
|
||||
self.fail("validate", "locked by others: %s" % ", ".join("%s (%s)" % i for i in sorted(others.items())))
|
||||
j["preheld"] = sorted(f for f, h in holders.items() if h == ME)
|
||||
self.end("validate", detail="%d modified, %d new" % (len(mods), len(news)))
|
||||
|
||||
if mods:
|
||||
self.begin("lock")
|
||||
for f in mods:
|
||||
self.check_cancel()
|
||||
if f in j["preheld"]:
|
||||
continue
|
||||
rc, out = self.cmd("ds_lock", f)
|
||||
if rc != 0:
|
||||
self.fail("lock", "could not lock %s: %s" % (f, last_line(out) or "rc=%d" % rc))
|
||||
with self.lk:
|
||||
j["locked_by_job"].append(f)
|
||||
self.save()
|
||||
self.end("lock", detail="%d locked, %d already yours" % (len(j["locked_by_job"]), len(j["preheld"])))
|
||||
|
||||
if j.get("refresh"):
|
||||
self.check_cancel()
|
||||
self.begin("refresh")
|
||||
rc, out = self.cmd("ds_refresh", timeout=7200)
|
||||
if rc != 0:
|
||||
self.fail("refresh", "refresh to %s failed: %s" % (flow.trunk, last_line(out)))
|
||||
self.end("refresh")
|
||||
|
||||
j["hashes"] = dict((f, sha1_file(flow.wpath(f))) for f in mods + news)
|
||||
self.save()
|
||||
|
||||
hist = read_json(flow.path(HISTORY), {})
|
||||
for cfg in j["configs"]:
|
||||
self.check_cancel()
|
||||
key = "sanity:" + cfg
|
||||
logp = flow.path("sanity_%s.log" % cfg)
|
||||
self.step(key)["log"] = logp
|
||||
self.begin(key)
|
||||
rc = self.run_sanity(cfg, logp)
|
||||
if rc is None:
|
||||
raise Cancelled()
|
||||
if rc != 0:
|
||||
self.fail(key, "sanity FAILED for %s (exit %d) - see %s" % (cfg, rc, os.path.relpath(logp, flow.ws)))
|
||||
dur = time.time() - self.step(key)["t0"]
|
||||
hist[cfg] = dur
|
||||
write_json(flow.path(HISTORY), hist)
|
||||
self.end(key, detail="passed in %s" % fmt_dur(dur))
|
||||
j["sanity_ok"] = True
|
||||
j["sanity_epoch"] = time.time()
|
||||
self.save()
|
||||
try:
|
||||
if flow.write_bash_stamp(mods + news, j["configs"]):
|
||||
self.log("wrote .dsflow/sanity.stamp - `dsflow checkin` will accept this run too")
|
||||
except OSError as e:
|
||||
self.log("could not write sanity.stamp: %s" % e)
|
||||
|
||||
if j["mode"] != "checkin":
|
||||
j["summary"] = "sanity passed on %s - locks released; check in within %s (key c)" % (
|
||||
" ".join(j["configs"]), fmt_dur(flow.max_age))
|
||||
return
|
||||
|
||||
self.begin("verify")
|
||||
changed = [f for f in mods + news if sha1_file(flow.wpath(f)) != j["hashes"].get(f)]
|
||||
if changed:
|
||||
self.fail("verify", "edited while sanity ran, NOT checked in: %s" % ", ".join(changed))
|
||||
stale = flow.stale_of(mods)
|
||||
if stale:
|
||||
self.fail("verify", "went stale on Trunk during the run, NOT checked in: %s" % ", ".join(sorted(stale)))
|
||||
self.end("verify")
|
||||
|
||||
self.begin("checkin")
|
||||
ok, msg = flow.checkin(j["msg"], mods, news, self.log)
|
||||
if not ok:
|
||||
self.fail("checkin", msg)
|
||||
self.end("checkin", detail=msg)
|
||||
j["checked_in"] = True
|
||||
|
||||
if j.get("tag"):
|
||||
self.begin("tag")
|
||||
rc, out = self.cmd("ds_tag", j["tag"], *(mods + news))
|
||||
if rc != 0:
|
||||
self.fail("tag", "checked in, but tagging '%s' failed: %s" % (j["tag"], last_line(out)))
|
||||
self.end("tag", detail="%d file(s)" % len(mods + news))
|
||||
j["summary"] = "sanity passed on %s - checked in %d file(s)%s" % (
|
||||
" ".join(j["configs"]), len(mods + news), " and tagged %s" % j["tag"] if j.get("tag") else "")
|
||||
|
||||
def run_sanity(self, cfg, logp):
|
||||
"""Returns the exit code, or None if the run was cancelled."""
|
||||
flow, cmd = self.flow, self.job.get("sanity_cmd")
|
||||
if cmd:
|
||||
snippet, args = 'eval "$1"', [cmd.replace("{cfg}", shlex.quote(cfg)).replace("{ws}", shlex.quote(flow.ws))]
|
||||
else:
|
||||
snippet, args = 'run_sanity "$1"', [cfg]
|
||||
with open(logp, "w") as fh:
|
||||
fh.write("# dsflow_tui sanity [%s] %s by %s\n# %s\n" % (
|
||||
cfg, time.strftime("%Y-%m-%d %H:%M:%S"), ME, args[0] if cmd else "run_sanity %s" % cfg))
|
||||
self.log(" sanity [%s] -> %s" % (cfg, logp))
|
||||
with open(logp, "ab") as out:
|
||||
self.child = subprocess.Popen(flow.argv(snippet, args), stdin=subprocess.DEVNULL, stdout=out,
|
||||
stderr=subprocess.STDOUT, cwd=flow.ws,
|
||||
env=flow.env({"DSFLOW_CFG": cfg}), start_new_session=True)
|
||||
with self.lk:
|
||||
self.job["child_pid"] = self.child.pid # lets the TUI stop it if this runner dies
|
||||
self.save()
|
||||
try:
|
||||
while True:
|
||||
rc = self.child.poll()
|
||||
if rc is not None:
|
||||
return rc
|
||||
if self.cancelled():
|
||||
self.log(" cancelling sanity [%s]" % cfg)
|
||||
kill_group(self.child)
|
||||
return None
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
self.child = None
|
||||
with self.lk:
|
||||
self.job.pop("child_pid", None)
|
||||
|
||||
def release_locks(self):
|
||||
j = self.job
|
||||
mine = []
|
||||
if j.get("locked_by_job"):
|
||||
self.begin("unlock")
|
||||
holders = self.flow.holders(j["locked_by_job"])
|
||||
mine = [f for f in j["locked_by_job"] if holders.get(f) == ME]
|
||||
if mine:
|
||||
rc, out = self.cmd("ds_unlock", *mine)
|
||||
if rc != 0:
|
||||
j["summary"] = "%s | WARNING: could not release locks on %s: %s" % (
|
||||
j.get("summary", ""), ", ".join(mine), last_line(out))
|
||||
self.end("unlock", "failed", "release by hand: dsflow release %s" % " ".join(mine))
|
||||
return
|
||||
j["released"] = mine
|
||||
self.end("unlock", detail="%d released" % len(mine) if mine else "already released by check-in")
|
||||
else:
|
||||
with self.lk:
|
||||
s = self.step("unlock")
|
||||
s.update(status="skipped", detail="run took no locks")
|
||||
|
||||
|
||||
def new_job(flow, mods, news, configs, mode, msg, tag, refresh):
|
||||
hist = read_json(flow.path(HISTORY), {})
|
||||
steps = [dict(key="validate", label="Check freshness & locks")]
|
||||
if mods:
|
||||
steps.append(dict(key="lock", label="Lock %d file(s)" % len(mods)))
|
||||
if refresh:
|
||||
steps.append(dict(key="refresh", label="Refresh to %s" % flow.trunk))
|
||||
for cfg in configs:
|
||||
steps.append(dict(key="sanity:" + cfg, label="Sanity %s" % cfg, kind="sanity", est=hist.get(cfg)))
|
||||
if mode == "checkin":
|
||||
steps.append(dict(key="verify", label="Verify files unchanged"))
|
||||
steps.append(dict(key="checkin", label="Check in %d file(s)" % (len(mods) + len(news))))
|
||||
if tag:
|
||||
steps.append(dict(key="tag", label="Tag %s" % tag))
|
||||
steps.append(dict(key="unlock", label="Release run locks"))
|
||||
for s in steps:
|
||||
s.setdefault("kind", "action")
|
||||
s.update(status="pending", detail="", t0=None, t1=None)
|
||||
now = time.time()
|
||||
return dict(id=time.strftime("%Y%m%d-%H%M%S"), user=ME, host=socket.gethostname(), created=now,
|
||||
heartbeat=now, status="queued", phase="queued", mode=mode, msg=msg, tag=tag,
|
||||
refresh=refresh, files=mods, new_files=news, configs=configs,
|
||||
sanity_cmd=flow.sanity_cmd, locked_by_job=[], preheld=[], hashes={}, steps=steps,
|
||||
summary="")
|
||||
|
||||
|
||||
def spawn_runner(flow, job):
|
||||
try:
|
||||
os.remove(flow.path(JOB_CANCEL))
|
||||
except OSError:
|
||||
pass
|
||||
write_json(flow.path(JOB_FILE), job)
|
||||
argv = [sys.executable, ENTRY, "--ws", flow.ws, "--conf", flow.conf]
|
||||
if flow.cli_sanity_cmd:
|
||||
argv += ["--sanity-cmd", flow.cli_sanity_cmd]
|
||||
argv.append("_runjob")
|
||||
with open(flow.path(RUNNER_OUT), "ab") as out:
|
||||
subprocess.Popen(argv, stdin=subprocess.DEVNULL, stdout=out, stderr=subprocess.STDOUT,
|
||||
cwd=flow.ws, env=flow.env(), start_new_session=True, close_fds=True)
|
||||
|
||||
|
||||
def runner_alive(flow):
|
||||
"""True if some process holds the runner flock (same host / working NFS locks)."""
|
||||
try:
|
||||
with open(flow.path(JOB_LOCK), "a") as fh:
|
||||
fcntl.flock(fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
fcntl.flock(fh, fcntl.LOCK_UN)
|
||||
return False
|
||||
except OSError:
|
||||
return True
|
||||
@@ -0,0 +1 @@
|
||||
"""Textual front end; only imported when the TUI runs, so status and the runner never need it."""
|
||||
@@ -0,0 +1,545 @@
|
||||
"""The Textual application: layout, key bindings, polling the job file, and the actions behind each key."""
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
|
||||
from textual import work
|
||||
from textual.app import App
|
||||
from textual.binding import Binding
|
||||
from textual.screen import ModalScreen
|
||||
from textual.widgets import Footer, Header, Input, Static, TabbedContent, TabPane
|
||||
|
||||
from .. import ops
|
||||
from ..common import JOB_FILE, ME, RUNNER_LOG, VERSION, fmt_ago, job_state, norm, read_json
|
||||
from ..flow import Snapshot
|
||||
from ..runner import new_job, runner_alive, spawn_runner
|
||||
from .dialogs import (AddFilesDialog, CheckinDialog, ConfirmDialog, HelpDialog, MessageDialog, SanityDialog,
|
||||
TagDialog, file_notes)
|
||||
from .widgets import DetailPane, FilePane, FileTable, LogPanel, RunPanel, run_bar
|
||||
|
||||
FILE_TABS = ("changes", "locks", "checkout")
|
||||
TAB_LABELS = {"changes": "Changes", "locks": "Locks", "checkout": "Checked-out", "sanity": "Sanity run",
|
||||
"logs": "Logs"}
|
||||
# which file actions make sense on which tab; everything else is global
|
||||
TAB_ACTIONS = {
|
||||
"changes": {"toggle_mark", "mark_all", "sanity", "checkin", "tag", "add_new", "rebase", "filter"},
|
||||
"locks": {"toggle_mark", "mark_all", "lock", "unlock", "tag", "filter"},
|
||||
"checkout": {"toggle_mark", "mark_all", "lock", "tag", "filter"},
|
||||
"sanity": {"checkin"},
|
||||
"logs": set(),
|
||||
}
|
||||
FILE_ACTIONS = set().union(*TAB_ACTIONS.values())
|
||||
|
||||
|
||||
class DsflowApp(App):
|
||||
"""dsflow_tui's main screen."""
|
||||
|
||||
CSS_PATH = "styles.tcss"
|
||||
TITLE = "dsflow"
|
||||
ENABLE_COMMAND_PALETTE = True
|
||||
AUTO_FOCUS = "#table-changes" # never the hidden filter input
|
||||
BINDINGS = [
|
||||
Binding("space", "toggle_mark", "Mark"),
|
||||
Binding("s", "sanity", "Sanity"),
|
||||
Binding("c", "checkin", "Check in"),
|
||||
Binding("t", "tag", "Tag"),
|
||||
Binding("l", "lock", "Lock"),
|
||||
Binding("u", "unlock", "Unlock"),
|
||||
Binding("x", "cancel_run", "Cancel run"),
|
||||
Binding("slash", "filter", "Filter"),
|
||||
Binding("r", "refresh", "Refresh"),
|
||||
Binding("question_mark", "help", "Help"),
|
||||
Binding("q", "quit", "Quit"),
|
||||
Binding("a", "mark_all", "Mark all", show=False),
|
||||
Binding("n", "add_new", "Add new", show=False),
|
||||
Binding("m", "rebase", "Rebase", show=False),
|
||||
Binding("escape", "clear", "Clear", show=False),
|
||||
] + [Binding(str(i + 1), "show_tab('%s')" % tab, TAB_LABELS[tab], show=False)
|
||||
for i, tab in enumerate(("changes", "locks", "checkout", "sanity", "logs"))]
|
||||
|
||||
def __init__(self, flow, auto_refresh=0, theme="tokyo-night"):
|
||||
super().__init__()
|
||||
self.flow = flow
|
||||
self.refresh_every = auto_refresh # not `auto_refresh`: that name is Textual's repaint interval
|
||||
self.start_theme = theme
|
||||
self.snap = None
|
||||
self.marks = set()
|
||||
self.text_filter = ""
|
||||
self.job, self.jstate, self.jmtime, self.locks_seen = None, "none", None, None
|
||||
self.activity = []
|
||||
self.busy = None
|
||||
self.refreshing = False
|
||||
self.last_refresh = 0.0
|
||||
self.last_msg = ""
|
||||
|
||||
# -- layout ---------------------------------------------------------------
|
||||
def compose(self):
|
||||
yield Header(show_clock=True, icon="◆")
|
||||
yield Input(placeholder="filter by path… (esc to close)", id="filter")
|
||||
with TabbedContent(id="tabs", initial="changes"):
|
||||
for tab in FILE_TABS:
|
||||
with TabPane(TAB_LABELS[tab], id=tab):
|
||||
yield FilePane(tab)
|
||||
with TabPane(TAB_LABELS["sanity"], id="sanity"):
|
||||
yield RunPanel()
|
||||
with TabPane(TAB_LABELS["logs"], id="logs"):
|
||||
yield LogPanel(self.log_sources, self.activity)
|
||||
yield Static(id="runbar")
|
||||
yield Footer()
|
||||
|
||||
def on_mount(self):
|
||||
# direct references: events that arrive during teardown must not need a DOM query
|
||||
self.tabs = self.query_one("#tabs", TabbedContent)
|
||||
self.tables = dict((t, self.query_one("#table-" + t, FileTable)) for t in FILE_TABS)
|
||||
self.details = dict((t, self.query_one("#detail-" + t, DetailPane)) for t in FILE_TABS)
|
||||
self.runbar = self.query_one("#runbar", Static)
|
||||
self.run_panel = self.query_one(RunPanel)
|
||||
self.log_panel = self.query_one(LogPanel)
|
||||
try:
|
||||
self.theme = self.start_theme
|
||||
except Exception: # noqa - an unknown --theme name just keeps the default
|
||||
self.notify("unknown theme %r" % self.start_theme, severity="warning")
|
||||
home = os.path.expanduser("~")
|
||||
ws = "~" + self.flow.ws[len(home):] if self.flow.ws.startswith(home) else self.flow.ws
|
||||
self.sub_title = "%s · %s · %s · green tag %s" % (ws, ME, self.flow.trunk, self.flow.working_tag)
|
||||
for tab in FILE_TABS:
|
||||
self.table(tab).loading = True
|
||||
self.refresh_snapshot()
|
||||
self.poll()
|
||||
self.set_interval(0.25, self.poll)
|
||||
|
||||
# -- helpers --------------------------------------------------------------
|
||||
def table(self, tab):
|
||||
return self.tables[tab]
|
||||
|
||||
def tab(self):
|
||||
return self.tabs.active
|
||||
|
||||
def log_sources(self):
|
||||
cfgs = (self.job or {}).get("configs") or self.flow.configs
|
||||
return ([("activity", None)] + [(c, self.flow.path("sanity_%s.log" % c)) for c in cfgs]
|
||||
+ [("runner", self.flow.path(RUNNER_LOG))])
|
||||
|
||||
def run_files(self):
|
||||
if self.jstate != "active":
|
||||
return set()
|
||||
return set(self.job.get("files", []) + self.job.get("new_files", []))
|
||||
|
||||
def to_ui(self, fn, *args, **kw):
|
||||
"""call_from_thread that is a no-op once the app is shutting down (a worker can outlive it)."""
|
||||
if self._closing or self._closed: # MessagePump state; pinned Textual, see vendor/requirements.txt
|
||||
return
|
||||
try:
|
||||
self.call_from_thread(fn, *args, **kw)
|
||||
except RuntimeError:
|
||||
pass
|
||||
|
||||
def say(self, text, severity="information"):
|
||||
"""A toast plus an entry in the activity log; safe from worker threads."""
|
||||
self.activity.append((time.time(), severity, text))
|
||||
if threading.current_thread() is threading.main_thread():
|
||||
self.notify(text, severity=severity, timeout=6)
|
||||
else:
|
||||
self.to_ui(self.notify, text, severity=severity, timeout=6)
|
||||
|
||||
def log_line(self, text):
|
||||
self.activity.append((time.time(), "log", text))
|
||||
|
||||
def check_action(self, action, parameters):
|
||||
if isinstance(self.screen, ModalScreen):
|
||||
return False
|
||||
if action == "cancel_run":
|
||||
return self.jstate in ("active", "orphaned")
|
||||
if action in FILE_ACTIONS:
|
||||
return action in TAB_ACTIONS.get(self.tab(), set())
|
||||
return True
|
||||
|
||||
# -- state: snapshot and job ------------------------------------------------
|
||||
def action_refresh(self):
|
||||
self.refresh_snapshot()
|
||||
|
||||
@work(thread=True, exclusive=True, group="refresh")
|
||||
def refresh_snapshot(self):
|
||||
self.refreshing = True
|
||||
self.last_refresh = time.time()
|
||||
self.to_ui(self.show_title)
|
||||
try:
|
||||
snap = self.flow.snapshot()
|
||||
except Exception as e: # noqa - a failed query is shown, never fatal
|
||||
snap = Snapshot()
|
||||
snap.err = str(e)
|
||||
self.to_ui(self.apply_snapshot, snap)
|
||||
|
||||
def show_title(self):
|
||||
if self.refreshing:
|
||||
self.title = "dsflow · querying DesignSync…"
|
||||
elif self.snap is not None:
|
||||
self.title = "dsflow · updated %s (%.1fs)" % (time.strftime("%H:%M:%S", time.localtime(self.snap.ts)),
|
||||
self.snap.took)
|
||||
|
||||
def apply_snapshot(self, snap):
|
||||
self.snap = snap
|
||||
self.refreshing = False
|
||||
known = set(r["path"] for r in snap.changes + snap.locks + snap.checkout)
|
||||
self.marks &= known
|
||||
self.render_tables()
|
||||
self.show_title()
|
||||
if self.focused is None and self.tab() in FILE_TABS:
|
||||
self.table(self.tab()).focus() # a loading table can't take focus at mount
|
||||
if snap.err:
|
||||
self.say("refresh failed: %s" % snap.err, "error")
|
||||
|
||||
def render_tables(self):
|
||||
if self.snap is None:
|
||||
return
|
||||
tabs = self.tabs
|
||||
counts = {"changes": len(self.snap.changes), "locks": len([r for r in self.snap.locks if r["holder"] == ME]),
|
||||
"checkout": len(self.snap.checkout)}
|
||||
for tab in FILE_TABS:
|
||||
table = self.table(tab)
|
||||
table.loading = False
|
||||
table.show(getattr(self.snap, tab), self.marks, self.run_files(), self.text_filter)
|
||||
tabs.get_tab(tab).label = "%s %d" % (TAB_LABELS[tab], counts[tab])
|
||||
self.show_detail(tab)
|
||||
|
||||
def show_detail(self, tab):
|
||||
table = self.table(tab)
|
||||
row = table.current()
|
||||
self.details[tab].show(tab, row, self.flow.ws,
|
||||
bool(row) and row["path"] in self.run_files())
|
||||
|
||||
def on_data_table_row_highlighted(self, event):
|
||||
if isinstance(event.data_table, FileTable):
|
||||
self.show_detail(event.data_table.kind)
|
||||
|
||||
def on_data_table_row_selected(self, event):
|
||||
if isinstance(event.data_table, FileTable) and event.data_table.selection_toggles():
|
||||
self.action_toggle_mark(advance=False)
|
||||
|
||||
def poll(self):
|
||||
path = self.flow.path(JOB_FILE)
|
||||
try:
|
||||
mtime = os.stat(path).st_mtime
|
||||
except OSError:
|
||||
mtime = None
|
||||
if mtime != self.jmtime:
|
||||
self.jmtime = mtime
|
||||
job = read_json(path) if mtime else None
|
||||
if job or mtime is None:
|
||||
self.job = job
|
||||
prev, self.jstate = self.jstate, job_state(self.job)
|
||||
if prev != self.jstate:
|
||||
self.refresh_bindings()
|
||||
self.render_tables()
|
||||
if self.jstate == "active" and self.locks_seen != self.job["id"] and \
|
||||
any(s["key"] == "lock" and s["status"] == "done" for s in self.job["steps"]):
|
||||
self.locks_seen = self.job["id"]
|
||||
self.refresh_snapshot() # show the run's locks as soon as it has them
|
||||
if prev == "active" and self.jstate == "done":
|
||||
self.run_finished()
|
||||
if self.refresh_every and not self.refreshing and time.time() - self.last_refresh > self.refresh_every:
|
||||
self.refresh_snapshot()
|
||||
self.runbar.update(run_bar(self.job, self.jstate, len(self.marks)))
|
||||
self.run_panel.show(self.job, self.jstate)
|
||||
self.log_panel.sync_sources()
|
||||
self.log_panel.tick()
|
||||
glyph = {"active": " ⟳", "orphaned": " ▲", "none": ""}.get(
|
||||
self.jstate, " ✔" if (self.job or {}).get("status") == "passed" else " ✘")
|
||||
tab = self.tabs.get_tab("sanity")
|
||||
if str(tab.label) != TAB_LABELS["sanity"] + glyph:
|
||||
tab.label = TAB_LABELS["sanity"] + glyph
|
||||
|
||||
def run_finished(self):
|
||||
st = self.job.get("status")
|
||||
if self.job.get("checked_in"):
|
||||
self.marks -= set(self.job["files"] + self.job["new_files"])
|
||||
self.say("sanity %s: %s" % (st.upper(), self.job.get("summary", "")),
|
||||
"information" if st == "passed" else "error")
|
||||
self.bell()
|
||||
self.refresh_snapshot()
|
||||
|
||||
# -- tabs, marks, filter ------------------------------------------------------
|
||||
def on_tabbed_content_tab_activated(self, event):
|
||||
self.refresh_bindings()
|
||||
if self.tab() in FILE_TABS:
|
||||
self.table(self.tab()).focus()
|
||||
|
||||
PANE_FOCUS = {"sanity": "#run-log", "logs": "#log-view"}
|
||||
|
||||
def action_show_tab(self, tab):
|
||||
# focus moves into the pane too: TabbedContent follows focus, so a stale focus would switch back
|
||||
self.tabs.active = tab
|
||||
self.query_one(self.PANE_FOCUS.get(tab, "#table-" + tab)).focus()
|
||||
self.refresh_bindings()
|
||||
|
||||
def action_toggle_mark(self, advance=True):
|
||||
if self.tab() not in FILE_TABS:
|
||||
return
|
||||
table = self.table(self.tab())
|
||||
row = table.current()
|
||||
if row is None:
|
||||
return
|
||||
self.marks ^= {row["path"]}
|
||||
for tab in FILE_TABS:
|
||||
self.table(tab).refresh_marks(self.marks)
|
||||
if advance:
|
||||
table.action_cursor_down()
|
||||
|
||||
def action_mark_all(self):
|
||||
paths = set(r["path"] for r in self.table(self.tab()).file_rows)
|
||||
self.marks = self.marks - paths if paths <= self.marks else self.marks | paths
|
||||
for tab in FILE_TABS:
|
||||
self.table(tab).refresh_marks(self.marks)
|
||||
|
||||
def action_clear(self):
|
||||
flt = self.query_one("#filter", Input)
|
||||
if flt.has_focus or flt.display:
|
||||
flt.value, self.text_filter = "", ""
|
||||
flt.display = False
|
||||
self.render_tables()
|
||||
if self.tab() in FILE_TABS:
|
||||
self.table(self.tab()).focus()
|
||||
return
|
||||
if self.marks:
|
||||
self.marks.clear()
|
||||
for tab in FILE_TABS:
|
||||
self.table(tab).refresh_marks(self.marks)
|
||||
|
||||
def action_filter(self):
|
||||
flt = self.query_one("#filter", Input)
|
||||
flt.display = True
|
||||
flt.focus()
|
||||
|
||||
def on_input_changed(self, event):
|
||||
if event.input.id == "filter":
|
||||
self.text_filter = event.value
|
||||
self.render_tables()
|
||||
|
||||
def on_input_submitted(self, event):
|
||||
if event.input.id == "filter":
|
||||
if not event.value:
|
||||
event.input.display = False
|
||||
self.table(self.tab()).focus()
|
||||
|
||||
# -- picking rows ---------------------------------------------------------------
|
||||
def need_snap(self):
|
||||
if self.snap is None:
|
||||
self.say("still reading the workspace - one moment", "warning")
|
||||
return False
|
||||
return True
|
||||
|
||||
def pick(self, rows, use_cursor=True):
|
||||
"""Marked rows among `rows`; with no marks, the highlighted row if it is one of them."""
|
||||
chosen = [r for r in rows if r["path"] in self.marks]
|
||||
if chosen or not use_cursor or self.tab() not in FILE_TABS:
|
||||
return chosen
|
||||
cur = self.table(self.tab()).current()
|
||||
return [r for r in rows if cur is not None and r["path"] == cur["path"]]
|
||||
|
||||
def background(self, label, fn):
|
||||
if self.busy:
|
||||
self.say("busy: %s - wait for it to finish" % self.busy, "warning")
|
||||
return
|
||||
self.busy = label
|
||||
self.log_line(label + " …")
|
||||
self.notify(label + " …", timeout=3)
|
||||
self.run_background(label, fn)
|
||||
|
||||
@work(thread=True, group="actions")
|
||||
def run_background(self, label, fn):
|
||||
try:
|
||||
ok, msg = fn()
|
||||
except Exception as e: # noqa - any failure becomes a toast instead of killing the UI
|
||||
ok, msg = False, "%s failed: %s" % (label, e)
|
||||
self.busy = None
|
||||
self.say(msg, "information" if ok else "error")
|
||||
self.to_ui(self.refresh_snapshot)
|
||||
|
||||
# -- actions --------------------------------------------------------------------
|
||||
def action_sanity(self):
|
||||
if not self.need_snap():
|
||||
return
|
||||
if self.jstate == "active":
|
||||
return self.say("a sanity run is already in progress (x cancels it)", "warning")
|
||||
if self.jstate == "orphaned":
|
||||
return self.say("the previous runner died holding locks - press x to release them first", "error")
|
||||
if runner_alive(self.flow):
|
||||
return self.say("another runner still holds the job lock in this workspace", "error")
|
||||
rows = self.pick(self.snap.changes, use_cursor=self.tab() == "changes")
|
||||
if not rows:
|
||||
return self.say("mark files in Changes (space) first", "warning")
|
||||
blockers = ops.sanity_blockers(rows)
|
||||
if blockers:
|
||||
return self.push_screen(MessageDialog("Can't start sanity", [("Fix these first:", "bold")]
|
||||
+ [(" " + b, "bad") for b in blockers]))
|
||||
if not self.flow.configs:
|
||||
return self.push_screen(MessageDialog("No sanity configs",
|
||||
[("SANITY_CONFIGS is empty in %s" % self.flow.conf, "bad")]))
|
||||
mods, news = ops.split_kinds(rows)
|
||||
chosen = set(mods + news)
|
||||
others = [r["path"] for r in self.snap.changes if r["path"] not in chosen]
|
||||
notes = [("%d file(s) are locked while sanity runs and released when it ends." % len(rows), "bold")]
|
||||
notes += file_notes(mods + news, 6)
|
||||
if others:
|
||||
notes.append(("▲ %d other local change(s) are not marked. They stay in the workspace, so sanity tests "
|
||||
"them too, but they won't be checked in." % len(others), "warn"))
|
||||
if any(r["unknown"] and r["kind"] == "M" for r in rows):
|
||||
notes.append(("▲ couldn't read base/latest versions for some files; freshness is unverified.", "warn"))
|
||||
if self.flow.sanity_cmd:
|
||||
notes.append(("sanity command: %s" % self.flow.sanity_cmd, "dim"))
|
||||
|
||||
def launch(values):
|
||||
if not values:
|
||||
return
|
||||
self.last_msg = values["msg"]
|
||||
job = new_job(self.flow, mods, news, values["configs"], values["mode"], values["msg"], values["tag"],
|
||||
values["refresh"])
|
||||
try:
|
||||
spawn_runner(self.flow, job)
|
||||
except OSError as e:
|
||||
return self.say("could not start the runner: %s" % e, "error")
|
||||
self.jmtime = None
|
||||
self.say("sanity started on %s for %d file(s)" % (" ".join(job["configs"]), len(rows)))
|
||||
self.call_after_refresh(self.action_show_tab, "sanity") # after the dialog hands focus back
|
||||
self.push_screen(SanityDialog(notes, self.flow.configs, self.flow.tags, self.flow.trunk, self.last_msg),
|
||||
launch)
|
||||
|
||||
def action_cancel_run(self):
|
||||
job = self.job
|
||||
if self.jstate == "active":
|
||||
def confirmed(yes):
|
||||
if yes:
|
||||
ops.request_cancel(self.flow)
|
||||
self.say("cancel requested - the runner is cleaning up")
|
||||
self.push_screen(ConfirmDialog("Cancel sanity run?", [
|
||||
("Stops the running sanity, then releases the %d lock(s) the run took. Nothing is checked in."
|
||||
% len(job.get("locked_by_job", [])), "")], yes="Cancel run"), confirmed)
|
||||
elif self.jstate == "orphaned":
|
||||
def confirmed(yes):
|
||||
if yes:
|
||||
self.background("releasing the lost runner's locks", lambda: ops.release_orphan(self.flow, job))
|
||||
self.push_screen(ConfirmDialog("Release the lost runner's locks?", [
|
||||
("The runner stopped sending heartbeats. Stop its simulation and release the lock(s) it took?", "")]
|
||||
+ file_notes(job.get("locked_by_job", [])), yes="Release"), confirmed)
|
||||
else:
|
||||
self.say("no sanity run in progress")
|
||||
|
||||
def action_checkin(self):
|
||||
if not self.need_snap():
|
||||
return
|
||||
if self.jstate == "active":
|
||||
return self.say("wait for the sanity run to finish - it may check these in itself", "warning")
|
||||
rows = self.pick(self.snap.changes, use_cursor=self.tab() == "changes")
|
||||
if not rows:
|
||||
return self.say("mark files in Changes (space) first", "warning")
|
||||
stale = [r["path"] for r in rows if r["stale"]]
|
||||
if stale:
|
||||
return self.push_screen(MessageDialog("Can't check in", [
|
||||
("Went stale on Trunk - rebase (m), then rerun sanity:", "bad")] + file_notes(stale)))
|
||||
probs = ops.stamp_problems(self.flow, self.job, rows)
|
||||
if probs:
|
||||
return self.push_screen(MessageDialog("Sanity required", [
|
||||
("These files need a passing sanity run first:", "bold")] + [(" " + p, "warn") for p in probs]
|
||||
+ [("", ""), ("Press s and pick 'Check in' to test and check in in one go.", "dim")]))
|
||||
mods, news = ops.split_kinds(rows)
|
||||
job = self.job
|
||||
|
||||
def go(values):
|
||||
if values:
|
||||
self.last_msg = values["msg"]
|
||||
self.background("checking in %d file(s)" % len(rows), lambda: ops.checkin_now(
|
||||
self.flow, job, rows, values["msg"], values["tag"], self.log_line))
|
||||
self.push_screen(CheckinDialog(
|
||||
"Check in %d file(s)" % len(rows),
|
||||
[("Sanity passed %s on %s." % (fmt_ago(job["sanity_epoch"]), " ".join(job["configs"])), "good")]
|
||||
+ file_notes(mods + news), self.flow.tags, job.get("msg") or self.last_msg), go)
|
||||
|
||||
def action_tag(self):
|
||||
if not self.need_snap():
|
||||
return
|
||||
rows = self.pick(self.table(self.tab()).file_rows)
|
||||
if not rows:
|
||||
return self.say("mark files (space) first", "warning")
|
||||
paths = [r["path"] for r in rows if r.get("kind") != "A"]
|
||||
if not paths:
|
||||
return self.say("new files aren't in the vault yet - check them in before tagging", "warning")
|
||||
if not self.flow.tags:
|
||||
return self.say("no tags configured (DSFLOW_TAGS in dsflow.conf)", "error")
|
||||
edited = [r for r in rows if r.get("kind") == "M" or r.get("modified")]
|
||||
notes = [("Tag %d file(s) in one batch:" % len(paths), "bold")] + file_notes(paths, 6)
|
||||
if edited:
|
||||
notes.append(("▲ %d file(s) have local edits. The tag goes on the vault version your copy is based on, "
|
||||
"not on your edits. Check in first to tag your changes." % len(edited), "warn"))
|
||||
if len(paths) < len(rows):
|
||||
notes.append(("skipping %d new (unmanaged) file(s)" % (len(rows) - len(paths)), "dim"))
|
||||
|
||||
def go(tag):
|
||||
if tag:
|
||||
self.background("tagging %d file(s) %s" % (len(paths), tag),
|
||||
lambda: ops.run_action(self.flow, "ds_tag", paths, "tag " + tag, self.log_line,
|
||||
lead=[tag]))
|
||||
self.push_screen(TagDialog(notes, self.flow.tags), go)
|
||||
|
||||
def action_lock(self):
|
||||
if not self.need_snap():
|
||||
return
|
||||
rows = [r for r in self.pick(self.table(self.tab()).file_rows) if r.get("kind") != "A"]
|
||||
paths = [r["path"] for r in rows if not r["holder"]]
|
||||
theirs = [r for r in rows if r["holder"] and r["holder"] != ME]
|
||||
if theirs:
|
||||
self.say("skipping %d file(s) locked by others" % len(theirs), "warning")
|
||||
if not paths:
|
||||
return self.say("nothing to lock - mark unlocked files first", "warning")
|
||||
self.background("locking %d file(s)" % len(paths),
|
||||
lambda: ops.run_action(self.flow, "ds_lock", paths, "lock", self.log_line))
|
||||
|
||||
def action_unlock(self):
|
||||
if not self.need_snap():
|
||||
return
|
||||
in_run = set(self.job.get("locked_by_job", [])) if self.jstate == "active" else set()
|
||||
rows = self.pick(self.table(self.tab()).file_rows)
|
||||
paths = [r["path"] for r in rows if r["holder"] == ME and r["path"] not in in_run]
|
||||
if any(r["path"] in in_run for r in rows):
|
||||
self.say("files locked by the running sanity are released when it ends", "warning")
|
||||
if not paths:
|
||||
return self.say("none of the marked files are locked by you", "warning")
|
||||
|
||||
def confirmed(yes):
|
||||
if yes:
|
||||
self.background("unlocking %d file(s)" % len(paths),
|
||||
lambda: ops.run_action(self.flow, "ds_unlock", paths, "unlock", self.log_line))
|
||||
self.push_screen(ConfirmDialog("Release %d lock(s)?" % len(paths),
|
||||
file_notes(paths) + [("", ""), ("Local edits are kept.", "dim")],
|
||||
yes="Release"), confirmed)
|
||||
|
||||
def action_add_new(self):
|
||||
def added(paths):
|
||||
if not paths:
|
||||
return
|
||||
paths = [norm(os.path.relpath(self.flow.wpath(p), self.flow.ws)) for p in paths]
|
||||
self.flow.add_new(paths)
|
||||
self.marks |= set(paths)
|
||||
self.say("registered %d new file(s)" % len(paths))
|
||||
self.refresh_snapshot()
|
||||
self.push_screen(AddFilesDialog(self.flow.ws), added)
|
||||
|
||||
def action_rebase(self):
|
||||
if not self.need_snap():
|
||||
return
|
||||
paths = [r["path"] for r in self.pick(self.snap.changes, use_cursor=self.tab() == "changes") if r["stale"]]
|
||||
if not paths:
|
||||
return self.say("none of the marked files are stale")
|
||||
|
||||
def confirmed(yes):
|
||||
if yes:
|
||||
def work_fn():
|
||||
ok, msg = ops.run_action(self.flow, "ds_rebase", paths, "merge", self.log_line)
|
||||
self.flow.drop_stamp()
|
||||
return ok, msg + (" - check for conflicts, then rerun sanity" if ok else "")
|
||||
self.background("merging %d file(s)" % len(paths), work_fn)
|
||||
self.push_screen(ConfirmDialog("Merge %s into %d file(s)?" % (self.flow.trunk, len(paths)), file_notes(paths) + [
|
||||
("", ""), ("Runs ds_rebase (dssc pop -merge). Resolve any conflict markers, then rerun sanity.", "dim")],
|
||||
yes="Merge"), confirmed)
|
||||
|
||||
def action_help(self):
|
||||
self.push_screen(HelpDialog(VERSION, self.flow.conf))
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Modal dialogs: run sanity, check in, tag, confirm, message, register new files, help."""
|
||||
import os
|
||||
import shlex
|
||||
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
from textual.binding import Binding
|
||||
from textual.containers import Horizontal, Vertical, VerticalScroll
|
||||
from textual.screen import ModalScreen
|
||||
from textual.widgets import Button, Checkbox, Input, Label, RadioButton, RadioSet, SelectionList, Static
|
||||
|
||||
from ..ops import sanity_form_error
|
||||
from .widgets import ACCENT, DIM
|
||||
|
||||
|
||||
def file_notes(paths, limit=8):
|
||||
notes = [(" • " + p, "") for p in paths[:limit]]
|
||||
if len(paths) > limit:
|
||||
notes.append((" … and %d more" % (len(paths) - limit), "dim"))
|
||||
return notes
|
||||
|
||||
|
||||
class Dialog(ModalScreen):
|
||||
"""Title, notes, a body of fields, an error line and buttons. Enter submits, Esc cancels."""
|
||||
|
||||
BINDINGS = [Binding("escape", "cancel", "Cancel")]
|
||||
OK_LABEL = "OK"
|
||||
CANCEL_LABEL = "Cancel"
|
||||
|
||||
def __init__(self, heading, notes=()):
|
||||
super().__init__(classes="dialog-screen")
|
||||
self.heading = heading
|
||||
self.notes = list(notes)
|
||||
|
||||
def compose(self):
|
||||
with Vertical(id="dialog"):
|
||||
yield Label(self.heading, id="dialog-title")
|
||||
with VerticalScroll(id="dialog-body"):
|
||||
for text, kind in self.notes:
|
||||
yield Static(Text(text), classes="note note-%s" % (kind or "plain"))
|
||||
yield from self.body()
|
||||
yield Label("", id="dialog-error")
|
||||
with Horizontal(id="dialog-buttons"):
|
||||
yield Button(self.OK_LABEL, variant="primary", id="ok")
|
||||
if self.CANCEL_LABEL:
|
||||
yield Button(self.CANCEL_LABEL, id="cancel")
|
||||
|
||||
def body(self):
|
||||
return iter(())
|
||||
|
||||
def on_mount(self):
|
||||
first = self.first_focus()
|
||||
(self.query_one(first) if first else self.query_one("#ok")).focus()
|
||||
|
||||
def first_focus(self):
|
||||
return None
|
||||
|
||||
def values(self):
|
||||
return True
|
||||
|
||||
def validate(self, values):
|
||||
return None
|
||||
|
||||
def submit(self):
|
||||
values = self.values()
|
||||
error = self.validate(values)
|
||||
if error:
|
||||
self.query_one("#dialog-error", Label).update("✘ " + error)
|
||||
return
|
||||
self.dismiss(values)
|
||||
|
||||
def on_button_pressed(self, event):
|
||||
event.stop()
|
||||
if event.button.id == "ok":
|
||||
self.submit()
|
||||
else:
|
||||
self.dismiss(None)
|
||||
|
||||
def on_input_submitted(self, event):
|
||||
event.stop()
|
||||
self.submit()
|
||||
|
||||
def action_cancel(self):
|
||||
self.dismiss(None)
|
||||
|
||||
|
||||
def field(text):
|
||||
return Label(text, classes="field")
|
||||
|
||||
|
||||
def radio_set(options, pressed=0, id=None):
|
||||
return RadioSet(*[RadioButton(o, value=i == pressed) for i, o in enumerate(options)], id=id, compact=True)
|
||||
|
||||
|
||||
class MessageDialog(Dialog):
|
||||
OK_LABEL, CANCEL_LABEL = "Close", ""
|
||||
|
||||
|
||||
class ConfirmDialog(Dialog):
|
||||
CANCEL_LABEL = "Cancel"
|
||||
|
||||
def __init__(self, heading, notes=(), yes="Yes"):
|
||||
super().__init__(heading, notes)
|
||||
self.OK_LABEL = yes
|
||||
|
||||
|
||||
class SanityDialog(Dialog):
|
||||
"""Configs, what to do on pass, comment, tag, refresh. Returns a dict for new_job()."""
|
||||
|
||||
OK_LABEL = "Run sanity"
|
||||
|
||||
def __init__(self, notes, configs, tags, trunk, last_msg):
|
||||
super().__init__("Run sanity", notes)
|
||||
self.configs, self.tags, self.trunk, self.last_msg = configs, tags, trunk, last_msg
|
||||
|
||||
def body(self):
|
||||
yield field("Sanity configs")
|
||||
yield SelectionList(*[(c, c, True) for c in self.configs], id="configs", compact=True)
|
||||
yield field("On pass")
|
||||
yield radio_set(["Check in", "Unlock only (check in later)"], id="mode")
|
||||
yield field("Check-in comment")
|
||||
yield Input(value=self.last_msg, placeholder="what changed and why", id="msg")
|
||||
yield field("Then tag")
|
||||
yield radio_set(["none"] + self.tags, id="tag")
|
||||
yield Checkbox("Refresh unmodified files to %s first" % self.trunk, value=True, id="refresh",
|
||||
compact=True, classes="field-check")
|
||||
|
||||
def first_focus(self):
|
||||
return "#msg"
|
||||
|
||||
def values(self):
|
||||
chosen = set(self.query_one("#configs", SelectionList).selected)
|
||||
tag_index = self.query_one("#tag", RadioSet).pressed_index
|
||||
return dict(configs=[c for c in self.configs if c in chosen],
|
||||
mode="checkin" if self.query_one("#mode", RadioSet).pressed_index == 0 else "unlock",
|
||||
msg=self.query_one("#msg", Input).value.strip(),
|
||||
tag=self.tags[tag_index - 1] if tag_index > 0 else "",
|
||||
refresh=self.query_one("#refresh", Checkbox).value)
|
||||
|
||||
def validate(self, values):
|
||||
return sanity_form_error(values, self.configs)
|
||||
|
||||
|
||||
class CheckinDialog(Dialog):
|
||||
OK_LABEL = "Check in"
|
||||
|
||||
def __init__(self, heading, notes, tags, msg):
|
||||
super().__init__(heading, notes)
|
||||
self.tags, self.msg = tags, msg
|
||||
|
||||
def body(self):
|
||||
yield field("Check-in comment")
|
||||
yield Input(value=self.msg, placeholder="what changed and why", id="msg")
|
||||
yield field("Then tag")
|
||||
yield radio_set(["none"] + self.tags, id="tag")
|
||||
|
||||
def first_focus(self):
|
||||
return "#msg"
|
||||
|
||||
def values(self):
|
||||
i = self.query_one("#tag", RadioSet).pressed_index
|
||||
return dict(msg=self.query_one("#msg", Input).value.strip(), tag=self.tags[i - 1] if i > 0 else "")
|
||||
|
||||
def validate(self, values):
|
||||
return None if values["msg"] else "a check-in comment is required"
|
||||
|
||||
|
||||
class TagDialog(Dialog):
|
||||
OK_LABEL = "Tag"
|
||||
|
||||
def __init__(self, notes, tags):
|
||||
super().__init__("Batch tag", notes)
|
||||
self.tags = tags
|
||||
|
||||
def body(self):
|
||||
yield field("Tag")
|
||||
yield radio_set(self.tags, id="tag")
|
||||
|
||||
def first_focus(self):
|
||||
return "#tag"
|
||||
|
||||
def values(self):
|
||||
return self.tags[max(0, self.query_one("#tag", RadioSet).pressed_index)]
|
||||
|
||||
|
||||
class AddFilesDialog(Dialog):
|
||||
OK_LABEL = "Register"
|
||||
|
||||
def __init__(self, ws):
|
||||
super().__init__("Register new files", [
|
||||
("Brand-new files aren't in the vault, so dssc can't see them as modified. Register them here and "
|
||||
"they're checked in with the rest (same as `dsflow add`).", "dim")])
|
||||
self.ws = ws
|
||||
|
||||
def body(self):
|
||||
yield field("Path(s), workspace-relative, space separated")
|
||||
yield Input(placeholder="rtl/rx/rx_new.sv", id="paths")
|
||||
|
||||
def first_focus(self):
|
||||
return "#paths"
|
||||
|
||||
def values(self):
|
||||
try:
|
||||
return shlex.split(self.query_one("#paths", Input).value)
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
def validate(self, paths):
|
||||
if not paths:
|
||||
return "give one or more workspace-relative paths"
|
||||
bad = [p for p in paths if not os.path.isfile(os.path.join(self.ws, p))]
|
||||
return "not a file: %s" % ", ".join(bad) if bad else None
|
||||
|
||||
|
||||
HELP_KEYS = [
|
||||
("Views", [("1-5", "Changes, Locks, Checked-out, Sanity run, Logs (or click a tab)"),
|
||||
("↑↓ PgUp PgDn", "move; the mouse works too (click, scroll)"),
|
||||
("/", "filter files by path; esc closes the filter"),
|
||||
("ctrl+p", "command palette: themes, keys, screenshot")]),
|
||||
("Files", [("space enter", "mark / unmark (no marks = the highlighted row)"),
|
||||
("a esc", "mark everything in the tab / clear marks"),
|
||||
("n", "register brand-new files for check-in"),
|
||||
("m", "rebase stale files onto Trunk:Latest"),
|
||||
("l u", "lock / release a lock"),
|
||||
("t", "batch-tag the marked files")]),
|
||||
("Sanity", [("s", "run sanity: lock, refresh, every config, then check in or unlock"),
|
||||
("c", "check in marked files a passing run already covers"),
|
||||
("x", "cancel the run, or clean up after a lost runner")]),
|
||||
("", [("r q", "refresh from DesignSync / quit (a running sanity keeps going)")]),
|
||||
]
|
||||
|
||||
|
||||
class HelpDialog(Dialog):
|
||||
OK_LABEL, CANCEL_LABEL = "Close", ""
|
||||
|
||||
def __init__(self, version, conf):
|
||||
super().__init__("dsflow_tui %s · keys" % version)
|
||||
self.conf = conf
|
||||
|
||||
def body(self):
|
||||
for section, keys in HELP_KEYS:
|
||||
if section:
|
||||
yield field(section)
|
||||
grid = Table.grid(padding=(0, 2))
|
||||
grid.add_column(style="bold " + ACCENT, no_wrap=True, min_width=14)
|
||||
grid.add_column()
|
||||
for key, text in keys:
|
||||
grid.add_row(key, text)
|
||||
yield Static(grid)
|
||||
yield Static(Text("\nconf %s" % self.conf, style=DIM, overflow="fold"))
|
||||
@@ -0,0 +1,198 @@
|
||||
/* dsflow_tui - colours come from the active theme ($primary, $warning, ...) so every theme works. */
|
||||
|
||||
Screen {
|
||||
layout: vertical;
|
||||
}
|
||||
|
||||
#filter {
|
||||
display: none;
|
||||
margin: 0 1;
|
||||
border: tall $accent;
|
||||
}
|
||||
|
||||
TabbedContent {
|
||||
height: 1fr;
|
||||
}
|
||||
|
||||
TabPane {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* -- file tabs ------------------------------------------------------------ */
|
||||
.file-pane {
|
||||
height: 1fr;
|
||||
}
|
||||
|
||||
FileTable {
|
||||
width: 1fr;
|
||||
height: 1fr;
|
||||
scrollbar-size-vertical: 1;
|
||||
}
|
||||
|
||||
FileTable > .datatable--header {
|
||||
text-style: bold;
|
||||
color: $text-muted;
|
||||
background: $surface;
|
||||
}
|
||||
|
||||
DetailPane {
|
||||
width: 40;
|
||||
height: 1fr;
|
||||
padding: 1 2;
|
||||
background: $boost;
|
||||
border-left: wide $primary 40%;
|
||||
}
|
||||
|
||||
/* -- sanity run tab ---------------------------------------------------------- */
|
||||
RunPanel {
|
||||
padding: 1 2 0 2;
|
||||
}
|
||||
|
||||
#run-empty {
|
||||
padding: 2 4;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
#run-head {
|
||||
height: auto;
|
||||
padding: 0 1 1 1;
|
||||
border-bottom: solid $primary 30%;
|
||||
}
|
||||
|
||||
#run-steps {
|
||||
height: auto;
|
||||
padding: 1 1;
|
||||
}
|
||||
|
||||
#run-summary {
|
||||
height: auto;
|
||||
padding: 0 1 1 1;
|
||||
}
|
||||
|
||||
#run-log, #log-view {
|
||||
height: 1fr;
|
||||
border: round $primary 40%;
|
||||
border-title-color: $text-muted;
|
||||
background: $surface;
|
||||
scrollbar-size-vertical: 1;
|
||||
}
|
||||
|
||||
/* -- logs tab ---------------------------------------------------------------- */
|
||||
LogPanel {
|
||||
padding: 1 2 0 2;
|
||||
}
|
||||
|
||||
#log-bar {
|
||||
height: auto;
|
||||
margin-bottom: 1;
|
||||
}
|
||||
|
||||
.log-label {
|
||||
padding: 1 1 0 0;
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
#log-source {
|
||||
width: 40;
|
||||
}
|
||||
|
||||
/* -- status line ------------------------------------------------------------ */
|
||||
#runbar {
|
||||
height: 1;
|
||||
padding: 0 1;
|
||||
background: $panel;
|
||||
}
|
||||
|
||||
/* -- dialogs ----------------------------------------------------------------- */
|
||||
.dialog-screen {
|
||||
align: center middle;
|
||||
background: $background 60%;
|
||||
}
|
||||
|
||||
#dialog {
|
||||
width: 90;
|
||||
max-width: 96%;
|
||||
height: auto;
|
||||
max-height: 94%;
|
||||
padding: 1 2;
|
||||
background: $surface;
|
||||
border: thick $primary 70%;
|
||||
}
|
||||
|
||||
#dialog-title {
|
||||
width: 100%;
|
||||
margin-bottom: 1;
|
||||
text-style: bold;
|
||||
color: $accent;
|
||||
}
|
||||
|
||||
#dialog-body {
|
||||
height: auto;
|
||||
max-height: 32;
|
||||
}
|
||||
|
||||
.note {
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.note-bold {
|
||||
text-style: bold;
|
||||
}
|
||||
|
||||
.note-warn {
|
||||
color: $warning;
|
||||
margin-top: 1;
|
||||
}
|
||||
|
||||
.note-bad {
|
||||
color: $error;
|
||||
}
|
||||
|
||||
.note-good {
|
||||
color: $success;
|
||||
}
|
||||
|
||||
.note-dim {
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
.field {
|
||||
margin-top: 1;
|
||||
text-style: bold;
|
||||
color: $text-muted;
|
||||
}
|
||||
|
||||
#dialog RadioSet {
|
||||
layout: horizontal;
|
||||
width: 100%;
|
||||
height: auto;
|
||||
}
|
||||
|
||||
#dialog RadioButton {
|
||||
margin-right: 2;
|
||||
}
|
||||
|
||||
#dialog SelectionList {
|
||||
height: auto;
|
||||
max-height: 8;
|
||||
}
|
||||
|
||||
.field-check {
|
||||
margin-top: 1;
|
||||
}
|
||||
|
||||
#dialog-error {
|
||||
width: 100%;
|
||||
color: $error;
|
||||
text-style: bold;
|
||||
}
|
||||
|
||||
#dialog-buttons {
|
||||
height: auto;
|
||||
margin-top: 1;
|
||||
align-horizontal: right;
|
||||
}
|
||||
|
||||
#dialog-buttons Button {
|
||||
margin-left: 2;
|
||||
}
|
||||
@@ -0,0 +1,466 @@
|
||||
"""The widgets the main screen is built from: file tables, the detail pane, the run panel and the log viewer."""
|
||||
import os
|
||||
import time
|
||||
|
||||
from rich.console import Group
|
||||
from rich.table import Table
|
||||
from rich.text import Text
|
||||
from textual.containers import Horizontal, Vertical
|
||||
from textual.widgets import DataTable, Label, RichLog, Select, Static
|
||||
|
||||
from ..common import ME, fmt_ago, fmt_clock, fmt_dur
|
||||
|
||||
# Semantic colours for cell content (rich styles). Chrome colours come from the theme via styles.tcss.
|
||||
GOOD, BAD, WARN, HOT, ACCENT, DIM = "#9ece6a", "#f7768e", "#e0af68", "#bb9af7", "#7aa2f7", "#737aa2"
|
||||
INK = "#1a1b26" # text on coloured pills
|
||||
SPIN = "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏"
|
||||
|
||||
|
||||
def spinner():
|
||||
return SPIN[int(time.time() * 10) % len(SPIN)]
|
||||
|
||||
|
||||
def pill(text, colour):
|
||||
return Text(" %s " % text, style="bold %s on %s" % (INK, colour))
|
||||
|
||||
|
||||
def join(parts, sep=" "):
|
||||
out = Text()
|
||||
for i, part in enumerate(parts):
|
||||
if i:
|
||||
out.append(sep)
|
||||
out.append_text(part)
|
||||
return out
|
||||
|
||||
|
||||
# -- file tables ---------------------------------------------------------------
|
||||
def mark_cell(on):
|
||||
return Text("●", style="bold " + ACCENT) if on else Text("○", style=DIM)
|
||||
|
||||
|
||||
def holder_cell(holder, free_label="—"):
|
||||
if not holder:
|
||||
return Text(free_label, style=GOOD if free_label == "free" else DIM)
|
||||
if holder == ME:
|
||||
return Text("you", style="bold " + GOOD)
|
||||
return Text(holder, style="bold " + BAD)
|
||||
|
||||
|
||||
def version_cell(r):
|
||||
if r["kind"] == "A":
|
||||
return Text("new file", style=DIM)
|
||||
if r["unknown"]:
|
||||
return Text("%s → %s" % (r["base"] or "?", r["latest"] or "?"), style=WARN)
|
||||
if r["stale"]:
|
||||
return Text("%s → %s" % (r["base"], r["latest"]), style="bold " + BAD)
|
||||
return Text.assemble((r["base"], ""), (" latest", DIM))
|
||||
|
||||
|
||||
def flags_cell(r, in_run):
|
||||
flags = []
|
||||
if r.get("hot"):
|
||||
flags.append(pill("HOT", HOT))
|
||||
if r.get("stale"):
|
||||
flags.append(pill("STALE", BAD))
|
||||
if r.get("unknown") and r.get("kind") == "M":
|
||||
flags.append(pill("?VER", WARN))
|
||||
if r.get("exists") is False:
|
||||
flags.append(pill("MISSING", BAD))
|
||||
if in_run:
|
||||
flags.append(pill("IN-RUN", ACCENT))
|
||||
return join(flags)
|
||||
|
||||
|
||||
def local_cell(r):
|
||||
return Text("modified", style=WARN) if r["modified"] else Text("clean", style=DIM)
|
||||
|
||||
|
||||
class FileTable(DataTable):
|
||||
"""A row-cursor table of file rows that remembers the cursor by path across refreshes."""
|
||||
|
||||
COLUMNS = {
|
||||
"changes": [("", "mark", 1), ("St", "st", 2), ("File", "file", None), ("Base → Latest", "ver", 14),
|
||||
("Lock", "lock", 10), ("Flags", "flags", None)],
|
||||
"locks": [("", "mark", 1), ("File", "file", None), ("Holder", "holder", 12), ("Local copy", "local", 10),
|
||||
("Flags", "flags", None)],
|
||||
"checkout": [("", "mark", 1), ("File", "file", None), ("Local copy", "local", 10), ("Flags", "flags", None)],
|
||||
}
|
||||
|
||||
def __init__(self, kind):
|
||||
super().__init__(cursor_type="row", zebra_stripes=True, id="table-" + kind)
|
||||
self.kind = kind
|
||||
self.file_rows = []
|
||||
self.click_column = None # set while a mouse click is being handled
|
||||
|
||||
async def _on_click(self, event):
|
||||
# a click on the ● column toggles the mark; anywhere else it only moves the cursor
|
||||
self.click_column = event.style.meta.get("column")
|
||||
try:
|
||||
await super()._on_click(event)
|
||||
finally:
|
||||
self.click_column = None
|
||||
|
||||
def selection_toggles(self):
|
||||
return self.click_column is None or self.click_column == 0
|
||||
|
||||
def on_mount(self):
|
||||
for label, key, width in self.COLUMNS[self.kind]:
|
||||
self.add_column(label, key=key, width=width)
|
||||
|
||||
def current(self):
|
||||
if 0 <= self.cursor_row < len(self.file_rows):
|
||||
return self.file_rows[self.cursor_row]
|
||||
return None
|
||||
|
||||
def show(self, rows, marks, run_files, text_filter):
|
||||
keep = self.current()
|
||||
needle = text_filter.lower()
|
||||
self.file_rows = [r for r in rows if needle in r["path"].lower()]
|
||||
self.clear()
|
||||
for r in self.file_rows:
|
||||
self.add_row(*self.cells(r, marks, run_files), key=r["path"])
|
||||
if keep:
|
||||
index = next((i for i, r in enumerate(self.file_rows) if r["path"] == keep["path"]), 0)
|
||||
self.move_cursor(row=index, animate=False)
|
||||
|
||||
def refresh_marks(self, marks):
|
||||
for r in self.file_rows:
|
||||
self.update_cell(r["path"], "mark", mark_cell(r["path"] in marks))
|
||||
|
||||
def cells(self, r, marks, run_files):
|
||||
mark, path, in_run = mark_cell(r["path"] in marks), Text(r["path"]), r["path"] in run_files
|
||||
if self.kind == "changes":
|
||||
st = Text("M", style="bold " + WARN) if r["kind"] == "M" else Text("A", style="bold " + GOOD)
|
||||
return [mark, st, path, version_cell(r), holder_cell(r["holder"]), flags_cell(r, in_run)]
|
||||
if self.kind == "locks":
|
||||
return [mark, path, holder_cell(r["holder"], "free"), local_cell(r), flags_cell(r, in_run)]
|
||||
return [mark, path, local_cell(r), flags_cell(r, in_run)]
|
||||
|
||||
|
||||
class FilePane(Horizontal):
|
||||
"""A file table with the detail pane for its highlighted row."""
|
||||
|
||||
def __init__(self, kind):
|
||||
super().__init__(classes="file-pane")
|
||||
self.kind = kind
|
||||
|
||||
def compose(self):
|
||||
yield FileTable(self.kind)
|
||||
yield DetailPane(id="detail-" + self.kind)
|
||||
|
||||
|
||||
class DetailPane(Static):
|
||||
"""Everything known about the highlighted file, plus what can be done with it."""
|
||||
|
||||
def show(self, kind, r, ws, in_run):
|
||||
if r is None:
|
||||
self.update(Text("Nothing here.", style=DIM))
|
||||
return
|
||||
grid = Table.grid(padding=(0, 1))
|
||||
grid.add_column(style=DIM, no_wrap=True)
|
||||
grid.add_column()
|
||||
if kind == "changes":
|
||||
grid.add_row("change", Text("new file" if r["kind"] == "A" else "modified", style=WARN))
|
||||
if r["kind"] == "M":
|
||||
fresh = Text("stale - rebase (m)", style="bold " + BAD) if r["stale"] else \
|
||||
Text("? could not read", style=WARN) if r["unknown"] else Text("✔ fresh", style=GOOD)
|
||||
grid.add_row("base", r["base"] or "?")
|
||||
grid.add_row("latest", Text.assemble((r["latest"] or "?", ""), (" ", ""), fresh))
|
||||
else:
|
||||
grid.add_row("local copy", local_cell(r))
|
||||
grid.add_row("lock", holder_cell(r.get("holder", ""), "free"))
|
||||
grid.add_row("hot file", Text("yes - locked on edit", style=HOT) if r.get("hot") else Text("no", style=DIM))
|
||||
if in_run:
|
||||
grid.add_row("sanity", Text("in the current run", style=ACCENT))
|
||||
try:
|
||||
st = os.stat(os.path.join(ws, r["path"]))
|
||||
grid.add_row("on disk", "%s %s" % (fmt_size(st.st_size), fmt_clock(st.st_mtime)))
|
||||
grid.add_row("writable", Text("yes", style=GOOD) if os.access(os.path.join(ws, r["path"]), os.W_OK)
|
||||
else Text("no (read-only copy)", style=DIM))
|
||||
except OSError:
|
||||
grid.add_row("on disk", Text("missing", style=BAD))
|
||||
keys = Table.grid(padding=(0, 1))
|
||||
keys.add_column(style="bold " + ACCENT, no_wrap=True)
|
||||
keys.add_column(style=DIM)
|
||||
for key, text in HINTS[kind]:
|
||||
keys.add_row(key, text)
|
||||
self.update(Group(Text(r["path"], style="bold", overflow="fold"), Text("─" * 30, style=DIM), grid,
|
||||
Text(""), keys))
|
||||
|
||||
|
||||
HINTS = {
|
||||
"changes": [("space", "mark"), ("s", "run sanity"), ("c", "check in"), ("t", "tag"), ("m", "rebase stale"),
|
||||
("n", "add a new file")],
|
||||
"locks": [("space", "mark"), ("u", "release lock"), ("l", "lock"), ("t", "tag")],
|
||||
"checkout": [("space", "mark"), ("l", "lock"), ("t", "tag")],
|
||||
}
|
||||
|
||||
|
||||
def fmt_size(n):
|
||||
for unit in ("B", "KB", "MB"):
|
||||
if n < 1024:
|
||||
return "%d %s" % (n, unit) if unit == "B" else "%.1f %s" % (n, unit)
|
||||
n /= 1024.0
|
||||
return "%.1f GB" % n
|
||||
|
||||
|
||||
# -- sanity run ----------------------------------------------------------------
|
||||
STATUS_COLOUR = {"passed": GOOD, "failed": BAD, "error": BAD, "cancelled": WARN, "queued": ACCENT,
|
||||
"running": ACCENT}
|
||||
|
||||
|
||||
def status_pill(job, jstate):
|
||||
if jstate == "orphaned":
|
||||
return pill("RUNNER LOST", WARN)
|
||||
st = job.get("status", "?")
|
||||
return pill(st.upper(), STATUS_COLOUR.get(st, ACCENT))
|
||||
|
||||
|
||||
def step_glyph(status, jstate):
|
||||
if status == "running":
|
||||
return Text("▲", style="bold " + WARN) if jstate == "orphaned" else Text(spinner(), style="bold " + ACCENT)
|
||||
return {"pending": Text("·", style=DIM), "done": Text("✔", style="bold " + GOOD),
|
||||
"failed": Text("✘", style="bold " + BAD), "cancelled": Text("–", style=WARN),
|
||||
"skipped": Text("–", style=DIM)}.get(status, Text("?"))
|
||||
|
||||
|
||||
def bar(frac, width, colour=ACCENT):
|
||||
"""A thin progress bar; frac None sweeps back and forth (duration unknown)."""
|
||||
if frac is None:
|
||||
pos = int(time.time() * 12) % (2 * width)
|
||||
pos = pos if pos < width else 2 * width - pos - 1
|
||||
lo, hi = max(0, pos - 2), min(width, pos + 3)
|
||||
return Text.assemble(("━" * lo, "grey23"), ("━" * (hi - lo), colour), ("━" * (width - hi), "grey23"))
|
||||
n = int(round(max(0.0, min(1.0, frac)) * width))
|
||||
return Text.assemble(("━" * n, colour), ("━" * (width - n), "grey23"))
|
||||
|
||||
|
||||
def step_bar(s, width=26):
|
||||
if s.get("kind") != "sanity" or s["status"] in ("pending", "skipped"):
|
||||
return Text("")
|
||||
if s["status"] == "failed":
|
||||
return bar(1.0, width, BAD)
|
||||
if s["status"] != "running":
|
||||
return bar(1.0, width, GOOD)
|
||||
est = s.get("est")
|
||||
if not est or not s.get("t0"):
|
||||
return bar(None, width)
|
||||
return bar(min(0.99, (time.time() - s["t0"]) / est), width)
|
||||
|
||||
|
||||
def steps_table(job, jstate):
|
||||
t = Table.grid(padding=(0, 2))
|
||||
for _ in range(5):
|
||||
t.add_column(no_wrap=True)
|
||||
for s in job["steps"]:
|
||||
st = s["status"]
|
||||
el = ((s.get("t1") or time.time()) - s["t0"]) if s.get("t0") else None
|
||||
timing = fmt_dur(el) if el is not None else ("~" + fmt_dur(s["est"]) if s.get("est") else "")
|
||||
if st == "running" and s.get("kind") == "sanity" and s.get("est"):
|
||||
timing = "%s / ~%s" % (fmt_dur(el), fmt_dur(s["est"]))
|
||||
label_style = DIM if st in ("pending", "skipped") else "bold" if st == "running" else ""
|
||||
detail = Text(s.get("detail") or "", style=BAD if st == "failed" else DIM)
|
||||
t.add_row(step_glyph(st, jstate), Text(s["label"], style=label_style), step_bar(s),
|
||||
Text(timing, style=ACCENT if st == "running" else DIM), detail)
|
||||
return t
|
||||
|
||||
|
||||
def run_heading(job, jstate):
|
||||
start = job.get("started") or job["created"]
|
||||
end = job.get("finished") or time.time()
|
||||
top = Table.grid(expand=True)
|
||||
top.add_column()
|
||||
top.add_column(justify="right")
|
||||
top.add_row(Text.assemble(("Run %s " % job["id"], "bold"), status_pill(job, jstate)),
|
||||
Text("started %s · elapsed %s" % (fmt_clock(start), fmt_dur(end - start)), style=DIM))
|
||||
if job["mode"] == "checkin":
|
||||
mode = Text.assemble(("on pass ", DIM), ("check in", "bold " + GOOD))
|
||||
if job.get("tag"):
|
||||
mode.append_text(Text.assemble((" → tag ", DIM), (job["tag"], "bold " + HOT)))
|
||||
mode.append_text(Text.assemble((" “%s”" % job.get("msg", ""), "")))
|
||||
else:
|
||||
mode = Text.assemble(("on pass ", DIM), ("release locks only", "bold " + WARN),
|
||||
(" (check in later with c)", DIM))
|
||||
files = job["files"] + job["new_files"]
|
||||
who = Text.assemble(("files ", DIM), (", ".join(files), ""),
|
||||
(" locked by run: %d" % len(job.get("locked_by_job", [])), ACCENT))
|
||||
return Group(top, mode, who)
|
||||
|
||||
|
||||
class RunPanel(Vertical):
|
||||
"""The Sanity run tab: step list with progress bars and a live tail of the current log."""
|
||||
|
||||
def compose(self):
|
||||
yield Static(EMPTY_RUN, id="run-empty")
|
||||
yield Static(id="run-head")
|
||||
yield Static(id="run-steps")
|
||||
yield Static(id="run-summary")
|
||||
yield RichLog(id="run-log", max_lines=4000, wrap=False, auto_scroll=True)
|
||||
|
||||
def on_mount(self):
|
||||
self.tail = Tail()
|
||||
self.show(None, "none", {})
|
||||
|
||||
def show(self, job, jstate, _unused=None):
|
||||
has = job is not None
|
||||
for wid in ("#run-head", "#run-steps", "#run-summary", "#run-log"):
|
||||
self.query_one(wid).display = has
|
||||
self.query_one("#run-empty").display = not has
|
||||
if not has:
|
||||
return
|
||||
self.query_one("#run-head", Static).update(run_heading(job, jstate))
|
||||
self.query_one("#run-steps", Static).update(steps_table(job, jstate))
|
||||
summary = self.query_one("#run-summary", Static)
|
||||
if jstate == "orphaned":
|
||||
summary.update(Text("▲ No heartbeat from the runner for %s - it may have been killed. "
|
||||
"Press x to stop its simulation and release the %d lock(s) it took." % (
|
||||
fmt_dur(time.time() - job.get("heartbeat", 0)),
|
||||
len(job.get("locked_by_job", []))), style="bold " + WARN))
|
||||
elif jstate == "done" and job.get("summary"):
|
||||
summary.update(Text(job["summary"], style="bold " + (GOOD if job["status"] == "passed" else BAD)))
|
||||
else:
|
||||
summary.update("")
|
||||
logs = [s for s in job["steps"] if s.get("kind") == "sanity" and s.get("log") and s["status"] != "pending"]
|
||||
log = self.query_one("#run-log", RichLog)
|
||||
if logs:
|
||||
log.border_title = "log · %s" % os.path.basename(logs[-1]["log"])
|
||||
self.tail.poll(logs[-1]["log"], log)
|
||||
else:
|
||||
log.border_title = "log"
|
||||
|
||||
|
||||
EMPTY_RUN = Text.assemble(
|
||||
("No sanity run yet.\n\n", "bold"),
|
||||
("1. In ", DIM), ("Changes", "bold"), (", mark files with ", DIM), ("space", "bold " + ACCENT),
|
||||
(" (no marks = the highlighted row).\n", DIM),
|
||||
("2. Press ", DIM), ("s", "bold " + ACCENT),
|
||||
(": the files are locked, sanity runs on every config, and on pass\n"
|
||||
" they are checked in (or just unlocked). Locks are always released.\n", DIM),
|
||||
("3. Follow it here, or from any shell: ", DIM), ("dsflow_tui.py status", "bold"))
|
||||
|
||||
|
||||
# -- logs ------------------------------------------------------------------------
|
||||
def log_line(line):
|
||||
low = line.lower()
|
||||
style = BAD if ("error" in low or "fail" in low) else GOOD if ("pass" in low) else ""
|
||||
return Text(line, style=style)
|
||||
|
||||
|
||||
class Tail(object):
|
||||
"""Follows one file into a RichLog: the last 256 KB first, then whatever gets appended."""
|
||||
|
||||
MAX_START = 256 * 1024
|
||||
|
||||
def __init__(self):
|
||||
self.path, self.pos, self.ino, self.partial = None, 0, None, ""
|
||||
|
||||
def poll(self, path, log):
|
||||
try:
|
||||
st = os.stat(path)
|
||||
except OSError:
|
||||
st = None
|
||||
if path != self.path or st is None or st.st_ino != self.ino or st.st_size < self.pos:
|
||||
log.clear()
|
||||
self.path, self.pos, self.partial = path, 0, ""
|
||||
self.ino = st.st_ino if st else None
|
||||
if st is None:
|
||||
log.write(Text("(%s does not exist yet)" % path, style=DIM))
|
||||
return
|
||||
if st.st_size == self.pos:
|
||||
return
|
||||
start = max(self.pos, st.st_size - self.MAX_START)
|
||||
with open(path, "rb") as fh:
|
||||
fh.seek(start)
|
||||
data = self.partial + fh.read().decode("utf-8", "replace").replace("\r", "")
|
||||
skipped = start > self.pos
|
||||
self.pos = st.st_size
|
||||
lines = data.split("\n")
|
||||
self.partial = lines.pop()
|
||||
if skipped and lines:
|
||||
lines = lines[1:]
|
||||
for line in lines:
|
||||
log.write(log_line(line.expandtabs(4)))
|
||||
|
||||
|
||||
class LogPanel(Vertical):
|
||||
"""The Logs tab: one source at a time (sanity per config, the runner, this session's activity)."""
|
||||
|
||||
def __init__(self, sources_fn, activity):
|
||||
super().__init__()
|
||||
self.sources_fn = sources_fn
|
||||
self.activity = activity
|
||||
self.shown_activity = 0
|
||||
self.source = "activity"
|
||||
|
||||
def compose(self):
|
||||
with Horizontal(id="log-bar"):
|
||||
yield Label("source", classes="log-label")
|
||||
yield Select(self.options(), value="activity", allow_blank=False, id="log-source")
|
||||
yield RichLog(id="log-view", max_lines=20000, wrap=False, auto_scroll=True)
|
||||
|
||||
def on_mount(self):
|
||||
self.tail = Tail()
|
||||
|
||||
def options(self):
|
||||
return [(name, name) for name, _ in self.sources_fn()]
|
||||
|
||||
def on_select_changed(self, event):
|
||||
if event.value != self.source and event.value is not Select.BLANK:
|
||||
self.source = event.value
|
||||
self.tail = Tail()
|
||||
self.shown_activity = 0
|
||||
self.query_one("#log-view", RichLog).clear()
|
||||
self.tick()
|
||||
|
||||
def sync_sources(self):
|
||||
select = self.query_one("#log-source", Select)
|
||||
opts = self.options()
|
||||
if [v for _, v in opts] != getattr(self, "_opts", None):
|
||||
self._opts = [v for _, v in opts]
|
||||
select.set_options(opts)
|
||||
select.value = self.source if self.source in self._opts else "activity"
|
||||
|
||||
def tick(self):
|
||||
log = self.query_one("#log-view", RichLog)
|
||||
if self.source == "activity":
|
||||
for ts, kind, text in self.activity[self.shown_activity:]:
|
||||
style = {"error": BAD, "warning": WARN, "information": ""}.get(kind, DIM)
|
||||
log.write(Text.assemble((fmt_clock(ts) + " ", DIM), (text, style)))
|
||||
self.shown_activity = len(self.activity)
|
||||
return
|
||||
path = dict(self.sources_fn()).get(self.source)
|
||||
if path:
|
||||
self.tail.poll(path, log)
|
||||
|
||||
|
||||
# -- bottom status line ------------------------------------------------------------
|
||||
def run_bar(job, jstate, n_marked):
|
||||
right = Text("%d marked" % n_marked, style=ACCENT if n_marked else DIM)
|
||||
if jstate == "none":
|
||||
left = Text("○ no sanity run yet", style=DIM)
|
||||
elif jstate == "orphaned":
|
||||
left = Text("▲ runner lost - press x to release %d lock(s)" % len(job.get("locked_by_job", [])),
|
||||
style="bold " + WARN)
|
||||
elif jstate == "active":
|
||||
steps = job["steps"]
|
||||
cur = next((s for s in steps if s["status"] == "running"), None)
|
||||
san = [s for s in steps if s.get("kind") == "sanity"]
|
||||
done = sum(1 for s in san if s["status"] == "done")
|
||||
frac = 0.0
|
||||
if cur is not None and cur.get("kind") == "sanity" and cur.get("est") and cur.get("t0"):
|
||||
frac = min(0.99, (time.time() - cur["t0"]) / cur["est"])
|
||||
overall = (done + frac) / len(san) if san else 0
|
||||
left = Text.assemble(pill("%s SANITY" % spinner(), ACCENT), (" %s " % (cur["label"] if cur else "starting"),
|
||||
"bold"),
|
||||
bar(overall if (done or frac) else None, 16),
|
||||
(" %d/%d cfg" % (done, len(san)), ACCENT),
|
||||
(" · %s" % fmt_dur(time.time() - (job.get("started") or job["created"])), DIM),
|
||||
(" · %d locked by run" % len(job.get("locked_by_job", [])), DIM))
|
||||
else:
|
||||
left = Text.assemble(("last run ", DIM), status_pill(job, jstate),
|
||||
(" %s " % fmt_ago(job.get("finished")), DIM), (job.get("summary", ""), DIM))
|
||||
grid = Table.grid(expand=True)
|
||||
grid.add_column(no_wrap=True, overflow="ellipsis", ratio=1)
|
||||
grid.add_column(no_wrap=True, justify="right")
|
||||
grid.add_row(left, right)
|
||||
return grid
|
||||
+7
-2474
File diff suppressed because it is too large.
Load diff
+10
-1
@@ -11,7 +11,16 @@ import time
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), ".."))
|
||||
import dsflow_tui as d # noqa: E402
|
||||
from dsflow import common, demo, flow, runner # noqa: E402
|
||||
|
||||
|
||||
class d(object):
|
||||
"""The names the tests use, gathered from the package modules."""
|
||||
ALL_CHANGES_SH, Flow = flow.ALL_CHANGES_SH, flow.Flow
|
||||
JOB_CANCEL, JOB_FILE, ME = common.JOB_CANCEL, common.JOB_FILE, common.ME
|
||||
job_state, read_json = staticmethod(common.job_state), staticmethod(common.read_json)
|
||||
new_job, spawn_runner = staticmethod(runner.new_job), staticmethod(runner.spawn_runner)
|
||||
setup_demo = staticmethod(demo.setup_demo)
|
||||
|
||||
RUN_TIMEOUT = 60
|
||||
|
||||
|
||||
@@ -0,0 +1,123 @@
|
||||
"""UI tests: drive the Textual app headlessly (Textual's pilot) against the demo sandbox.
|
||||
|
||||
tools/guard.py -- python3 -m unittest discover -s tests -v
|
||||
"""
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
|
||||
ROOT = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..")
|
||||
sys.path[:0] = [ROOT, os.path.join(ROOT, "vendor")]
|
||||
from dsflow.demo import setup_demo # noqa: E402
|
||||
from dsflow.flow import Flow # noqa: E402
|
||||
from dsflow.ui.app import DsflowApp # noqa: E402
|
||||
from dsflow.ui.dialogs import MessageDialog, SanityDialog # noqa: E402
|
||||
|
||||
SIZE = (130, 40)
|
||||
|
||||
|
||||
class UICase(unittest.IsolatedAsyncioTestCase):
|
||||
def setUp(self):
|
||||
self.base = tempfile.mkdtemp(prefix="dsflow_ui_test-")
|
||||
self.env = dict(os.environ)
|
||||
os.environ.update(DEMO_STEP_SECS="0.05", DEMO_SANITY_TESTS="3")
|
||||
os.environ.pop("DEMO_FAIL", None)
|
||||
ws, conf = setup_demo(self.base, True)
|
||||
self.flow = Flow(ws, conf)
|
||||
self.flow.load_vars()
|
||||
|
||||
def tearDown(self):
|
||||
os.environ.clear()
|
||||
os.environ.update(self.env)
|
||||
for root, dirs, files in os.walk(self.base):
|
||||
for n in dirs + files:
|
||||
os.chmod(os.path.join(root, n), 0o755)
|
||||
shutil.rmtree(self.base)
|
||||
|
||||
async def until(self, pilot, cond, timeout=30):
|
||||
deadline = time.time() + timeout
|
||||
while not cond():
|
||||
self.assertLess(time.time(), deadline, "condition not reached")
|
||||
await pilot.pause(0.1)
|
||||
|
||||
async def ready(self, pilot, app):
|
||||
await self.until(pilot, lambda: app.snap is not None)
|
||||
await pilot.pause(0.2)
|
||||
|
||||
|
||||
class MainScreenTest(UICase):
|
||||
async def test_lists_changes_and_marks_with_space(self):
|
||||
app = DsflowApp(self.flow)
|
||||
async with app.run_test(size=SIZE) as pilot:
|
||||
await self.ready(pilot, app)
|
||||
table = app.table("changes")
|
||||
self.assertIs(app.focused, table) # never the hidden filter input
|
||||
self.assertEqual(table.row_count, 5)
|
||||
await pilot.press("space", "space")
|
||||
self.assertEqual(app.marks, {"rtl/rx/rx_fsm.sv", "rtl/top/wifi_mac_top.sv"})
|
||||
await pilot.press("escape")
|
||||
self.assertEqual(app.marks, set())
|
||||
|
||||
async def test_filter_narrows_the_table(self):
|
||||
app = DsflowApp(self.flow)
|
||||
async with app.run_test(size=SIZE) as pilot:
|
||||
await self.ready(pilot, app)
|
||||
await pilot.press("slash", *"tx_")
|
||||
await pilot.pause(0.1)
|
||||
self.assertEqual([r["path"] for r in app.table("changes").file_rows],
|
||||
["rtl/tx/tx_ctrl.sv", "rtl/tx/tx_fifo.sv"])
|
||||
await pilot.press("escape")
|
||||
self.assertEqual(app.table("changes").row_count, 5)
|
||||
|
||||
async def test_stale_file_is_refused_with_a_dialog(self):
|
||||
app = DsflowApp(self.flow)
|
||||
async with app.run_test(size=SIZE) as pilot:
|
||||
await self.ready(pilot, app)
|
||||
await pilot.press("down", "down", "s") # rtl/tx/tx_ctrl.sv is stale in the demo
|
||||
await pilot.pause(0.2)
|
||||
self.assertIsInstance(app.screen, MessageDialog)
|
||||
|
||||
|
||||
class SanityRunTest(UICase):
|
||||
async def test_run_from_dialog_checks_in_and_releases_locks(self):
|
||||
app = DsflowApp(self.flow)
|
||||
async with app.run_test(size=SIZE) as pilot:
|
||||
await self.ready(pilot, app)
|
||||
await pilot.press("space", "s")
|
||||
await pilot.pause(0.3)
|
||||
self.assertIsInstance(app.screen, SanityDialog)
|
||||
await pilot.press("enter") # empty comment: refused, dialog stays
|
||||
await pilot.pause(0.1)
|
||||
self.assertIsInstance(app.screen, SanityDialog)
|
||||
await pilot.press(*"fix rx fsm", "enter")
|
||||
await self.until(pilot, lambda: app.jstate == "active")
|
||||
await pilot.pause(0.3)
|
||||
self.assertEqual(app.tab(), "sanity")
|
||||
await self.until(pilot, lambda: app.jstate == "done", 60)
|
||||
self.assertEqual(app.job["status"], "passed", app.job.get("summary"))
|
||||
self.assertTrue(app.job["checked_in"])
|
||||
self.assertEqual(self.flow.holders(["rtl/rx/rx_fsm.sv"]), {"rtl/rx/rx_fsm.sv": ""})
|
||||
|
||||
async def test_cancel_from_the_ui(self):
|
||||
os.environ.update(DEMO_STEP_SECS="2", DEMO_SANITY_TESTS="30")
|
||||
app = DsflowApp(self.flow)
|
||||
async with app.run_test(size=SIZE) as pilot:
|
||||
await self.ready(pilot, app)
|
||||
await pilot.press("space", "s")
|
||||
await pilot.pause(0.3)
|
||||
await pilot.press(*"wip", "enter")
|
||||
await self.until(pilot, lambda: app.jstate == "active" and any(
|
||||
s["status"] == "running" and s.get("kind") == "sanity" for s in app.job["steps"]))
|
||||
await pilot.press("x")
|
||||
await pilot.pause(0.3)
|
||||
await pilot.press("enter") # confirm
|
||||
await self.until(pilot, lambda: app.jstate == "done", 60)
|
||||
self.assertEqual(app.job["status"], "cancelled")
|
||||
self.assertEqual(self.flow.holders(["rtl/rx/rx_fsm.sv"]), {"rtl/rx/rx_fsm.sv": ""})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Executable
+73
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Regenerate docs/screenshots/*.svg by driving the demo headlessly.
|
||||
|
||||
tools/guard.py -- python3 tools/screenshots.py
|
||||
"""
|
||||
import asyncio
|
||||
import os
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path[:0] = [ROOT, os.path.join(ROOT, "vendor")]
|
||||
os.environ["USER"] = "designer" # neutral name in the published images; read at import time
|
||||
from dsflow.demo import setup_demo # noqa: E402
|
||||
from dsflow.flow import Flow # noqa: E402
|
||||
from dsflow.ui.app import DsflowApp # noqa: E402
|
||||
|
||||
OUT = os.path.join(ROOT, "docs", "screenshots")
|
||||
SIZE = (120, 34)
|
||||
|
||||
|
||||
async def until(pilot, cond, timeout=60):
|
||||
deadline = time.time() + timeout
|
||||
while not cond():
|
||||
if time.time() > deadline:
|
||||
raise SystemExit("screenshots: timed out")
|
||||
await pilot.pause(0.1)
|
||||
|
||||
|
||||
async def shoot(flow):
|
||||
app = DsflowApp(flow)
|
||||
async with app.run_test(size=SIZE) as pilot:
|
||||
app.sub_title = "demo sandbox · Trunk:Latest · green tag working" # not the temp path
|
||||
await until(pilot, lambda: app.snap is not None)
|
||||
await pilot.pause(0.3)
|
||||
await pilot.press("space", "space", "up")
|
||||
await pilot.pause(0.3)
|
||||
app.save_screenshot("changes.svg", OUT)
|
||||
await pilot.press("s")
|
||||
await pilot.pause(0.4)
|
||||
await pilot.press(*"fix rx fsm corner case")
|
||||
app.save_screenshot("run-dialog.svg", OUT)
|
||||
await pilot.press("enter")
|
||||
await until(pilot, lambda: app.jstate == "active" and any(
|
||||
s["status"] == "running" and s.get("kind") == "sanity" for s in app.job["steps"]))
|
||||
await pilot.pause(2.5)
|
||||
app.save_screenshot("sanity-run.svg", OUT)
|
||||
await until(pilot, lambda: app.jstate == "done")
|
||||
await pilot.pause(0.5)
|
||||
app.save_screenshot("sanity-passed.svg", OUT)
|
||||
|
||||
|
||||
def main():
|
||||
base = tempfile.mkdtemp(prefix="dsflow_shots-")
|
||||
os.environ.update(DEMO_STEP_SECS="0.5", DEMO_SANITY_TESTS="8")
|
||||
try:
|
||||
ws, conf = setup_demo(base, True)
|
||||
flow = Flow(ws, conf)
|
||||
flow.load_vars()
|
||||
os.makedirs(OUT, exist_ok=True)
|
||||
asyncio.run(shoot(flow))
|
||||
print("wrote", ", ".join(sorted(os.listdir(OUT))))
|
||||
finally:
|
||||
for root, dirs, files in os.walk(base):
|
||||
for n in dirs + files:
|
||||
os.chmod(os.path.join(root, n), 0o755)
|
||||
shutil.rmtree(base)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+54
@@ -0,0 +1,54 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Refresh vendor/ from vendor/requirements.txt. Needs internet; the servers never run this.
|
||||
|
||||
tools/vendor.py
|
||||
|
||||
Downloads the pinned pure-Python wheels for the oldest supported Python
|
||||
(PY_FLOOR), unpacks them into vendor/ (licenses included, via dist-info)
|
||||
and rewrites vendor/VERSIONS.txt. dsflow_tui.py puts vendor/ first on
|
||||
sys.path, so a plain checkout runs with no pip and no network.
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import zipfile
|
||||
|
||||
PY_FLOOR = "3.8.10"
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
VENDOR = os.path.join(ROOT, "vendor")
|
||||
REQS = os.path.join(VENDOR, "requirements.txt")
|
||||
KEEP = ("requirements.txt", "README.md", "VERSIONS.txt")
|
||||
|
||||
|
||||
def main():
|
||||
tmp = tempfile.mkdtemp(prefix="dsflow-vendor-")
|
||||
try:
|
||||
subprocess.check_call([sys.executable, "-m", "pip", "download", "--quiet", "--no-deps",
|
||||
"-r", REQS, "-d", tmp, "--only-binary=:all:",
|
||||
"--python-version", PY_FLOOR, "--implementation", "py", "--platform", "any"])
|
||||
for name in os.listdir(VENDOR):
|
||||
if name not in KEEP:
|
||||
path = os.path.join(VENDOR, name)
|
||||
shutil.rmtree(path) if os.path.isdir(path) else os.remove(path)
|
||||
versions = []
|
||||
for whl in sorted(glob.glob(os.path.join(tmp, "*.whl"))):
|
||||
if not whl.endswith("-py3-none-any.whl") and not whl.endswith("-py2.py3-none-any.whl"):
|
||||
sys.exit("vendor: %s is not pure Python - it would not run on every host" % whl)
|
||||
with zipfile.ZipFile(whl) as zf:
|
||||
zf.extractall(VENDOR)
|
||||
versions.append("-".join(os.path.basename(whl).split("-")[:2]))
|
||||
for cache in glob.glob(os.path.join(VENDOR, "**", "__pycache__"), recursive=True):
|
||||
shutil.rmtree(cache)
|
||||
with open(os.path.join(VENDOR, "VERSIONS.txt"), "w") as fh:
|
||||
fh.write("# generated by tools/vendor.py for Python >= %s\n" % PY_FLOOR)
|
||||
fh.write("\n".join(versions) + "\n")
|
||||
print("vendored %d packages into %s" % (len(versions), VENDOR))
|
||||
finally:
|
||||
shutil.rmtree(tmp)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
# generated by tools/vendor.py for Python >= 3.8.10
|
||||
linkify_it_py-2.0.3
|
||||
markdown_it_py-3.0.0
|
||||
mdit_py_plugins-0.4.2
|
||||
mdurl-0.1.2
|
||||
platformdirs-4.3.6
|
||||
pygments-2.19.2
|
||||
rich-14.3.4
|
||||
textual-6.2.1
|
||||
typing_extensions-4.13.2
|
||||
uc_micro_py-1.0.3
|
||||
Vendored
+4
@@ -0,0 +1,4 @@
|
||||
from .main import LinkifyIt # noqa: F401p
|
||||
from .main import SchemaError # noqa: F401p
|
||||
|
||||
__version__ = "2.0.3"
|
||||
Vendored
+642
@@ -0,0 +1,642 @@
|
||||
import copy
|
||||
import re
|
||||
import types
|
||||
|
||||
from .ucre import build_re
|
||||
|
||||
# py>=37: re.Pattern, else: _sre.SRE_Pattern
|
||||
RE_TYPE = type(re.compile(r""))
|
||||
|
||||
|
||||
def _escape_re(string):
|
||||
return re.sub(r"([.?*+^$[\]\\(){}|-])", r"\\\1", string)
|
||||
|
||||
|
||||
def _index_of(text, search_value):
|
||||
try:
|
||||
result = text.index(search_value)
|
||||
except ValueError:
|
||||
result = -1
|
||||
|
||||
return result
|
||||
|
||||
|
||||
class SchemaError(Exception):
|
||||
"""Linkify schema error"""
|
||||
|
||||
def __init__(self, name, val):
|
||||
message = "(LinkifyIt) Invalid schema '{}': '{}'".format(name, val)
|
||||
super().__init__(message)
|
||||
|
||||
|
||||
class Match:
|
||||
"""Match result.
|
||||
|
||||
Attributes:
|
||||
schema (str): Prefix (protocol) for matched string.
|
||||
index (int): First position of matched string.
|
||||
last_index (int): Next position after matched string.
|
||||
raw (str): Matched string.
|
||||
text (str): Notmalized text of matched string.
|
||||
url (str): Normalized url of matched string.
|
||||
|
||||
Args:
|
||||
linkifyit (:class:`linkify_it.main.LinkifyIt`) LinkifyIt object
|
||||
shift (int): text searh position
|
||||
"""
|
||||
|
||||
def __repr__(self):
|
||||
return "{}.{}({!r})".format(
|
||||
self.__class__.__module__, self.__class__.__name__, self.__dict__
|
||||
)
|
||||
|
||||
def __init__(self, linkifyit, shift):
|
||||
start = linkifyit._index
|
||||
end = linkifyit._last_index
|
||||
text = linkifyit._text_cache[start:end]
|
||||
|
||||
self.schema = linkifyit._schema.lower()
|
||||
self.index = start + shift
|
||||
self.last_index = end + shift
|
||||
self.raw = text
|
||||
self.text = text
|
||||
self.url = text
|
||||
|
||||
|
||||
class LinkifyIt:
|
||||
"""Creates new linkifier instance with optional additional schemas.
|
||||
|
||||
By default understands:
|
||||
|
||||
- ``http(s)://...`` , ``ftp://...``, ``mailto:...`` & ``//...`` links
|
||||
- "fuzzy" links and emails (example.com, foo@bar.com).
|
||||
|
||||
``schemas`` is an dict where each key/value describes protocol/rule:
|
||||
|
||||
- **key** - link prefix (usually, protocol name with ``:`` at the end, ``skype:``
|
||||
for example). `linkify-it` makes shure that prefix is not preceeded with
|
||||
alphanumeric char. Only whitespaces and punctuation allowed.
|
||||
|
||||
- **value** - rule to check tail after link prefix
|
||||
|
||||
- *str* - just alias to existing rule
|
||||
- *dict*
|
||||
|
||||
- *validate* - either a ``re.Pattern``, ``re str`` (start with ``^``, and don't
|
||||
include the link prefix itself), or a validator ``function`` which, given
|
||||
arguments *self*, *text* and *pos* returns the length of a match in *text*
|
||||
starting at index *pos*. *pos* is the index right after the link prefix.
|
||||
- *normalize* - optional function to normalize text & url of matched
|
||||
result (for example, for @twitter mentions).
|
||||
|
||||
``options`` is an dict:
|
||||
|
||||
- **fuzzyLink** - recognige URL-s without ``http(s):`` prefix. Default ``True``.
|
||||
- **fuzzyIP** - allow IPs in fuzzy links above. Can conflict with some texts
|
||||
like version numbers. Default ``False``.
|
||||
- **fuzzyEmail** - recognize emails without ``mailto:`` prefix.
|
||||
- **---** - set `True` to terminate link with `---` (if it's considered as long
|
||||
dash).
|
||||
|
||||
Args:
|
||||
schemas (dict): Optional. Additional schemas to validate (prefix/validator)
|
||||
options (dict): { fuzzy_link | fuzzy_email | fuzzy_ip: True | False }.
|
||||
Default: {"fuzzy_link": True, "fuzzy_email": True, "fuzzy_ip": False}.
|
||||
"""
|
||||
|
||||
def _validate_http(self, text, pos):
|
||||
tail = text[pos:]
|
||||
if not self.re.get("http"):
|
||||
# compile lazily, because "host"-containing variables can change on
|
||||
# tlds update.
|
||||
self.re["http"] = (
|
||||
"^\\/\\/"
|
||||
+ self.re["src_auth"]
|
||||
+ self.re["src_host_port_strict"]
|
||||
+ self.re["src_path"]
|
||||
)
|
||||
|
||||
founds = re.search(self.re["http"], tail, flags=re.IGNORECASE)
|
||||
if founds:
|
||||
return len(founds.group())
|
||||
|
||||
return 0
|
||||
|
||||
def _validate_double_slash(self, text, pos):
|
||||
tail = text[pos:]
|
||||
|
||||
if not self.re.get("not_http"):
|
||||
# compile lazily, because "host"-containing variables can change on
|
||||
# tlds update.
|
||||
self.re["not_http"] = (
|
||||
"^"
|
||||
+ self.re["src_auth"]
|
||||
+ "(?:localhost|(?:(?:"
|
||||
+ self.re["src_domain"]
|
||||
+ ")\\.)+"
|
||||
+ self.re["src_domain_root"]
|
||||
+ ")"
|
||||
+ self.re["src_port"]
|
||||
+ self.re["src_host_terminator"]
|
||||
+ self.re["src_path"]
|
||||
)
|
||||
|
||||
founds = re.search(self.re["not_http"], tail, flags=re.IGNORECASE)
|
||||
if founds:
|
||||
if pos >= 3 and text[pos - 3] == ":":
|
||||
return 0
|
||||
|
||||
if pos >= 3 and text[pos - 3] == "/":
|
||||
return 0
|
||||
|
||||
return len(founds.group(0))
|
||||
|
||||
return 0
|
||||
|
||||
def _validate_mailto(self, text, pos):
|
||||
tail = text[pos:]
|
||||
|
||||
if not self.re.get("mailto"):
|
||||
self.re["mailto"] = (
|
||||
"^" + self.re["src_email_name"] + "@" + self.re["src_host_strict"]
|
||||
)
|
||||
|
||||
founds = re.search(self.re["mailto"], tail, flags=re.IGNORECASE)
|
||||
if founds:
|
||||
return len(founds.group(0))
|
||||
|
||||
return 0
|
||||
|
||||
def _reset_scan_cache(self):
|
||||
self._index = -1
|
||||
self._text_cache = ""
|
||||
|
||||
def _create_validator(self, regex):
|
||||
def func(text, pos):
|
||||
tail = text[pos:]
|
||||
if isinstance(regex, str):
|
||||
founds = re.search(regex, tail, flags=re.IGNORECASE)
|
||||
else:
|
||||
# re.Pattern
|
||||
founds = re.search(regex, tail)
|
||||
|
||||
if founds:
|
||||
return len(founds.group(0))
|
||||
|
||||
return 0
|
||||
|
||||
return func
|
||||
|
||||
def _create_normalizer(self):
|
||||
def func(match):
|
||||
self.normalize(match)
|
||||
|
||||
return func
|
||||
|
||||
def _create_match(self, shift):
|
||||
match = Match(self, shift)
|
||||
self._compiled[match.schema]["normalize"](match)
|
||||
return match
|
||||
|
||||
def __init__(self, schemas=None, options=None):
|
||||
self.default_options = {
|
||||
"fuzzy_link": True,
|
||||
"fuzzy_email": True,
|
||||
"fuzzy_ip": False,
|
||||
}
|
||||
|
||||
self.default_schemas = {
|
||||
"http:": {"validate": self._validate_http},
|
||||
"https:": "http:",
|
||||
"ftp:": "http:",
|
||||
"//": {"validate": self._validate_double_slash},
|
||||
"mailto:": {"validate": self._validate_mailto},
|
||||
}
|
||||
|
||||
# RE pattern for 2-character tlds (autogenerated by ./support/tlds_2char_gen.js)
|
||||
self.tlds_2ch_src_re = "a[cdefgilmnoqrstuwxz]|b[abdefghijmnorstvwyz]|c[acdfghiklmnoruvwxyz]|d[ejkmoz]|e[cegrstu]|f[ijkmor]|g[abdefghilmnpqrstuwy]|h[kmnrtu]|i[delmnoqrst]|j[emop]|k[eghimnprwyz]|l[abcikrstuvy]|m[acdeghklmnopqrstuvwxyz]|n[acefgilopruz]|om|p[aefghklmnrstwy]|qa|r[eosuw]|s[abcdeghijklmnortuvxyz]|t[cdfghjklmnortvwz]|u[agksyz]|v[aceginu]|w[fs]|y[et]|z[amw]" # noqa: E501
|
||||
|
||||
# DON'T try to make PRs with changes. Extend TLDs with LinkifyIt.tlds() instead
|
||||
self.tlds_default = "biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф".split( # noqa: E501
|
||||
"|"
|
||||
)
|
||||
|
||||
if options:
|
||||
self.default_options.update(options)
|
||||
self._opts = self.default_options
|
||||
else:
|
||||
self._opts = self.default_options
|
||||
|
||||
# Cache last tested result. Used to skip repeating steps on next `match` call.
|
||||
self._index = -1
|
||||
self._last_index = -1 # Next scan position
|
||||
self._schema = ""
|
||||
self._text_cache = ""
|
||||
|
||||
if schemas:
|
||||
self.default_schemas.update(schemas)
|
||||
self._schemas = self.default_schemas
|
||||
else:
|
||||
self._schemas = self.default_schemas
|
||||
|
||||
self._compiled = {}
|
||||
|
||||
self._tlds = self.tlds_default
|
||||
self._tlds_replaced = False
|
||||
|
||||
self.re = {}
|
||||
|
||||
self._compile()
|
||||
|
||||
def _compile(self):
|
||||
"""Schemas compiler. Build regexps."""
|
||||
|
||||
# Load & clone RE patterns.
|
||||
self.re = build_re(self._opts)
|
||||
|
||||
# Define dynamic patterns
|
||||
tlds = copy.deepcopy(self._tlds)
|
||||
|
||||
self._on_compile()
|
||||
|
||||
if not self._tlds_replaced:
|
||||
tlds.append(self.tlds_2ch_src_re)
|
||||
tlds.append(self.re["src_xn"])
|
||||
|
||||
self.re["src_tlds"] = "|".join(tlds)
|
||||
|
||||
def untpl(tpl):
|
||||
return tpl.replace("%TLDS%", self.re["src_tlds"])
|
||||
|
||||
self.re["email_fuzzy"] = untpl(self.re["tpl_email_fuzzy"])
|
||||
|
||||
self.re["link_fuzzy"] = untpl(self.re["tpl_link_fuzzy"])
|
||||
|
||||
self.re["link_no_ip_fuzzy"] = untpl(self.re["tpl_link_no_ip_fuzzy"])
|
||||
|
||||
self.re["host_fuzzy_test"] = untpl(self.re["tpl_host_fuzzy_test"])
|
||||
|
||||
#
|
||||
# Compile each schema
|
||||
#
|
||||
|
||||
aliases = []
|
||||
|
||||
self._compiled = {}
|
||||
|
||||
for name, val in self._schemas.items():
|
||||
# skip disabled methods
|
||||
if val is None:
|
||||
continue
|
||||
|
||||
compiled = {"validate": None, "link": None}
|
||||
|
||||
self._compiled[name] = compiled
|
||||
|
||||
if isinstance(val, dict):
|
||||
if isinstance(val.get("validate"), RE_TYPE):
|
||||
compiled["validate"] = self._create_validator(val.get("validate"))
|
||||
elif isinstance(val.get("validate"), str):
|
||||
compiled["validate"] = self._create_validator(val.get("validate"))
|
||||
elif isinstance(val.get("validate"), types.MethodType):
|
||||
compiled["validate"] = val.get("validate")
|
||||
# Add custom handler
|
||||
elif isinstance(val.get("validate"), types.FunctionType):
|
||||
setattr(LinkifyIt, "func", val.get("validate"))
|
||||
compiled["validate"] = self.func
|
||||
else:
|
||||
raise SchemaError(name, val)
|
||||
|
||||
if isinstance(val.get("normalize"), types.MethodType):
|
||||
compiled["normalize"] = val.get("normalize")
|
||||
# Add custom handler
|
||||
elif isinstance(val.get("normalize"), types.FunctionType):
|
||||
setattr(LinkifyIt, "func", val.get("normalize"))
|
||||
compiled["normalize"] = self.func
|
||||
elif not val.get("normalize"):
|
||||
compiled["normalize"] = self._create_normalizer()
|
||||
else:
|
||||
raise SchemaError(name, val)
|
||||
|
||||
continue
|
||||
|
||||
if isinstance(val, str):
|
||||
aliases.append(name)
|
||||
continue
|
||||
|
||||
raise SchemaError(name, val)
|
||||
|
||||
#
|
||||
# Compile postponed aliases
|
||||
#
|
||||
for alias in aliases:
|
||||
if not self._compiled.get(self._schemas.get(alias)):
|
||||
continue
|
||||
|
||||
self._compiled[alias]["validate"] = self._compiled[self._schemas[alias]][
|
||||
"validate"
|
||||
]
|
||||
self._compiled[alias]["normalize"] = self._compiled[self._schemas[alias]][
|
||||
"normalize"
|
||||
]
|
||||
|
||||
# Fake record for guessed links
|
||||
self._compiled[""] = {"validate": None, "normalize": self._create_normalizer()}
|
||||
|
||||
#
|
||||
# Build schema condition
|
||||
#
|
||||
slist = "|".join(
|
||||
[
|
||||
_escape_re(name)
|
||||
for name, val in self._compiled.items()
|
||||
if len(name) > 0 and val
|
||||
]
|
||||
)
|
||||
|
||||
re_schema_test = (
|
||||
"(^|(?!_)(?:[><\uff5c]|" + self.re["src_ZPCc"] + "))(" + slist + ")"
|
||||
)
|
||||
|
||||
# (?!_) cause 1.5x slowdown
|
||||
self.re["schema_test"] = re_schema_test
|
||||
self.re["schema_search"] = re_schema_test
|
||||
self.re["schema_at_start"] = "^" + self.re["schema_search"]
|
||||
|
||||
self.re["pretest"] = (
|
||||
"(" + re_schema_test + ")|(" + self.re["host_fuzzy_test"] + ")|@"
|
||||
)
|
||||
|
||||
# Cleanup
|
||||
|
||||
self._reset_scan_cache()
|
||||
|
||||
def add(self, schema, definition):
|
||||
"""Add new rule definition. (chainable)
|
||||
|
||||
See :class:`linkify_it.main.LinkifyIt` init description for details.
|
||||
``schema`` is a link prefix (``skype:``, for example), and ``definition``
|
||||
is a ``str`` to alias to another schema, or an ``dict`` with ``validate`` and
|
||||
optionally `normalize` definitions. To disable an existing rule, use
|
||||
``.add(<schema>, None)``.
|
||||
|
||||
Args:
|
||||
schema (str): rule name (fixed pattern prefix)
|
||||
definition (`str` or `re.Pattern`): schema definition
|
||||
|
||||
Return:
|
||||
:class:`linkify_it.main.LinkifyIt`
|
||||
"""
|
||||
self._schemas[schema] = definition
|
||||
self._compile()
|
||||
return self
|
||||
|
||||
def set(self, options):
|
||||
"""Override default options. (chainable)
|
||||
|
||||
Missed properties will not be changed.
|
||||
|
||||
Args:
|
||||
options (dict): ``keys``: [``fuzzy_link`` | ``fuzzy_email`` | ``fuzzy_ip``].
|
||||
``values``: [``True`` | ``False``]
|
||||
|
||||
Return:
|
||||
:class:`linkify_it.main.LinkifyIt`
|
||||
"""
|
||||
self._opts.update(options)
|
||||
return self
|
||||
|
||||
def test(self, text):
|
||||
"""Searches linkifiable pattern and returns ``True`` on success or ``False``
|
||||
on fail.
|
||||
|
||||
Args:
|
||||
text (str): text to search
|
||||
|
||||
Returns:
|
||||
bool: ``True`` if a linkable pattern was found, otherwise it is ``False``.
|
||||
"""
|
||||
self._text_cache = text
|
||||
self._index = -1
|
||||
|
||||
if not len(text):
|
||||
return False
|
||||
|
||||
if re.search(self.re["schema_test"], text, flags=re.IGNORECASE):
|
||||
regex = self.re["schema_search"]
|
||||
last_index = 0
|
||||
matched_iter = re.finditer(regex, text[last_index:], flags=re.IGNORECASE)
|
||||
for matched in matched_iter:
|
||||
last_index = matched.end(0)
|
||||
m = (matched.group(), matched.groups()[0], matched.groups()[1])
|
||||
length = self.test_schema_at(text, m[2], last_index)
|
||||
if length:
|
||||
self._schema = m[2]
|
||||
self._index = matched.start(0) + len(m[1])
|
||||
self._last_index = matched.start(0) + len(m[0]) + length
|
||||
break
|
||||
|
||||
if self._opts.get("fuzzy_link") and self._compiled.get("http:"):
|
||||
# guess schemaless links
|
||||
matched_tld = re.search(
|
||||
self.re["host_fuzzy_test"], text, flags=re.IGNORECASE
|
||||
)
|
||||
if matched_tld:
|
||||
tld_pos = matched_tld.start(0)
|
||||
else:
|
||||
tld_pos = -1
|
||||
if tld_pos >= 0:
|
||||
# if tld is located after found link - no need to check fuzzy pattern
|
||||
if self._index < 0 or tld_pos < self._index:
|
||||
if self._opts.get("fuzzy_ip"):
|
||||
pattern = self.re["link_fuzzy"]
|
||||
else:
|
||||
pattern = self.re["link_no_ip_fuzzy"]
|
||||
|
||||
ml = re.search(pattern, text, flags=re.IGNORECASE)
|
||||
if ml:
|
||||
shift = ml.start(0) + len(ml.groups()[0])
|
||||
|
||||
if self._index < 0 or shift < self._index:
|
||||
self._schema = ""
|
||||
self._index = shift
|
||||
self._last_index = ml.start(0) + len(ml.group())
|
||||
|
||||
if self._opts.get("fuzzy_email") and self._compiled.get("mailto:"):
|
||||
# guess schemaless emails
|
||||
at_pos = _index_of(text, "@")
|
||||
if at_pos >= 0:
|
||||
# We can't skip this check, because this cases are possible:
|
||||
# [email protected], [email protected]
|
||||
me = re.search(self.re["email_fuzzy"], text, flags=re.IGNORECASE)
|
||||
if me:
|
||||
shift = me.start(0) + len(me.groups()[0])
|
||||
next_shift = me.start(0) + len(me.group())
|
||||
|
||||
if (
|
||||
self._index < 0
|
||||
or shift < self._index
|
||||
or (shift == self._index and next_shift > self._last_index)
|
||||
):
|
||||
self._schema = "mailto:"
|
||||
self._index = shift
|
||||
self._last_index = next_shift
|
||||
|
||||
return self._index >= 0
|
||||
|
||||
def pretest(self, text):
|
||||
"""Very quick check, that can give false positives.
|
||||
|
||||
Returns true if link MAY BE can exists. Can be used for speed optimization,
|
||||
when you need to check that link NOT exists.
|
||||
|
||||
Args:
|
||||
text (str): text to search
|
||||
|
||||
Returns:
|
||||
bool: ``True`` if a linkable pattern was found, otherwise it is ``False``.
|
||||
"""
|
||||
if re.search(self.re["pretest"], text, flags=re.IGNORECASE):
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def test_schema_at(self, text, name, position):
|
||||
"""Similar to :meth:`linkify_it.main.LinkifyIt.test` but checks only
|
||||
specific protocol tail exactly at given position.
|
||||
|
||||
Args:
|
||||
text (str): text to scan
|
||||
name (str): rule (schema) name
|
||||
position (int): length of found pattern (0 on fail).
|
||||
|
||||
Returns:
|
||||
int: text (str): text to search
|
||||
"""
|
||||
# If not supported schema check requested - terminate
|
||||
if not self._compiled.get(name.lower()):
|
||||
return 0
|
||||
return self._compiled.get(name.lower()).get("validate")(text, position)
|
||||
|
||||
def match(self, text):
|
||||
"""Returns ``list`` of found link descriptions or ``None`` on fail.
|
||||
|
||||
We strongly recommend to use :meth:`linkify_it.main.LinkifyIt.test`
|
||||
first, for best speed.
|
||||
|
||||
Args:
|
||||
text (str): text to search
|
||||
|
||||
Returns:
|
||||
``list`` or ``None``: Result match description:
|
||||
* **schema** - link schema, can be empty for fuzzy links, or ``//``
|
||||
for protocol-neutral links.
|
||||
* **index** - offset of matched text
|
||||
* **last_index** - offset of matched text
|
||||
* **raw** - offset of matched text
|
||||
* **text** - normalized text
|
||||
* **url** - link, generated from matched text
|
||||
"""
|
||||
shift = 0
|
||||
result = []
|
||||
|
||||
# try to take previous element from cache, if .test() called before
|
||||
if self._index >= 0 and self._text_cache == text:
|
||||
result.append(self._create_match(shift))
|
||||
shift = self._last_index
|
||||
|
||||
# Cut head if cache was used
|
||||
tail = text[shift:] if shift else text
|
||||
|
||||
# Scan string until end reached
|
||||
while self.test(tail):
|
||||
result.append(self._create_match(shift))
|
||||
|
||||
tail = tail[self._last_index :]
|
||||
shift += self._last_index
|
||||
|
||||
if len(result):
|
||||
return result
|
||||
|
||||
return None
|
||||
|
||||
def match_at_start(self, text):
|
||||
"""Returns fully-formed (not fuzzy) link if it starts at the beginning
|
||||
of the string, and null otherwise.
|
||||
|
||||
Args:
|
||||
text (str): text to search
|
||||
|
||||
Retuns:
|
||||
``Match`` or ``None``
|
||||
"""
|
||||
# Reset scan cache
|
||||
self._text_cache = text
|
||||
self._index = -1
|
||||
|
||||
if not len(text):
|
||||
return None
|
||||
|
||||
founds = re.search(self.re["schema_at_start"], text, flags=re.IGNORECASE)
|
||||
if not founds:
|
||||
return None
|
||||
|
||||
m = (founds.group(), founds.groups()[0], founds.groups()[1])
|
||||
length = self.test_schema_at(text, m[2], len(m[0]))
|
||||
if not length:
|
||||
return None
|
||||
|
||||
self._schema = m[2]
|
||||
self._index = founds.start(0) + len(m[1])
|
||||
self._last_index = founds.start(0) + len(m[0]) + length
|
||||
|
||||
return self._create_match(0)
|
||||
|
||||
def tlds(self, list_tlds, keep_old=False):
|
||||
"""Load (or merge) new tlds list. (chainable)
|
||||
|
||||
Those are user for fuzzy links (without prefix) to avoid false positives.
|
||||
By default this algorythm used:
|
||||
|
||||
* hostname with any 2-letter root zones are ok.
|
||||
* biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф
|
||||
are ok.
|
||||
* encoded (`xn--...`) root zones are ok.
|
||||
|
||||
If list is replaced, then exact match for 2-chars root zones will be checked.
|
||||
|
||||
Args:
|
||||
list_tlds (list or str): ``list of tlds`` or ``tlds string``
|
||||
keep_old (bool): merge with current list if q`True`q (q`Falseq` by default)
|
||||
"""
|
||||
_list = list_tlds if isinstance(list_tlds, list) else [list_tlds]
|
||||
|
||||
if not keep_old:
|
||||
self._tlds = _list
|
||||
self._tlds_replaced = True
|
||||
self._compile()
|
||||
return self
|
||||
|
||||
self._tlds.extend(_list)
|
||||
self._tlds = sorted(list(set(self._tlds)), reverse=True)
|
||||
|
||||
self._compile()
|
||||
return self
|
||||
|
||||
def normalize(self, match):
|
||||
"""Default normalizer (if schema does not define it's own).
|
||||
|
||||
Args:
|
||||
match (:class:`linkify_it.main.Match`): Match result
|
||||
"""
|
||||
if not match.schema:
|
||||
match.url = "http://" + match.url
|
||||
|
||||
if match.schema == "mailto:" and not re.search(
|
||||
"^mailto:", match.url, flags=re.IGNORECASE
|
||||
):
|
||||
match.url = "mailto:" + match.url
|
||||
|
||||
def _on_compile(self):
|
||||
"""Override to modify basic RegExp-s."""
|
||||
pass
|
||||
Vendored
+1517
File diff suppressed because it is too large.
Load diff
Vendored
+264
@@ -0,0 +1,264 @@
|
||||
from uc_micro.categories import Cc, Cf, P, Z
|
||||
from uc_micro.properties import Any
|
||||
|
||||
SRC_ANY = Any.REGEX
|
||||
SRC_CC = Cc.REGEX
|
||||
SRC_CF = Cf.REGEX
|
||||
SRC_P = P.REGEX
|
||||
SRC_Z = Z.REGEX
|
||||
|
||||
# \p{\Z\P\Cc\CF} (white spaces + control + format + punctuation)
|
||||
SRC_ZPCC = "|".join([SRC_Z, SRC_P, SRC_CC])
|
||||
|
||||
# \p{\Z\Cc} (white spaces + control)
|
||||
SRC_ZCC = "|".join([SRC_Z, SRC_CC])
|
||||
|
||||
# Experimental. List of chars, completely prohibited in links
|
||||
# because can separate it from other part of text
|
||||
TEXT_SEPARATORS = "[><\uff5c]"
|
||||
|
||||
# All possible word characters (everything without punctuation, spaces & controls)
|
||||
# Defined via punctuation & spaces to save space
|
||||
# Should be something like \p{\L\N\S\M} (\w but without `_`)
|
||||
SRC_PSEUDO_LETTER = "(?:(?!" + TEXT_SEPARATORS + "|" + SRC_ZPCC + ")" + SRC_ANY + ")"
|
||||
# The same as abothe but without [0-9]
|
||||
# var SRC_PSEUDO_LETTER_non_d = '(?:(?![0-9]|' + SRC_ZPCC + ')' + SRC_ANY + ')'
|
||||
|
||||
# =============================================================================
|
||||
|
||||
SRC_IP4 = (
|
||||
"(?:(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|"
|
||||
+ "2[0-4][0-9]|[01]?[0-9][0-9]?)"
|
||||
)
|
||||
|
||||
# Prohibit any of "@/[]()" in user/pass to avoid wrong domain fetch.
|
||||
SRC_AUTH = "(?:(?:(?!" + SRC_ZCC + "|[@/\\[\\]()]).)+@)?"
|
||||
|
||||
SRC_PORT = (
|
||||
"(?::(?:6(?:[0-4]\\d{3}|5(?:[0-4]\\d{2}|5(?:[0-2]\\d|3[0-5])))|[1-5]?\\d{1,4}))?"
|
||||
)
|
||||
|
||||
# Allow anything in markdown spec, forbid quote (") at the first position
|
||||
# because emails enclosed in quotes are far more common
|
||||
SRC_EMAIL_NAME = '[\\-:&=\\+\\$,\\.a-zA-Z0-9_][\\-:&=\\+\\$,\\"\\.a-zA-Z0-9_]*'
|
||||
|
||||
SRC_XN = "xn--[a-z0-9\\-]{1,59}"
|
||||
|
||||
# More to read about domain names
|
||||
# http:#serverfault.com/questions/638260/
|
||||
|
||||
# Allow letters & digits (http:#test1)
|
||||
SRC_DOMAIN_ROOT = "(?:" + SRC_XN + "|" + SRC_PSEUDO_LETTER + "{1,63}" + ")"
|
||||
|
||||
SRC_DOMAIN = (
|
||||
"(?:"
|
||||
+ SRC_XN
|
||||
+ "|"
|
||||
+ "(?:"
|
||||
+ SRC_PSEUDO_LETTER
|
||||
+ ")"
|
||||
+ "|"
|
||||
+ "(?:"
|
||||
+ SRC_PSEUDO_LETTER
|
||||
+ "(?:-|"
|
||||
+ SRC_PSEUDO_LETTER
|
||||
+ "){0,61}"
|
||||
+ SRC_PSEUDO_LETTER
|
||||
+ ")"
|
||||
+ ")"
|
||||
)
|
||||
|
||||
SRC_HOST = (
|
||||
"(?:"
|
||||
+
|
||||
# Don't need IP check, because digits are already allowed in normal domain names
|
||||
# SRC_IP4 +
|
||||
# '|' +
|
||||
"(?:(?:(?:"
|
||||
+ SRC_DOMAIN
|
||||
+ ")\\.)*"
|
||||
+ SRC_DOMAIN # _root
|
||||
+ ")"
|
||||
+ ")"
|
||||
)
|
||||
|
||||
TPL_HOST_FUZZY = (
|
||||
"(?:" + SRC_IP4 + "|" + "(?:(?:(?:" + SRC_DOMAIN + ")\\.)+(?:%TLDS%))" + ")"
|
||||
)
|
||||
|
||||
TPL_HOST_NO_IP_FUZZY = "(?:(?:(?:" + SRC_DOMAIN + ")\\.)+(?:%TLDS%))"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
|
||||
# Rude test fuzzy links by host, for quick deny
|
||||
TPL_HOST_FUZZY_TEST = (
|
||||
"localhost|www\\.|\\.\\d{1,3}\\.|(?:\\.(?:%TLDS%)(?:" + SRC_ZPCC + "|>|$))"
|
||||
)
|
||||
|
||||
|
||||
def _re_host_terminator(opts):
|
||||
src_host_terminator = (
|
||||
"(?=$|"
|
||||
+ TEXT_SEPARATORS
|
||||
+ "|"
|
||||
+ SRC_ZPCC
|
||||
+ ")"
|
||||
+ "(?!"
|
||||
+ ("-(?!--)|" if opts.get("---") else "-|")
|
||||
+ "_|:\\d|\\.-|\\.(?!$|"
|
||||
+ SRC_ZPCC
|
||||
+ "))"
|
||||
)
|
||||
return src_host_terminator
|
||||
|
||||
|
||||
def _re_src_path(opts):
|
||||
src_path = (
|
||||
"(?:"
|
||||
+ "[/?#]"
|
||||
+ "(?:"
|
||||
+ "(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|"
|
||||
+ TEXT_SEPARATORS
|
||||
+ "|[()[\\]{}.,\"'?!\\-;]).|"
|
||||
+ "\\[(?:(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|\\]).)*\\]|"
|
||||
+ "\\((?:(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|[)]).)*\\)|"
|
||||
+ "\\{(?:(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|[}]).)*\\}|"
|
||||
+ '\\"(?:(?!'
|
||||
+ SRC_ZCC
|
||||
+ '|["]).)+\\"|'
|
||||
+ "\\'(?:(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|[']).)+\\'|"
|
||||
+ "\\'(?="
|
||||
+ SRC_PSEUDO_LETTER
|
||||
+ "|[-])|"
|
||||
+ "\\.{2,}[a-zA-Z0-9%/&]|"
|
||||
# google has many dots in "google search" links (#66, #81).
|
||||
# github has ... in commit range links,
|
||||
# ReSTRICT to
|
||||
# - english
|
||||
# - percent-encoded
|
||||
# - parts of file path
|
||||
# - params separator
|
||||
# until more examples found.
|
||||
+ "\\.(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|[.]|$)|"
|
||||
+ ("\\-(?!--(?:[^-]|$))(?:-*)|" if opts.get("---") else "\\-+|")
|
||||
+ ",(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|$)|" # allow `,,,` in paths
|
||||
+ ";(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|$)|" # allow `,,,` in paths
|
||||
+ "\\!+(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|[!]|$)|" # allow `!!!` in paths, but not at the end
|
||||
+ "\\?(?!"
|
||||
+ SRC_ZCC
|
||||
+ "|[?]|$)"
|
||||
+ ")+"
|
||||
+ "|\\/"
|
||||
+ ")?"
|
||||
)
|
||||
|
||||
return src_path
|
||||
|
||||
|
||||
def build_re(opts):
|
||||
"""Build regex
|
||||
|
||||
Args:
|
||||
opts (dict): options
|
||||
|
||||
Return:
|
||||
dict: dict of regex string
|
||||
"""
|
||||
SRC_HOST_STRICT = SRC_HOST + _re_host_terminator(opts)
|
||||
|
||||
TPL_HOST_FUZZY_STRICT = TPL_HOST_FUZZY + _re_host_terminator(opts)
|
||||
|
||||
SRC_HOST_PORT_STRICT = SRC_HOST + SRC_PORT + _re_host_terminator(opts)
|
||||
|
||||
TPL_HOST_PORT_FUZZY_STRICT = TPL_HOST_FUZZY + SRC_PORT + _re_host_terminator(opts)
|
||||
|
||||
TPL_HOST_PORT_NO_IP_FUZZY_STRICT = (
|
||||
TPL_HOST_NO_IP_FUZZY + SRC_PORT + _re_host_terminator(opts)
|
||||
)
|
||||
|
||||
TPL_EMAIL_FUZZY = (
|
||||
"(^|"
|
||||
+ TEXT_SEPARATORS
|
||||
+ '|"|\\(|'
|
||||
+ SRC_ZCC
|
||||
+ ")"
|
||||
+ "("
|
||||
+ SRC_EMAIL_NAME
|
||||
+ "@"
|
||||
+ TPL_HOST_FUZZY_STRICT
|
||||
+ ")"
|
||||
)
|
||||
|
||||
regex = {
|
||||
"src_Any": SRC_ANY,
|
||||
"src_Cc": SRC_CC,
|
||||
"src_Cf": SRC_CF,
|
||||
"src_Z": SRC_Z,
|
||||
"src_P": SRC_P,
|
||||
"src_ZPCc": SRC_ZPCC,
|
||||
"src_ZCc": SRC_ZCC,
|
||||
"src_pseudo_letter": SRC_PSEUDO_LETTER,
|
||||
"src_ip4": SRC_IP4,
|
||||
"src_auth": SRC_AUTH,
|
||||
"src_port": SRC_PORT,
|
||||
"src_host_terminator": _re_host_terminator(opts),
|
||||
"src_path": _re_src_path(opts),
|
||||
"src_email_name": SRC_EMAIL_NAME,
|
||||
"src_xn": SRC_XN,
|
||||
"src_domain_root": SRC_DOMAIN_ROOT,
|
||||
"src_domain": SRC_DOMAIN,
|
||||
"src_host": SRC_HOST,
|
||||
"tpl_host_fuzzy": TPL_HOST_FUZZY,
|
||||
"tpl_host_no_ip_fuzzy": TPL_HOST_NO_IP_FUZZY,
|
||||
"src_host_strict": SRC_HOST_STRICT,
|
||||
"tpl_host_fuzzy_strict": TPL_HOST_FUZZY_STRICT,
|
||||
"src_host_port_strict": SRC_HOST_PORT_STRICT,
|
||||
"tpl_host_port_fuzzy_strict": TPL_HOST_PORT_FUZZY_STRICT,
|
||||
"tpl_host_port_no_ip_fuzzy_strict": TPL_HOST_PORT_FUZZY_STRICT,
|
||||
# Main rules
|
||||
"tpl_host_fuzzy_test": TPL_HOST_FUZZY_TEST,
|
||||
"tpl_email_fuzzy": TPL_EMAIL_FUZZY,
|
||||
# Fuzzy link can't be prepended with .:/\- and non punctuation.
|
||||
# but can start with > (markdown blockquote)
|
||||
"tpl_link_fuzzy": (
|
||||
"(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|"
|
||||
+ SRC_ZPCC
|
||||
+ "))"
|
||||
+ "((?![$+<=>^`|\uff5c])"
|
||||
+ TPL_HOST_PORT_FUZZY_STRICT
|
||||
+ _re_src_path(opts)
|
||||
+ ")"
|
||||
),
|
||||
# Fuzzy link can't be prepended with .:/\- and non punctuation.
|
||||
# but can start with > (markdown blockquote)
|
||||
"tpl_link_no_ip_fuzzy": (
|
||||
"(^|(?![.:/\\-_@])(?:[$+<=>^`|\uff5c]|"
|
||||
+ SRC_ZPCC
|
||||
+ "))"
|
||||
+ "((?![$+<=>^`|\uff5c])"
|
||||
+ TPL_HOST_PORT_NO_IP_FUZZY_STRICT
|
||||
+ _re_src_path(opts)
|
||||
+ ")"
|
||||
),
|
||||
}
|
||||
|
||||
return regex
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2020 tsutsu3
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
===============================================================================
|
||||
|
||||
Original Javascript version:
|
||||
|
||||
Copyright (c) 2015 Vitaly Puzrin.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation
|
||||
files (the "Software"), to deal in the Software without
|
||||
restriction, including without limitation the rights to use,
|
||||
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the
|
||||
Software is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
||||
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
||||
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
||||
OTHER DEALINGS IN THE SOFTWARE.
|
||||
+265
@@ -0,0 +1,265 @@
|
||||
Metadata-Version: 2.1
|
||||
Name: linkify-it-py
|
||||
Version: 2.0.3
|
||||
Summary: Links recognition library with FULL unicode support.
|
||||
Author: tsutsu3
|
||||
License: MIT
|
||||
Project-URL: Homepage, https://github.com/tsutsu3/linkify-it-py
|
||||
Keywords: linkify,linkifier,autolink,autolinker
|
||||
Classifier: Development Status :: 5 - Production/Stable
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Programming Language :: Python :: 3.7
|
||||
Classifier: Programming Language :: Python :: 3.8
|
||||
Classifier: Programming Language :: Python :: 3.9
|
||||
Classifier: Programming Language :: Python :: 3.10
|
||||
Classifier: Programming Language :: Python :: 3.11
|
||||
Classifier: License :: OSI Approved :: MIT License
|
||||
Classifier: Operating System :: OS Independent
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
||||
Requires-Python: >=3.7
|
||||
Description-Content-Type: text/markdown
|
||||
License-File: LICENSE
|
||||
Requires-Dist: uc-micro-py
|
||||
Provides-Extra: benchmark
|
||||
Requires-Dist: pytest ; extra == 'benchmark'
|
||||
Requires-Dist: pytest-benchmark ; extra == 'benchmark'
|
||||
Provides-Extra: dev
|
||||
Requires-Dist: pre-commit ; extra == 'dev'
|
||||
Requires-Dist: isort ; extra == 'dev'
|
||||
Requires-Dist: flake8 ; extra == 'dev'
|
||||
Requires-Dist: black ; extra == 'dev'
|
||||
Requires-Dist: pyproject-flake8 ; extra == 'dev'
|
||||
Provides-Extra: doc
|
||||
Requires-Dist: sphinx ; extra == 'doc'
|
||||
Requires-Dist: sphinx-book-theme ; extra == 'doc'
|
||||
Requires-Dist: myst-parser ; extra == 'doc'
|
||||
Provides-Extra: test
|
||||
Requires-Dist: pytest ; extra == 'test'
|
||||
Requires-Dist: coverage ; extra == 'test'
|
||||
Requires-Dist: pytest-cov ; extra == 'test'
|
||||
|
||||
# linkify-it-py
|
||||
|
||||
[](https://github.com/tsutsu3/linkify-it-py/actions)
|
||||
[](https://pypi.org/project/linkify-it-py/)
|
||||
[](https://anaconda.org/conda-forge/linkify-it-py)
|
||||
[](https://linkify-it-py.readthedocs.io/en/latest/?badge=latest)
|
||||
[](https://codecov.io/gh/tsutsu3/linkify-it-py)
|
||||
[](https://codeclimate.com/github/tsutsu3/linkify-it-py/maintainability)
|
||||
|
||||
This is Python port of [linkify-it](https://github.com/markdown-it/linkify-it).
|
||||
|
||||
> Links recognition library with FULL unicode support.
|
||||
> Focused on high quality link patterns detection in plain text.
|
||||
|
||||
__[Demo](https://linkify-it-py-demo.vercel.app/)__
|
||||
|
||||
__[Javascript Demo](http://markdown-it.github.io/linkify-it/)__
|
||||
|
||||
Why it's awesome:
|
||||
|
||||
- Full unicode support, _with astral characters_!
|
||||
- International domains support.
|
||||
- Allows rules extension & custom normalizers.
|
||||
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
pip install linkify-it-py
|
||||
```
|
||||
|
||||
or
|
||||
|
||||
```bash
|
||||
conda install -c conda-forge linkify-it-py
|
||||
```
|
||||
|
||||
## Usage examples
|
||||
|
||||
### Example 1. Simple use
|
||||
|
||||
```python
|
||||
from linkify_it import LinkifyIt
|
||||
|
||||
|
||||
linkify = LinkifyIt()
|
||||
|
||||
print(linkify.test("Site github.com!"))
|
||||
# => True
|
||||
|
||||
print(linkify.match("Site github.com!"))
|
||||
# => [linkify_it.main.Match({
|
||||
# 'schema': '',
|
||||
# 'index': 5,
|
||||
# 'last_index': 15,
|
||||
# 'raw': 'github.com',
|
||||
# 'text': 'github.com',
|
||||
# 'url': 'http://github.com'
|
||||
# }]
|
||||
```
|
||||
|
||||
### Example 2. With options
|
||||
|
||||
```python
|
||||
from linkify_it import LinkifyIt
|
||||
from linkify_it.tlds import TLDS
|
||||
|
||||
|
||||
# Reload full tlds list & add unofficial `.onion` domain.
|
||||
linkify = (
|
||||
LinkifyIt()
|
||||
.tlds(TLDS) # Reload with full tlds list
|
||||
.tlds("onion", True) # Add unofficial `.onion` domain
|
||||
.add("git:", "http:") # Add `git:` protocol as "alias"
|
||||
.add("ftp:", None) # Disable `ftp:` protocol
|
||||
.set({"fuzzy_ip": True}) # Enable IPs in fuzzy links (without schema)
|
||||
)
|
||||
print(linkify.test("Site tamanegi.onion!"))
|
||||
# => True
|
||||
|
||||
print(linkify.match("Site tamanegi.onion!"))
|
||||
# => [linkify_it.main.Match({
|
||||
# 'schema': '',
|
||||
# 'index': 5,
|
||||
# 'last_index': 19,
|
||||
# 'raw': 'tamanegi.onion',
|
||||
# 'text': 'tamanegi.onion',
|
||||
# 'url': 'http://tamanegi.onion'
|
||||
# }]
|
||||
```
|
||||
|
||||
### Example 3. Add twitter mentions handler
|
||||
|
||||
```python
|
||||
from linkify_it import LinkifyIt
|
||||
|
||||
|
||||
linkify = LinkifyIt()
|
||||
|
||||
def validate(obj, text, pos):
|
||||
tail = text[pos:]
|
||||
|
||||
if not obj.re.get("twitter"):
|
||||
obj.re["twitter"] = re.compile(
|
||||
"^([a-zA-Z0-9_]){1,15}(?!_)(?=$|" + obj.re["src_ZPCc"] + ")"
|
||||
)
|
||||
if obj.re["twitter"].search(tail):
|
||||
if pos > 2 and tail[pos - 2] == "@":
|
||||
return False
|
||||
return len(obj.re["twitter"].search(tail).group())
|
||||
return 0
|
||||
|
||||
def normalize(obj, match):
|
||||
match.url = "https://twitter.com/" + re.sub(r"^@", "", match.url)
|
||||
|
||||
linkify.add("@", {"validate": validate, "normalize": normalize})
|
||||
```
|
||||
|
||||
|
||||
## API
|
||||
|
||||
[API documentation](https://linkify-it-py.readthedocs.io/en/latest/)
|
||||
|
||||
### LinkifyIt(schemas, options)
|
||||
|
||||
Creates new linkifier instance with optional additional schemas.
|
||||
|
||||
By default understands:
|
||||
|
||||
- `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links
|
||||
- "fuzzy" links and emails (google.com, [email protected]).
|
||||
|
||||
`schemas` is an dict, where each key/value describes protocol/rule:
|
||||
|
||||
- __key__ - link prefix (usually, protocol name with `:` at the end, `skype:`
|
||||
for example). `linkify-it-py` makes sure that prefix is not preceded with
|
||||
alphanumeric char.
|
||||
- __value__ - rule to check tail after link prefix
|
||||
- _str_
|
||||
- just alias to existing rule
|
||||
- _dict_
|
||||
- _validate_ - either a `re.Pattern` (start with `^`, and don't include the
|
||||
link prefix itself), or a validator `function` which, given arguments
|
||||
_self_, _text_ and _pos_, returns the length of a match in _text_
|
||||
starting at index _pos_. _pos_ is the index right after the link prefix.
|
||||
_self_ can be used to access the linkify object to cache data.
|
||||
- _normalize_ - optional function to normalize text & url of matched result
|
||||
(for example, for twitter mentions).
|
||||
|
||||
`options`:
|
||||
|
||||
- __fuzzy_link__ - recognize URL-s without `http(s)://` head. Default `True`.
|
||||
- __fuzzy_ip__ - allow IPs in fuzzy links above. Can conflict with some texts
|
||||
like version numbers. Default `False`.
|
||||
- __fuzzy_email__ - recognize emails without `mailto:` prefix. Default `True`.
|
||||
- __---__ - set `True` to terminate link with `---` (if it's considered as long dash).
|
||||
|
||||
|
||||
### .test(text)
|
||||
|
||||
Searches linkifiable pattern and returns `True` on success or `False` on fail.
|
||||
|
||||
|
||||
### .pretest(text)
|
||||
|
||||
Quick check if link MAY BE can exist. Can be used to optimize more expensive
|
||||
`.test()` calls. Return `False` if link can not be found, `True` - if `.test()`
|
||||
call needed to know exactly.
|
||||
|
||||
|
||||
### .test_schema_at(text, name, position)
|
||||
|
||||
Similar to `.test()` but checks only specific protocol tail exactly at given
|
||||
position. Returns length of found pattern (0 on fail).
|
||||
|
||||
|
||||
### .match(text)
|
||||
|
||||
Returns `list` of found link matches or null if nothing found.
|
||||
|
||||
Each match has:
|
||||
|
||||
- __schema__ - link schema, can be empty for fuzzy links, or `//` for
|
||||
protocol-neutral links.
|
||||
- __index__ - offset of matched text
|
||||
- __last_index__ - index of next char after mathch end
|
||||
- __raw__ - matched text
|
||||
- __text__ - normalized text
|
||||
- __url__ - link, generated from matched text
|
||||
|
||||
### .matchAtStart(text)
|
||||
|
||||
Checks if a match exists at the start of the string. Returns `Match`
|
||||
(see docs for `match(text)`) or null if no URL is at the start.
|
||||
Doesn't work with fuzzy links.
|
||||
|
||||
### .tlds(list_tlds, keep_old=False)
|
||||
|
||||
Load (or merge) new tlds list. Those are needed for fuzzy links (without schema)
|
||||
to avoid false positives. By default:
|
||||
|
||||
- 2-letter root zones are ok.
|
||||
- biz|com|edu|gov|net|org|pro|web|xxx|aero|asia|coop|info|museum|name|shop|рф are ok.
|
||||
- encoded (`xn--...`) root zones are ok.
|
||||
|
||||
If that's not enough, you can reload defaults with more detailed zones list.
|
||||
|
||||
### .add(key, value)
|
||||
|
||||
Add a new schema to the schemas object. As described in the constructor
|
||||
definition, `key` is a link prefix (`skype:`, for example), and `value`
|
||||
is a `str` to alias to another schema, or an `dict` with `validate` and
|
||||
optionally `normalize` definitions. To disable an existing rule, use
|
||||
`.add(key, None)`.
|
||||
|
||||
|
||||
### .set(options)
|
||||
|
||||
Override default options. Missed properties will not be changed.
|
||||
|
||||
|
||||
## License
|
||||
|
||||
[MIT](https://github.com/tsutsu3/linkify-it-py/blob/master/LICENSE)
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
linkify_it/__init__.py,sha256=ZnKSUATUH8ZAy_lTWrEgSK4Ug7uw46aoySYWipdm44g,111
|
||||
linkify_it/main.py,sha256=Uz1znZWNyYYARZMZCo2WopkGm4bhCGGmlAfQ8_q9hfQ,21327
|
||||
linkify_it/tlds.py,sha256=qMiHGlrXHOQ8o_PLIo91PdlvqEk1URRq7vBpy2m-reQ,20791
|
||||
linkify_it/ucre.py,sha256=Uke7Jrmuwo_yWHJx0-p2qUa_-yvdQug9y9qWMOK78v0,7103
|
||||
linkify_it_py-2.0.3.dist-info/LICENSE,sha256=211x9h8PeB9QeN9LagDV08eZ-wu4K89EimiOl2Jhii4,2234
|
||||
linkify_it_py-2.0.3.dist-info/METADATA,sha256=m1HD37X0cqwnkOxs3BfN9ZneVXAsw5tOZJOt4g08e24,8463
|
||||
linkify_it_py-2.0.3.dist-info/WHEEL,sha256=oiQVh_5PnQM0E3gPdiz09WCNmwiHDMaGer_elqB3coM,92
|
||||
linkify_it_py-2.0.3.dist-info/top_level.txt,sha256=GX2cfxY-SBCSdp6rvG1YSnI4SQrTxT8tzUFHFvfiM2s,11
|
||||
linkify_it_py-2.0.3.dist-info/RECORD,,
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
Wheel-Version: 1.0
|
||||
Generator: bdist_wheel (0.42.0)
|
||||
Root-Is-Purelib: true
|
||||
Tag: py3-none-any
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
linkify_it
|
||||
Vendored
+5
@@ -0,0 +1,5 @@
|
||||
"""A Python port of Markdown-It"""
|
||||
__all__ = ("MarkdownIt",)
|
||||
__version__ = "3.0.0"
|
||||
|
||||
from .main import MarkdownIt
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Mapping
|
||||
import sys
|
||||
from typing import Any
|
||||
|
||||
DATACLASS_KWARGS: Mapping[str, Any]
|
||||
if sys.version_info >= (3, 10):
|
||||
DATACLASS_KWARGS = {"slots": True}
|
||||
else:
|
||||
DATACLASS_KWARGS = {}
|
||||
Vendored
+67
@@ -0,0 +1,67 @@
|
||||
# Copyright 2014 Mathias Bynens <https://mathiasbynens.be/>
|
||||
# Copyright 2021 Taneli Hukkinen
|
||||
#
|
||||
# Permission is hereby granted, free of charge, to any person obtaining
|
||||
# a copy of this software and associated documentation files (the
|
||||
# "Software"), to deal in the Software without restriction, including
|
||||
# without limitation the rights to use, copy, modify, merge, publish,
|
||||
# distribute, sublicense, and/or sell copies of the Software, and to
|
||||
# permit persons to whom the Software is furnished to do so, subject to
|
||||
# the following conditions:
|
||||
#
|
||||
# The above copyright notice and this permission notice shall be
|
||||
# included in all copies or substantial portions of the Software.
|
||||
#
|
||||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
|
||||
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
import codecs
|
||||
import re
|
||||
from typing import Callable
|
||||
|
||||
REGEX_SEPARATORS = re.compile(r"[\x2E\u3002\uFF0E\uFF61]")
|
||||
REGEX_NON_ASCII = re.compile(r"[^\0-\x7E]")
|
||||
|
||||
|
||||
def encode(uni: str) -> str:
|
||||
return codecs.encode(uni, encoding="punycode").decode()
|
||||
|
||||
|
||||
def decode(ascii: str) -> str:
|
||||
return codecs.decode(ascii, encoding="punycode") # type: ignore
|
||||
|
||||
|
||||
def map_domain(string: str, fn: Callable[[str], str]) -> str:
|
||||
parts = string.split("@")
|
||||
result = ""
|
||||
if len(parts) > 1:
|
||||
# In email addresses, only the domain name should be punycoded. Leave
|
||||
# the local part (i.e. everything up to `@`) intact.
|
||||
result = parts[0] + "@"
|
||||
string = parts[1]
|
||||
labels = REGEX_SEPARATORS.split(string)
|
||||
encoded = ".".join(fn(label) for label in labels)
|
||||
return result + encoded
|
||||
|
||||
|
||||
def to_unicode(obj: str) -> str:
|
||||
def mapping(obj: str) -> str:
|
||||
if obj.startswith("xn--"):
|
||||
return decode(obj[4:].lower())
|
||||
return obj
|
||||
|
||||
return map_domain(obj, mapping)
|
||||
|
||||
|
||||
def to_ascii(obj: str) -> str:
|
||||
def mapping(obj: str) -> str:
|
||||
if REGEX_NON_ASCII.search(obj):
|
||||
return "xn--" + encode(obj)
|
||||
return obj
|
||||
|
||||
return map_domain(obj, mapping)
|
||||
Whitespace-only changes.
Vendored
+109
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python
|
||||
"""
|
||||
CLI interface to markdown-it-py
|
||||
|
||||
Parse one or more markdown files, convert each to HTML, and print to stdout.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
from collections.abc import Iterable, Sequence
|
||||
import sys
|
||||
|
||||
from markdown_it import __version__
|
||||
from markdown_it.main import MarkdownIt
|
||||
|
||||
version_str = "markdown-it-py [version {}]".format(__version__)
|
||||
|
||||
|
||||
def main(args: Sequence[str] | None = None) -> int:
|
||||
namespace = parse_args(args)
|
||||
if namespace.filenames:
|
||||
convert(namespace.filenames)
|
||||
else:
|
||||
interactive()
|
||||
return 0
|
||||
|
||||
|
||||
def convert(filenames: Iterable[str]) -> None:
|
||||
for filename in filenames:
|
||||
convert_file(filename)
|
||||
|
||||
|
||||
def convert_file(filename: str) -> None:
|
||||
"""
|
||||
Parse a Markdown file and dump the output to stdout.
|
||||
"""
|
||||
try:
|
||||
with open(filename, "r", encoding="utf8", errors="ignore") as fin:
|
||||
rendered = MarkdownIt().render(fin.read())
|
||||
print(rendered, end="")
|
||||
except OSError:
|
||||
sys.stderr.write(f'Cannot open file "{filename}".\n')
|
||||
sys.exit(1)
|
||||
|
||||
|
||||
def interactive() -> None:
|
||||
"""
|
||||
Parse user input, dump to stdout, rinse and repeat.
|
||||
Python REPL style.
|
||||
"""
|
||||
print_heading()
|
||||
contents = []
|
||||
more = False
|
||||
while True:
|
||||
try:
|
||||
prompt, more = ("... ", True) if more else (">>> ", True)
|
||||
contents.append(input(prompt) + "\n")
|
||||
except EOFError:
|
||||
print("\n" + MarkdownIt().render("\n".join(contents)), end="")
|
||||
more = False
|
||||
contents = []
|
||||
except KeyboardInterrupt:
|
||||
print("\nExiting.")
|
||||
break
|
||||
|
||||
|
||||
def parse_args(args: Sequence[str] | None) -> argparse.Namespace:
|
||||
"""Parse input CLI arguments."""
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Parse one or more markdown files, "
|
||||
"convert each to HTML, and print to stdout",
|
||||
# NOTE: Remember to update README.md w/ the output of `markdown-it -h`
|
||||
epilog=(
|
||||
f"""
|
||||
Interactive:
|
||||
|
||||
$ markdown-it
|
||||
markdown-it-py [version {__version__}] (interactive)
|
||||
Type Ctrl-D to complete input, or Ctrl-C to exit.
|
||||
>>> # Example
|
||||
... > markdown *input*
|
||||
...
|
||||
<h1>Example</h1>
|
||||
<blockquote>
|
||||
<p>markdown <em>input</em></p>
|
||||
</blockquote>
|
||||
|
||||
Batch:
|
||||
|
||||
$ markdown-it README.md README.footer.md > index.html
|
||||
"""
|
||||
),
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
)
|
||||
parser.add_argument("-v", "--version", action="version", version=version_str)
|
||||
parser.add_argument(
|
||||
"filenames", nargs="*", help="specify an optional list of files to convert"
|
||||
)
|
||||
return parser.parse_args(args)
|
||||
|
||||
|
||||
def print_heading() -> None:
|
||||
print("{} (interactive)".format(version_str))
|
||||
print("Type Ctrl-D to complete input, or Ctrl-C to exit.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
exit_code = main(sys.argv[1:])
|
||||
sys.exit(exit_code)
|
||||
Whitespace-only changes.
+4
@@ -0,0 +1,4 @@
|
||||
"""HTML5 entities map: { name -> characters }."""
|
||||
import html.entities
|
||||
|
||||
entities = {name.rstrip(";"): chars for name, chars in html.entities.html5.items()}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
"""List of valid html blocks names, according to commonmark spec
|
||||
http://jgm.github.io/CommonMark/spec.html#html-blocks
|
||||
"""
|
||||
|
||||
block_names = [
|
||||
"address",
|
||||
"article",
|
||||
"aside",
|
||||
"base",
|
||||
"basefont",
|
||||
"blockquote",
|
||||
"body",
|
||||
"caption",
|
||||
"center",
|
||||
"col",
|
||||
"colgroup",
|
||||
"dd",
|
||||
"details",
|
||||
"dialog",
|
||||
"dir",
|
||||
"div",
|
||||
"dl",
|
||||
"dt",
|
||||
"fieldset",
|
||||
"figcaption",
|
||||
"figure",
|
||||
"footer",
|
||||
"form",
|
||||
"frame",
|
||||
"frameset",
|
||||
"h1",
|
||||
"h2",
|
||||
"h3",
|
||||
"h4",
|
||||
"h5",
|
||||
"h6",
|
||||
"head",
|
||||
"header",
|
||||
"hr",
|
||||
"html",
|
||||
"iframe",
|
||||
"legend",
|
||||
"li",
|
||||
"link",
|
||||
"main",
|
||||
"menu",
|
||||
"menuitem",
|
||||
"nav",
|
||||
"noframes",
|
||||
"ol",
|
||||
"optgroup",
|
||||
"option",
|
||||
"p",
|
||||
"param",
|
||||
"section",
|
||||
"source",
|
||||
"summary",
|
||||
"table",
|
||||
"tbody",
|
||||
"td",
|
||||
"tfoot",
|
||||
"th",
|
||||
"thead",
|
||||
"title",
|
||||
"tr",
|
||||
"track",
|
||||
"ul",
|
||||
]
|
||||
Vendored
+40
@@ -0,0 +1,40 @@
|
||||
"""Regexps to match html elements
|
||||
"""
|
||||
|
||||
import re
|
||||
|
||||
attr_name = "[a-zA-Z_:][a-zA-Z0-9:._-]*"
|
||||
|
||||
unquoted = "[^\"'=<>`\\x00-\\x20]+"
|
||||
single_quoted = "'[^']*'"
|
||||
double_quoted = '"[^"]*"'
|
||||
|
||||
attr_value = "(?:" + unquoted + "|" + single_quoted + "|" + double_quoted + ")"
|
||||
|
||||
attribute = "(?:\\s+" + attr_name + "(?:\\s*=\\s*" + attr_value + ")?)"
|
||||
|
||||
open_tag = "<[A-Za-z][A-Za-z0-9\\-]*" + attribute + "*\\s*\\/?>"
|
||||
|
||||
close_tag = "<\\/[A-Za-z][A-Za-z0-9\\-]*\\s*>"
|
||||
comment = "<!---->|<!--(?:-?[^>-])(?:-?[^-])*-->"
|
||||
processing = "<[?][\\s\\S]*?[?]>"
|
||||
declaration = "<![A-Z]+\\s+[^>]*>"
|
||||
cdata = "<!\\[CDATA\\[[\\s\\S]*?\\]\\]>"
|
||||
|
||||
HTML_TAG_RE = re.compile(
|
||||
"^(?:"
|
||||
+ open_tag
|
||||
+ "|"
|
||||
+ close_tag
|
||||
+ "|"
|
||||
+ comment
|
||||
+ "|"
|
||||
+ processing
|
||||
+ "|"
|
||||
+ declaration
|
||||
+ "|"
|
||||
+ cdata
|
||||
+ ")"
|
||||
)
|
||||
HTML_OPEN_CLOSE_TAG_STR = "^(?:" + open_tag + "|" + close_tag + ")"
|
||||
HTML_OPEN_CLOSE_TAG_RE = re.compile(HTML_OPEN_CLOSE_TAG_STR)
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from contextlib import suppress
|
||||
import re
|
||||
from urllib.parse import quote, unquote, urlparse, urlunparse # noqa: F401
|
||||
|
||||
import mdurl
|
||||
|
||||
from .. import _punycode
|
||||
|
||||
RECODE_HOSTNAME_FOR = ("http:", "https:", "mailto:")
|
||||
|
||||
|
||||
def normalizeLink(url: str) -> str:
|
||||
"""Normalize destination URLs in links
|
||||
|
||||
::
|
||||
|
||||
[label]: destination 'title'
|
||||
^^^^^^^^^^^
|
||||
"""
|
||||
parsed = mdurl.parse(url, slashes_denote_host=True)
|
||||
|
||||
# Encode hostnames in urls like:
|
||||
# `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
|
||||
#
|
||||
# We don't encode unknown schemas, because it's likely that we encode
|
||||
# something we shouldn't (e.g. `skype:name` treated as `skype:host`)
|
||||
#
|
||||
if parsed.hostname and (
|
||||
not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR
|
||||
):
|
||||
with suppress(Exception):
|
||||
parsed = parsed._replace(hostname=_punycode.to_ascii(parsed.hostname))
|
||||
|
||||
return mdurl.encode(mdurl.format(parsed))
|
||||
|
||||
|
||||
def normalizeLinkText(url: str) -> str:
|
||||
"""Normalize autolink content
|
||||
|
||||
::
|
||||
|
||||
<destination>
|
||||
~~~~~~~~~~~
|
||||
"""
|
||||
parsed = mdurl.parse(url, slashes_denote_host=True)
|
||||
|
||||
# Encode hostnames in urls like:
|
||||
# `http://host/`, `https://host/`, `mailto:user@host`, `//host/`
|
||||
#
|
||||
# We don't encode unknown schemas, because it's likely that we encode
|
||||
# something we shouldn't (e.g. `skype:name` treated as `skype:host`)
|
||||
#
|
||||
if parsed.hostname and (
|
||||
not parsed.protocol or parsed.protocol in RECODE_HOSTNAME_FOR
|
||||
):
|
||||
with suppress(Exception):
|
||||
parsed = parsed._replace(hostname=_punycode.to_unicode(parsed.hostname))
|
||||
|
||||
# add '%' to exclude list because of https://github.com/markdown-it/markdown-it/issues/720
|
||||
return mdurl.decode(mdurl.format(parsed), mdurl.DECODE_DEFAULT_CHARS + "%")
|
||||
|
||||
|
||||
BAD_PROTO_RE = re.compile(r"^(vbscript|javascript|file|data):")
|
||||
GOOD_DATA_RE = re.compile(r"^data:image\/(gif|png|jpeg|webp);")
|
||||
|
||||
|
||||
def validateLink(url: str, validator: Callable[[str], bool] | None = None) -> bool:
|
||||
"""Validate URL link is allowed in output.
|
||||
|
||||
This validator can prohibit more than really needed to prevent XSS.
|
||||
It's a tradeoff to keep code simple and to be secure by default.
|
||||
|
||||
Note: url should be normalized at this point, and existing entities decoded.
|
||||
"""
|
||||
if validator is not None:
|
||||
return validator(url)
|
||||
url = url.strip().lower()
|
||||
return bool(GOOD_DATA_RE.search(url)) if BAD_PROTO_RE.search(url) else True
|
||||
Vendored
+318
@@ -0,0 +1,318 @@
|
||||
"""Utilities for parsing source text
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Match, TypeVar
|
||||
|
||||
from .entities import entities
|
||||
|
||||
|
||||
def charCodeAt(src: str, pos: int) -> int | None:
|
||||
"""
|
||||
Returns the Unicode value of the character at the specified location.
|
||||
|
||||
@param - index The zero-based index of the desired character.
|
||||
If there is no character at the specified index, NaN is returned.
|
||||
|
||||
This was added for compatibility with python
|
||||
"""
|
||||
try:
|
||||
return ord(src[pos])
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
|
||||
def charStrAt(src: str, pos: int) -> str | None:
|
||||
"""
|
||||
Returns the Unicode value of the character at the specified location.
|
||||
|
||||
@param - index The zero-based index of the desired character.
|
||||
If there is no character at the specified index, NaN is returned.
|
||||
|
||||
This was added for compatibility with python
|
||||
"""
|
||||
try:
|
||||
return src[pos]
|
||||
except IndexError:
|
||||
return None
|
||||
|
||||
|
||||
_ItemTV = TypeVar("_ItemTV")
|
||||
|
||||
|
||||
def arrayReplaceAt(
|
||||
src: list[_ItemTV], pos: int, newElements: list[_ItemTV]
|
||||
) -> list[_ItemTV]:
|
||||
"""
|
||||
Remove element from array and put another array at those position.
|
||||
Useful for some operations with tokens
|
||||
"""
|
||||
return src[:pos] + newElements + src[pos + 1 :]
|
||||
|
||||
|
||||
def isValidEntityCode(c: int) -> bool:
|
||||
# broken sequence
|
||||
if c >= 0xD800 and c <= 0xDFFF:
|
||||
return False
|
||||
# never used
|
||||
if c >= 0xFDD0 and c <= 0xFDEF:
|
||||
return False
|
||||
if ((c & 0xFFFF) == 0xFFFF) or ((c & 0xFFFF) == 0xFFFE):
|
||||
return False
|
||||
# control codes
|
||||
if c >= 0x00 and c <= 0x08:
|
||||
return False
|
||||
if c == 0x0B:
|
||||
return False
|
||||
if c >= 0x0E and c <= 0x1F:
|
||||
return False
|
||||
if c >= 0x7F and c <= 0x9F:
|
||||
return False
|
||||
# out of range
|
||||
if c > 0x10FFFF:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def fromCodePoint(c: int) -> str:
|
||||
"""Convert ordinal to unicode.
|
||||
|
||||
Note, in the original Javascript two string characters were required,
|
||||
for codepoints larger than `0xFFFF`.
|
||||
But Python 3 can represent any unicode codepoint in one character.
|
||||
"""
|
||||
return chr(c)
|
||||
|
||||
|
||||
# UNESCAPE_MD_RE = re.compile(r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])')
|
||||
# ENTITY_RE_g = re.compile(r'&([a-z#][a-z0-9]{1,31})', re.IGNORECASE)
|
||||
UNESCAPE_ALL_RE = re.compile(
|
||||
r'\\([!"#$%&\'()*+,\-.\/:;<=>?@[\\\]^_`{|}~])' + "|" + r"&([a-z#][a-z0-9]{1,31});",
|
||||
re.IGNORECASE,
|
||||
)
|
||||
DIGITAL_ENTITY_BASE10_RE = re.compile(r"#([0-9]{1,8})")
|
||||
DIGITAL_ENTITY_BASE16_RE = re.compile(r"#x([a-f0-9]{1,8})", re.IGNORECASE)
|
||||
|
||||
|
||||
def replaceEntityPattern(match: str, name: str) -> str:
|
||||
"""Convert HTML entity patterns,
|
||||
see https://spec.commonmark.org/0.30/#entity-references
|
||||
"""
|
||||
if name in entities:
|
||||
return entities[name]
|
||||
|
||||
code: None | int = None
|
||||
if pat := DIGITAL_ENTITY_BASE10_RE.fullmatch(name):
|
||||
code = int(pat.group(1), 10)
|
||||
elif pat := DIGITAL_ENTITY_BASE16_RE.fullmatch(name):
|
||||
code = int(pat.group(1), 16)
|
||||
|
||||
if code is not None and isValidEntityCode(code):
|
||||
return fromCodePoint(code)
|
||||
|
||||
return match
|
||||
|
||||
|
||||
def unescapeAll(string: str) -> str:
|
||||
def replacer_func(match: Match[str]) -> str:
|
||||
escaped = match.group(1)
|
||||
if escaped:
|
||||
return escaped
|
||||
entity = match.group(2)
|
||||
return replaceEntityPattern(match.group(), entity)
|
||||
|
||||
if "\\" not in string and "&" not in string:
|
||||
return string
|
||||
return UNESCAPE_ALL_RE.sub(replacer_func, string)
|
||||
|
||||
|
||||
ESCAPABLE = r"""\\!"#$%&'()*+,./:;<=>?@\[\]^`{}|_~-"""
|
||||
ESCAPE_CHAR = re.compile(r"\\([" + ESCAPABLE + r"])")
|
||||
|
||||
|
||||
def stripEscape(string: str) -> str:
|
||||
"""Strip escape \\ characters"""
|
||||
return ESCAPE_CHAR.sub(r"\1", string)
|
||||
|
||||
|
||||
def escapeHtml(raw: str) -> str:
|
||||
"""Replace special characters "&", "<", ">" and '"' to HTML-safe sequences."""
|
||||
# like html.escape, but without escaping single quotes
|
||||
raw = raw.replace("&", "&") # Must be done first!
|
||||
raw = raw.replace("<", "<")
|
||||
raw = raw.replace(">", ">")
|
||||
raw = raw.replace('"', """)
|
||||
return raw
|
||||
|
||||
|
||||
# //////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
REGEXP_ESCAPE_RE = re.compile(r"[.?*+^$[\]\\(){}|-]")
|
||||
|
||||
|
||||
def escapeRE(string: str) -> str:
|
||||
string = REGEXP_ESCAPE_RE.sub("\\$&", string)
|
||||
return string
|
||||
|
||||
|
||||
# //////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
|
||||
def isSpace(code: int | None) -> bool:
|
||||
"""Check if character code is a whitespace."""
|
||||
return code in (0x09, 0x20)
|
||||
|
||||
|
||||
def isStrSpace(ch: str | None) -> bool:
|
||||
"""Check if character is a whitespace."""
|
||||
return ch in ("\t", " ")
|
||||
|
||||
|
||||
MD_WHITESPACE = {
|
||||
0x09, # \t
|
||||
0x0A, # \n
|
||||
0x0B, # \v
|
||||
0x0C, # \f
|
||||
0x0D, # \r
|
||||
0x20, # space
|
||||
0xA0,
|
||||
0x1680,
|
||||
0x202F,
|
||||
0x205F,
|
||||
0x3000,
|
||||
}
|
||||
|
||||
|
||||
def isWhiteSpace(code: int) -> bool:
|
||||
r"""Zs (unicode class) || [\t\f\v\r\n]"""
|
||||
if code >= 0x2000 and code <= 0x200A:
|
||||
return True
|
||||
return code in MD_WHITESPACE
|
||||
|
||||
|
||||
# //////////////////////////////////////////////////////////////////////////////
|
||||
|
||||
UNICODE_PUNCT_RE = re.compile(
|
||||
r"[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061E\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166D\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B5A-\u1B60\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2E00-\u2E2E\u2E30-\u2E4E\u3001-\u3003\u3008-\u3011\u3014-\u301F\u3030\u303D\u30A0\u30FB\uA4FE\uA4FF\uA60D-\uA60F\uA673\uA67E\uA6F2-\uA6F7\uA874-\uA877\uA8CE\uA8CF\uA8F8-\uA8FA\uA8FC\uA92E\uA92F\uA95F\uA9C1-\uA9CD\uA9DE\uA9DF\uAA5C-\uAA5F\uAADE\uAADF\uAAF0\uAAF1\uABEB\uFD3E\uFD3F\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE61\uFE63\uFE68\uFE6A\uFE6B\uFF01-\uFF03\uFF05-\uFF0A\uFF0C-\uFF0F\uFF1A\uFF1B\uFF1F\uFF20\uFF3B-\uFF3D\uFF3F\uFF5B\uFF5D\uFF5F-\uFF65]|\uD800[\uDD00-\uDD02\uDF9F\uDFD0]|\uD801\uDD6F|\uD802[\uDC57\uDD1F\uDD3F\uDE50-\uDE58\uDE7F\uDEF0-\uDEF6\uDF39-\uDF3F\uDF99-\uDF9C]|\uD803[\uDF55-\uDF59]|\uD804[\uDC47-\uDC4D\uDCBB\uDCBC\uDCBE-\uDCC1\uDD40-\uDD43\uDD74\uDD75\uDDC5-\uDDC8\uDDCD\uDDDB\uDDDD-\uDDDF\uDE38-\uDE3D\uDEA9]|\uD805[\uDC4B-\uDC4F\uDC5B\uDC5D\uDCC6\uDDC1-\uDDD7\uDE41-\uDE43\uDE60-\uDE6C\uDF3C-\uDF3E]|\uD806[\uDC3B\uDE3F-\uDE46\uDE9A-\uDE9C\uDE9E-\uDEA2]|\uD807[\uDC41-\uDC45\uDC70\uDC71\uDEF7\uDEF8]|\uD809[\uDC70-\uDC74]|\uD81A[\uDE6E\uDE6F\uDEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDE97-\uDE9A]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD83A[\uDD5E\uDD5F]" # noqa: E501
|
||||
)
|
||||
|
||||
|
||||
# Currently without astral characters support.
|
||||
def isPunctChar(ch: str) -> bool:
|
||||
"""Check if character is a punctuation character."""
|
||||
return UNICODE_PUNCT_RE.search(ch) is not None
|
||||
|
||||
|
||||
MD_ASCII_PUNCT = {
|
||||
0x21, # /* ! */
|
||||
0x22, # /* " */
|
||||
0x23, # /* # */
|
||||
0x24, # /* $ */
|
||||
0x25, # /* % */
|
||||
0x26, # /* & */
|
||||
0x27, # /* ' */
|
||||
0x28, # /* ( */
|
||||
0x29, # /* ) */
|
||||
0x2A, # /* * */
|
||||
0x2B, # /* + */
|
||||
0x2C, # /* , */
|
||||
0x2D, # /* - */
|
||||
0x2E, # /* . */
|
||||
0x2F, # /* / */
|
||||
0x3A, # /* : */
|
||||
0x3B, # /* ; */
|
||||
0x3C, # /* < */
|
||||
0x3D, # /* = */
|
||||
0x3E, # /* > */
|
||||
0x3F, # /* ? */
|
||||
0x40, # /* @ */
|
||||
0x5B, # /* [ */
|
||||
0x5C, # /* \ */
|
||||
0x5D, # /* ] */
|
||||
0x5E, # /* ^ */
|
||||
0x5F, # /* _ */
|
||||
0x60, # /* ` */
|
||||
0x7B, # /* { */
|
||||
0x7C, # /* | */
|
||||
0x7D, # /* } */
|
||||
0x7E, # /* ~ */
|
||||
}
|
||||
|
||||
|
||||
def isMdAsciiPunct(ch: int) -> bool:
|
||||
"""Markdown ASCII punctuation characters.
|
||||
|
||||
::
|
||||
|
||||
!, ", #, $, %, &, ', (, ), *, +, ,, -, ., /, :, ;, <, =, >, ?, @, [, \\, ], ^, _, `, {, |, }, or ~
|
||||
|
||||
See http://spec.commonmark.org/0.15/#ascii-punctuation-character
|
||||
|
||||
Don't confuse with unicode punctuation !!! It lacks some chars in ascii range.
|
||||
|
||||
""" # noqa: E501
|
||||
return ch in MD_ASCII_PUNCT
|
||||
|
||||
|
||||
def normalizeReference(string: str) -> str:
|
||||
"""Helper to unify [reference labels]."""
|
||||
# Trim and collapse whitespace
|
||||
#
|
||||
string = re.sub(r"\s+", " ", string.strip())
|
||||
|
||||
# In node v10 'ẞ'.toLowerCase() === 'Ṿ', which is presumed to be a bug
|
||||
# fixed in v12 (couldn't find any details).
|
||||
#
|
||||
# So treat this one as a special case
|
||||
# (remove this when node v10 is no longer supported).
|
||||
#
|
||||
# if ('ẞ'.toLowerCase() === 'Ṿ') {
|
||||
# str = str.replace(/ẞ/g, 'ß')
|
||||
# }
|
||||
|
||||
# .toLowerCase().toUpperCase() should get rid of all differences
|
||||
# between letter variants.
|
||||
#
|
||||
# Simple .toLowerCase() doesn't normalize 125 code points correctly,
|
||||
# and .toUpperCase doesn't normalize 6 of them (list of exceptions:
|
||||
# İ, ϴ, ẞ, Ω, K, Å - those are already uppercased, but have differently
|
||||
# uppercased versions).
|
||||
#
|
||||
# Here's an example showing how it happens. Lets take greek letter omega:
|
||||
# uppercase U+0398 (Θ), U+03f4 (ϴ) and lowercase U+03b8 (θ), U+03d1 (ϑ)
|
||||
#
|
||||
# Unicode entries:
|
||||
# 0398;GREEK CAPITAL LETTER THETA;Lu;0;L;;;;;N;;;;03B8
|
||||
# 03B8;GREEK SMALL LETTER THETA;Ll;0;L;;;;;N;;;0398;;0398
|
||||
# 03D1;GREEK THETA SYMBOL;Ll;0;L;<compat> 03B8;;;;N;GREEK SMALL LETTER SCRIPT THETA;;0398;;0398
|
||||
# 03F4;GREEK CAPITAL THETA SYMBOL;Lu;0;L;<compat> 0398;;;;N;;;;03B8
|
||||
#
|
||||
# Case-insensitive comparison should treat all of them as equivalent.
|
||||
#
|
||||
# But .toLowerCase() doesn't change ϑ (it's already lowercase),
|
||||
# and .toUpperCase() doesn't change ϴ (already uppercase).
|
||||
#
|
||||
# Applying first lower then upper case normalizes any character:
|
||||
# '\u0398\u03f4\u03b8\u03d1'.toLowerCase().toUpperCase() === '\u0398\u0398\u0398\u0398'
|
||||
#
|
||||
# Note: this is equivalent to unicode case folding; unicode normalization
|
||||
# is a different step that is not required here.
|
||||
#
|
||||
# Final result should be uppercased, because it's later stored in an object
|
||||
# (this avoid a conflict with Object.prototype members,
|
||||
# most notably, `__proto__`)
|
||||
#
|
||||
return string.lower().upper()
|
||||
|
||||
|
||||
LINK_OPEN_RE = re.compile(r"^<a[>\s]", flags=re.IGNORECASE)
|
||||
LINK_CLOSE_RE = re.compile(r"^</a\s*>", flags=re.IGNORECASE)
|
||||
|
||||
|
||||
def isLinkOpen(string: str) -> bool:
|
||||
return bool(LINK_OPEN_RE.search(string))
|
||||
|
||||
|
||||
def isLinkClose(string: str) -> bool:
|
||||
return bool(LINK_CLOSE_RE.search(string))
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
"""Functions for parsing Links
|
||||
"""
|
||||
__all__ = ("parseLinkLabel", "parseLinkDestination", "parseLinkTitle")
|
||||
from .parse_link_destination import parseLinkDestination
|
||||
from .parse_link_label import parseLinkLabel
|
||||
from .parse_link_title import parseLinkTitle
|
||||
@@ -0,0 +1,86 @@
|
||||
"""
|
||||
Parse link destination
|
||||
"""
|
||||
|
||||
from ..common.utils import charCodeAt, unescapeAll
|
||||
|
||||
|
||||
class _Result:
|
||||
__slots__ = ("ok", "pos", "lines", "str")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.ok = False
|
||||
self.pos = 0
|
||||
self.lines = 0
|
||||
self.str = ""
|
||||
|
||||
|
||||
def parseLinkDestination(string: str, pos: int, maximum: int) -> _Result:
|
||||
lines = 0
|
||||
start = pos
|
||||
result = _Result()
|
||||
|
||||
if charCodeAt(string, pos) == 0x3C: # /* < */
|
||||
pos += 1
|
||||
while pos < maximum:
|
||||
code = charCodeAt(string, pos)
|
||||
if code == 0x0A: # /* \n */)
|
||||
return result
|
||||
if code == 0x3C: # / * < * /
|
||||
return result
|
||||
if code == 0x3E: # /* > */) {
|
||||
result.pos = pos + 1
|
||||
result.str = unescapeAll(string[start + 1 : pos])
|
||||
result.ok = True
|
||||
return result
|
||||
|
||||
if code == 0x5C and pos + 1 < maximum: # \
|
||||
pos += 2
|
||||
continue
|
||||
|
||||
pos += 1
|
||||
|
||||
# no closing '>'
|
||||
return result
|
||||
|
||||
# this should be ... } else { ... branch
|
||||
|
||||
level = 0
|
||||
while pos < maximum:
|
||||
code = charCodeAt(string, pos)
|
||||
|
||||
if code is None or code == 0x20:
|
||||
break
|
||||
|
||||
# ascii control characters
|
||||
if code < 0x20 or code == 0x7F:
|
||||
break
|
||||
|
||||
if code == 0x5C and pos + 1 < maximum:
|
||||
if charCodeAt(string, pos + 1) == 0x20:
|
||||
break
|
||||
pos += 2
|
||||
continue
|
||||
|
||||
if code == 0x28: # /* ( */)
|
||||
level += 1
|
||||
if level > 32:
|
||||
return result
|
||||
|
||||
if code == 0x29: # /* ) */)
|
||||
if level == 0:
|
||||
break
|
||||
level -= 1
|
||||
|
||||
pos += 1
|
||||
|
||||
if start == pos:
|
||||
return result
|
||||
if level != 0:
|
||||
return result
|
||||
|
||||
result.str = unescapeAll(string[start:pos])
|
||||
result.lines = lines
|
||||
result.pos = pos
|
||||
result.ok = True
|
||||
return result
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
Parse link label
|
||||
|
||||
this function assumes that first character ("[") already matches
|
||||
returns the end of the label
|
||||
|
||||
"""
|
||||
from markdown_it.rules_inline import StateInline
|
||||
|
||||
|
||||
def parseLinkLabel(state: StateInline, start: int, disableNested: bool = False) -> int:
|
||||
labelEnd = -1
|
||||
oldPos = state.pos
|
||||
found = False
|
||||
|
||||
state.pos = start + 1
|
||||
level = 1
|
||||
|
||||
while state.pos < state.posMax:
|
||||
marker = state.src[state.pos]
|
||||
if marker == "]":
|
||||
level -= 1
|
||||
if level == 0:
|
||||
found = True
|
||||
break
|
||||
|
||||
prevPos = state.pos
|
||||
state.md.inline.skipToken(state)
|
||||
if marker == "[":
|
||||
if prevPos == state.pos - 1:
|
||||
# increase level if we find text `[`,
|
||||
# which is not a part of any token
|
||||
level += 1
|
||||
elif disableNested:
|
||||
state.pos = oldPos
|
||||
return -1
|
||||
if found:
|
||||
labelEnd = state.pos
|
||||
|
||||
# restore old state
|
||||
state.pos = oldPos
|
||||
|
||||
return labelEnd
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
"""Parse link title
|
||||
"""
|
||||
from ..common.utils import charCodeAt, unescapeAll
|
||||
|
||||
|
||||
class _Result:
|
||||
__slots__ = ("ok", "pos", "lines", "str")
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.ok = False
|
||||
self.pos = 0
|
||||
self.lines = 0
|
||||
self.str = ""
|
||||
|
||||
def __str__(self) -> str:
|
||||
return self.str
|
||||
|
||||
|
||||
def parseLinkTitle(string: str, pos: int, maximum: int) -> _Result:
|
||||
lines = 0
|
||||
start = pos
|
||||
result = _Result()
|
||||
|
||||
if pos >= maximum:
|
||||
return result
|
||||
|
||||
marker = charCodeAt(string, pos)
|
||||
|
||||
# /* " */ /* ' */ /* ( */
|
||||
if marker != 0x22 and marker != 0x27 and marker != 0x28:
|
||||
return result
|
||||
|
||||
pos += 1
|
||||
|
||||
# if opening marker is "(", switch it to closing marker ")"
|
||||
if marker == 0x28:
|
||||
marker = 0x29
|
||||
|
||||
while pos < maximum:
|
||||
code = charCodeAt(string, pos)
|
||||
if code == marker:
|
||||
title = string[start + 1 : pos]
|
||||
title = unescapeAll(title)
|
||||
result.pos = pos + 1
|
||||
result.lines = lines
|
||||
result.str = title
|
||||
result.ok = True
|
||||
return result
|
||||
elif code == 0x28 and marker == 0x29: # /* ( */ /* ) */
|
||||
return result
|
||||
elif code == 0x0A:
|
||||
lines += 1
|
||||
elif code == 0x5C and pos + 1 < maximum: # /* \ */
|
||||
pos += 1
|
||||
if charCodeAt(string, pos) == 0x0A:
|
||||
lines += 1
|
||||
|
||||
pos += 1
|
||||
|
||||
return result
|
||||
Vendored
+355
@@ -0,0 +1,355 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable, Generator, Iterable, Mapping, MutableMapping
|
||||
from contextlib import contextmanager
|
||||
from typing import Any, Literal, overload
|
||||
|
||||
from . import helpers, presets
|
||||
from .common import normalize_url, utils
|
||||
from .parser_block import ParserBlock
|
||||
from .parser_core import ParserCore
|
||||
from .parser_inline import ParserInline
|
||||
from .renderer import RendererHTML, RendererProtocol
|
||||
from .rules_core.state_core import StateCore
|
||||
from .token import Token
|
||||
from .utils import EnvType, OptionsDict, OptionsType, PresetType
|
||||
|
||||
try:
|
||||
import linkify_it
|
||||
except ModuleNotFoundError:
|
||||
linkify_it = None
|
||||
|
||||
|
||||
_PRESETS: dict[str, PresetType] = {
|
||||
"default": presets.default.make(),
|
||||
"js-default": presets.js_default.make(),
|
||||
"zero": presets.zero.make(),
|
||||
"commonmark": presets.commonmark.make(),
|
||||
"gfm-like": presets.gfm_like.make(),
|
||||
}
|
||||
|
||||
|
||||
class MarkdownIt:
|
||||
def __init__(
|
||||
self,
|
||||
config: str | PresetType = "commonmark",
|
||||
options_update: Mapping[str, Any] | None = None,
|
||||
*,
|
||||
renderer_cls: Callable[[MarkdownIt], RendererProtocol] = RendererHTML,
|
||||
):
|
||||
"""Main parser class
|
||||
|
||||
:param config: name of configuration to load or a pre-defined dictionary
|
||||
:param options_update: dictionary that will be merged into ``config["options"]``
|
||||
:param renderer_cls: the class to load as the renderer:
|
||||
``self.renderer = renderer_cls(self)
|
||||
"""
|
||||
# add modules
|
||||
self.utils = utils
|
||||
self.helpers = helpers
|
||||
|
||||
# initialise classes
|
||||
self.inline = ParserInline()
|
||||
self.block = ParserBlock()
|
||||
self.core = ParserCore()
|
||||
self.renderer = renderer_cls(self)
|
||||
self.linkify = linkify_it.LinkifyIt() if linkify_it else None
|
||||
|
||||
# set the configuration
|
||||
if options_update and not isinstance(options_update, Mapping):
|
||||
# catch signature change where renderer_cls was not used as a key-word
|
||||
raise TypeError(
|
||||
f"options_update should be a mapping: {options_update}"
|
||||
"\n(Perhaps you intended this to be the renderer_cls?)"
|
||||
)
|
||||
self.configure(config, options_update=options_update)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"{self.__class__.__module__}.{self.__class__.__name__}()"
|
||||
|
||||
@overload
|
||||
def __getitem__(self, name: Literal["inline"]) -> ParserInline:
|
||||
...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, name: Literal["block"]) -> ParserBlock:
|
||||
...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, name: Literal["core"]) -> ParserCore:
|
||||
...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, name: Literal["renderer"]) -> RendererProtocol:
|
||||
...
|
||||
|
||||
@overload
|
||||
def __getitem__(self, name: str) -> Any:
|
||||
...
|
||||
|
||||
def __getitem__(self, name: str) -> Any:
|
||||
return {
|
||||
"inline": self.inline,
|
||||
"block": self.block,
|
||||
"core": self.core,
|
||||
"renderer": self.renderer,
|
||||
}[name]
|
||||
|
||||
def set(self, options: OptionsType) -> None:
|
||||
"""Set parser options (in the same format as in constructor).
|
||||
Probably, you will never need it, but you can change options after constructor call.
|
||||
|
||||
__Note:__ To achieve the best possible performance, don't modify a
|
||||
`markdown-it` instance options on the fly. If you need multiple configurations
|
||||
it's best to create multiple instances and initialize each with separate config.
|
||||
"""
|
||||
self.options = OptionsDict(options)
|
||||
|
||||
def configure(
|
||||
self, presets: str | PresetType, options_update: Mapping[str, Any] | None = None
|
||||
) -> MarkdownIt:
|
||||
"""Batch load of all options and component settings.
|
||||
This is an internal method, and you probably will not need it.
|
||||
But if you will - see available presets and data structure
|
||||
[here](https://github.com/markdown-it/markdown-it/tree/master/lib/presets)
|
||||
|
||||
We strongly recommend to use presets instead of direct config loads.
|
||||
That will give better compatibility with next versions.
|
||||
"""
|
||||
if isinstance(presets, str):
|
||||
if presets not in _PRESETS:
|
||||
raise KeyError(f"Wrong `markdown-it` preset '{presets}', check name")
|
||||
config = _PRESETS[presets]
|
||||
else:
|
||||
config = presets
|
||||
|
||||
if not config:
|
||||
raise ValueError("Wrong `markdown-it` config, can't be empty")
|
||||
|
||||
options = config.get("options", {}) or {}
|
||||
if options_update:
|
||||
options = {**options, **options_update} # type: ignore
|
||||
|
||||
self.set(options) # type: ignore
|
||||
|
||||
if "components" in config:
|
||||
for name, component in config["components"].items():
|
||||
rules = component.get("rules", None)
|
||||
if rules:
|
||||
self[name].ruler.enableOnly(rules)
|
||||
rules2 = component.get("rules2", None)
|
||||
if rules2:
|
||||
self[name].ruler2.enableOnly(rules2)
|
||||
|
||||
return self
|
||||
|
||||
def get_all_rules(self) -> dict[str, list[str]]:
|
||||
"""Return the names of all active rules."""
|
||||
rules = {
|
||||
chain: self[chain].ruler.get_all_rules()
|
||||
for chain in ["core", "block", "inline"]
|
||||
}
|
||||
rules["inline2"] = self.inline.ruler2.get_all_rules()
|
||||
return rules
|
||||
|
||||
def get_active_rules(self) -> dict[str, list[str]]:
|
||||
"""Return the names of all active rules."""
|
||||
rules = {
|
||||
chain: self[chain].ruler.get_active_rules()
|
||||
for chain in ["core", "block", "inline"]
|
||||
}
|
||||
rules["inline2"] = self.inline.ruler2.get_active_rules()
|
||||
return rules
|
||||
|
||||
def enable(
|
||||
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
||||
) -> MarkdownIt:
|
||||
"""Enable list or rules. (chainable)
|
||||
|
||||
:param names: rule name or list of rule names to enable.
|
||||
:param ignoreInvalid: set `true` to ignore errors when rule not found.
|
||||
|
||||
It will automatically find appropriate components,
|
||||
containing rules with given names. If rule not found, and `ignoreInvalid`
|
||||
not set - throws exception.
|
||||
|
||||
Example::
|
||||
|
||||
md = MarkdownIt().enable(['sub', 'sup']).disable('smartquotes')
|
||||
|
||||
"""
|
||||
result = []
|
||||
|
||||
if isinstance(names, str):
|
||||
names = [names]
|
||||
|
||||
for chain in ["core", "block", "inline"]:
|
||||
result.extend(self[chain].ruler.enable(names, True))
|
||||
result.extend(self.inline.ruler2.enable(names, True))
|
||||
|
||||
missed = [name for name in names if name not in result]
|
||||
if missed and not ignoreInvalid:
|
||||
raise ValueError(f"MarkdownIt. Failed to enable unknown rule(s): {missed}")
|
||||
|
||||
return self
|
||||
|
||||
def disable(
|
||||
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
||||
) -> MarkdownIt:
|
||||
"""The same as [[MarkdownIt.enable]], but turn specified rules off. (chainable)
|
||||
|
||||
:param names: rule name or list of rule names to disable.
|
||||
:param ignoreInvalid: set `true` to ignore errors when rule not found.
|
||||
|
||||
"""
|
||||
result = []
|
||||
|
||||
if isinstance(names, str):
|
||||
names = [names]
|
||||
|
||||
for chain in ["core", "block", "inline"]:
|
||||
result.extend(self[chain].ruler.disable(names, True))
|
||||
result.extend(self.inline.ruler2.disable(names, True))
|
||||
|
||||
missed = [name for name in names if name not in result]
|
||||
if missed and not ignoreInvalid:
|
||||
raise ValueError(f"MarkdownIt. Failed to disable unknown rule(s): {missed}")
|
||||
return self
|
||||
|
||||
@contextmanager
|
||||
def reset_rules(self) -> Generator[None, None, None]:
|
||||
"""A context manager, that will reset the current enabled rules on exit."""
|
||||
chain_rules = self.get_active_rules()
|
||||
yield
|
||||
for chain, rules in chain_rules.items():
|
||||
if chain != "inline2":
|
||||
self[chain].ruler.enableOnly(rules)
|
||||
self.inline.ruler2.enableOnly(chain_rules["inline2"])
|
||||
|
||||
def add_render_rule(
|
||||
self, name: str, function: Callable[..., Any], fmt: str = "html"
|
||||
) -> None:
|
||||
"""Add a rule for rendering a particular Token type.
|
||||
|
||||
Only applied when ``renderer.__output__ == fmt``
|
||||
"""
|
||||
if self.renderer.__output__ == fmt:
|
||||
self.renderer.rules[name] = function.__get__(self.renderer) # type: ignore
|
||||
|
||||
def use(
|
||||
self, plugin: Callable[..., None], *params: Any, **options: Any
|
||||
) -> MarkdownIt:
|
||||
"""Load specified plugin with given params into current parser instance. (chainable)
|
||||
|
||||
It's just a sugar to call `plugin(md, params)` with curring.
|
||||
|
||||
Example::
|
||||
|
||||
def func(tokens, idx):
|
||||
tokens[idx].content = tokens[idx].content.replace('foo', 'bar')
|
||||
md = MarkdownIt().use(plugin, 'foo_replace', 'text', func)
|
||||
|
||||
"""
|
||||
plugin(self, *params, **options)
|
||||
return self
|
||||
|
||||
def parse(self, src: str, env: EnvType | None = None) -> list[Token]:
|
||||
"""Parse the source string to a token stream
|
||||
|
||||
:param src: source string
|
||||
:param env: environment sandbox
|
||||
|
||||
Parse input string and return list of block tokens (special token type
|
||||
"inline" will contain list of inline tokens).
|
||||
|
||||
`env` is used to pass data between "distributed" rules and return additional
|
||||
metadata like reference info, needed for the renderer. It also can be used to
|
||||
inject data in specific cases. Usually, you will be ok to pass `{}`,
|
||||
and then pass updated object to renderer.
|
||||
"""
|
||||
env = {} if env is None else env
|
||||
if not isinstance(env, MutableMapping):
|
||||
raise TypeError(f"Input data should be a MutableMapping, not {type(env)}")
|
||||
if not isinstance(src, str):
|
||||
raise TypeError(f"Input data should be a string, not {type(src)}")
|
||||
state = StateCore(src, self, env)
|
||||
self.core.process(state)
|
||||
return state.tokens
|
||||
|
||||
def render(self, src: str, env: EnvType | None = None) -> Any:
|
||||
"""Render markdown string into html. It does all magic for you :).
|
||||
|
||||
:param src: source string
|
||||
:param env: environment sandbox
|
||||
:returns: The output of the loaded renderer
|
||||
|
||||
`env` can be used to inject additional metadata (`{}` by default).
|
||||
But you will not need it with high probability. See also comment
|
||||
in [[MarkdownIt.parse]].
|
||||
"""
|
||||
env = {} if env is None else env
|
||||
return self.renderer.render(self.parse(src, env), self.options, env)
|
||||
|
||||
def parseInline(self, src: str, env: EnvType | None = None) -> list[Token]:
|
||||
"""The same as [[MarkdownIt.parse]] but skip all block rules.
|
||||
|
||||
:param src: source string
|
||||
:param env: environment sandbox
|
||||
|
||||
It returns the
|
||||
block tokens list with the single `inline` element, containing parsed inline
|
||||
tokens in `children` property. Also updates `env` object.
|
||||
"""
|
||||
env = {} if env is None else env
|
||||
if not isinstance(env, MutableMapping):
|
||||
raise TypeError(f"Input data should be an MutableMapping, not {type(env)}")
|
||||
if not isinstance(src, str):
|
||||
raise TypeError(f"Input data should be a string, not {type(src)}")
|
||||
state = StateCore(src, self, env)
|
||||
state.inlineMode = True
|
||||
self.core.process(state)
|
||||
return state.tokens
|
||||
|
||||
def renderInline(self, src: str, env: EnvType | None = None) -> Any:
|
||||
"""Similar to [[MarkdownIt.render]] but for single paragraph content.
|
||||
|
||||
:param src: source string
|
||||
:param env: environment sandbox
|
||||
|
||||
Similar to [[MarkdownIt.render]] but for single paragraph content. Result
|
||||
will NOT be wrapped into `<p>` tags.
|
||||
"""
|
||||
env = {} if env is None else env
|
||||
return self.renderer.render(self.parseInline(src, env), self.options, env)
|
||||
|
||||
# link methods
|
||||
|
||||
def validateLink(self, url: str) -> bool:
|
||||
"""Validate if the URL link is allowed in output.
|
||||
|
||||
This validator can prohibit more than really needed to prevent XSS.
|
||||
It's a tradeoff to keep code simple and to be secure by default.
|
||||
|
||||
Note: the url should be normalized at this point, and existing entities decoded.
|
||||
"""
|
||||
return normalize_url.validateLink(url)
|
||||
|
||||
def normalizeLink(self, url: str) -> str:
|
||||
"""Normalize destination URLs in links
|
||||
|
||||
::
|
||||
|
||||
[label]: destination 'title'
|
||||
^^^^^^^^^^^
|
||||
"""
|
||||
return normalize_url.normalizeLink(url)
|
||||
|
||||
def normalizeLinkText(self, link: str) -> str:
|
||||
"""Normalize autolink content
|
||||
|
||||
::
|
||||
|
||||
<destination>
|
||||
~~~~~~~~~~~
|
||||
"""
|
||||
return normalize_url.normalizeLinkText(link)
|
||||
Vendored
+111
@@ -0,0 +1,111 @@
|
||||
"""Block-level tokenizer."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from . import rules_block
|
||||
from .ruler import Ruler
|
||||
from .rules_block.state_block import StateBlock
|
||||
from .token import Token
|
||||
from .utils import EnvType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from markdown_it import MarkdownIt
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
RuleFuncBlockType = Callable[[StateBlock, int, int, bool], bool]
|
||||
"""(state: StateBlock, startLine: int, endLine: int, silent: bool) -> matched: bool)
|
||||
|
||||
`silent` disables token generation, useful for lookahead.
|
||||
"""
|
||||
|
||||
_rules: list[tuple[str, RuleFuncBlockType, list[str]]] = [
|
||||
# First 2 params - rule name & source. Secondary array - list of rules,
|
||||
# which can be terminated by this one.
|
||||
("table", rules_block.table, ["paragraph", "reference"]),
|
||||
("code", rules_block.code, []),
|
||||
("fence", rules_block.fence, ["paragraph", "reference", "blockquote", "list"]),
|
||||
(
|
||||
"blockquote",
|
||||
rules_block.blockquote,
|
||||
["paragraph", "reference", "blockquote", "list"],
|
||||
),
|
||||
("hr", rules_block.hr, ["paragraph", "reference", "blockquote", "list"]),
|
||||
("list", rules_block.list_block, ["paragraph", "reference", "blockquote"]),
|
||||
("reference", rules_block.reference, []),
|
||||
("html_block", rules_block.html_block, ["paragraph", "reference", "blockquote"]),
|
||||
("heading", rules_block.heading, ["paragraph", "reference", "blockquote"]),
|
||||
("lheading", rules_block.lheading, []),
|
||||
("paragraph", rules_block.paragraph, []),
|
||||
]
|
||||
|
||||
|
||||
class ParserBlock:
|
||||
"""
|
||||
ParserBlock#ruler -> Ruler
|
||||
|
||||
[[Ruler]] instance. Keep configuration of block rules.
|
||||
"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.ruler = Ruler[RuleFuncBlockType]()
|
||||
for name, rule, alt in _rules:
|
||||
self.ruler.push(name, rule, {"alt": alt})
|
||||
|
||||
def tokenize(self, state: StateBlock, startLine: int, endLine: int) -> None:
|
||||
"""Generate tokens for input range."""
|
||||
rules = self.ruler.getRules("")
|
||||
line = startLine
|
||||
maxNesting = state.md.options.maxNesting
|
||||
hasEmptyLines = False
|
||||
|
||||
while line < endLine:
|
||||
state.line = line = state.skipEmptyLines(line)
|
||||
if line >= endLine:
|
||||
break
|
||||
if state.sCount[line] < state.blkIndent:
|
||||
# Termination condition for nested calls.
|
||||
# Nested calls currently used for blockquotes & lists
|
||||
break
|
||||
if state.level >= maxNesting:
|
||||
# If nesting level exceeded - skip tail to the end.
|
||||
# That's not ordinary situation and we should not care about content.
|
||||
state.line = endLine
|
||||
break
|
||||
|
||||
# Try all possible rules.
|
||||
# On success, rule should:
|
||||
# - update `state.line`
|
||||
# - update `state.tokens`
|
||||
# - return True
|
||||
for rule in rules:
|
||||
if rule(state, line, endLine, False):
|
||||
break
|
||||
|
||||
# set state.tight if we had an empty line before current tag
|
||||
# i.e. latest empty line should not count
|
||||
state.tight = not hasEmptyLines
|
||||
|
||||
line = state.line
|
||||
|
||||
# paragraph might "eat" one newline after it in nested lists
|
||||
if (line - 1) < endLine and state.isEmpty(line - 1):
|
||||
hasEmptyLines = True
|
||||
|
||||
if line < endLine and state.isEmpty(line):
|
||||
hasEmptyLines = True
|
||||
line += 1
|
||||
state.line = line
|
||||
|
||||
def parse(
|
||||
self, src: str, md: MarkdownIt, env: EnvType, outTokens: list[Token]
|
||||
) -> list[Token] | None:
|
||||
"""Process input string and push block tokens into `outTokens`."""
|
||||
if not src:
|
||||
return None
|
||||
state = StateBlock(src, md, env, outTokens)
|
||||
self.tokenize(state, state.line, state.lineMax)
|
||||
return state.tokens
|
||||
Vendored
+45
@@ -0,0 +1,45 @@
|
||||
"""
|
||||
* class Core
|
||||
*
|
||||
* Top-level rules executor. Glues block/inline parsers and does intermediate
|
||||
* transformations.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Callable
|
||||
|
||||
from .ruler import Ruler
|
||||
from .rules_core import (
|
||||
block,
|
||||
inline,
|
||||
linkify,
|
||||
normalize,
|
||||
replace,
|
||||
smartquotes,
|
||||
text_join,
|
||||
)
|
||||
from .rules_core.state_core import StateCore
|
||||
|
||||
RuleFuncCoreType = Callable[[StateCore], None]
|
||||
|
||||
_rules: list[tuple[str, RuleFuncCoreType]] = [
|
||||
("normalize", normalize),
|
||||
("block", block),
|
||||
("inline", inline),
|
||||
("linkify", linkify),
|
||||
("replacements", replace),
|
||||
("smartquotes", smartquotes),
|
||||
("text_join", text_join),
|
||||
]
|
||||
|
||||
|
||||
class ParserCore:
|
||||
def __init__(self) -> None:
|
||||
self.ruler = Ruler[RuleFuncCoreType]()
|
||||
for name, rule in _rules:
|
||||
self.ruler.push(name, rule)
|
||||
|
||||
def process(self, state: StateCore) -> None:
|
||||
"""Executes core chain rules."""
|
||||
for rule in self.ruler.getRules(""):
|
||||
rule(state)
|
||||
Vendored
+147
@@ -0,0 +1,147 @@
|
||||
"""Tokenizes paragraph content.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Callable
|
||||
|
||||
from . import rules_inline
|
||||
from .ruler import Ruler
|
||||
from .rules_inline.state_inline import StateInline
|
||||
from .token import Token
|
||||
from .utils import EnvType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from markdown_it import MarkdownIt
|
||||
|
||||
|
||||
# Parser rules
|
||||
RuleFuncInlineType = Callable[[StateInline, bool], bool]
|
||||
"""(state: StateInline, silent: bool) -> matched: bool)
|
||||
|
||||
`silent` disables token generation, useful for lookahead.
|
||||
"""
|
||||
_rules: list[tuple[str, RuleFuncInlineType]] = [
|
||||
("text", rules_inline.text),
|
||||
("linkify", rules_inline.linkify),
|
||||
("newline", rules_inline.newline),
|
||||
("escape", rules_inline.escape),
|
||||
("backticks", rules_inline.backtick),
|
||||
("strikethrough", rules_inline.strikethrough.tokenize),
|
||||
("emphasis", rules_inline.emphasis.tokenize),
|
||||
("link", rules_inline.link),
|
||||
("image", rules_inline.image),
|
||||
("autolink", rules_inline.autolink),
|
||||
("html_inline", rules_inline.html_inline),
|
||||
("entity", rules_inline.entity),
|
||||
]
|
||||
|
||||
# Note `rule2` ruleset was created specifically for emphasis/strikethrough
|
||||
# post-processing and may be changed in the future.
|
||||
#
|
||||
# Don't use this for anything except pairs (plugins working with `balance_pairs`).
|
||||
#
|
||||
RuleFuncInline2Type = Callable[[StateInline], None]
|
||||
_rules2: list[tuple[str, RuleFuncInline2Type]] = [
|
||||
("balance_pairs", rules_inline.link_pairs),
|
||||
("strikethrough", rules_inline.strikethrough.postProcess),
|
||||
("emphasis", rules_inline.emphasis.postProcess),
|
||||
# rules for pairs separate '**' into its own text tokens, which may be left unused,
|
||||
# rule below merges unused segments back with the rest of the text
|
||||
("fragments_join", rules_inline.fragments_join),
|
||||
]
|
||||
|
||||
|
||||
class ParserInline:
|
||||
def __init__(self) -> None:
|
||||
self.ruler = Ruler[RuleFuncInlineType]()
|
||||
for name, rule in _rules:
|
||||
self.ruler.push(name, rule)
|
||||
# Second ruler used for post-processing (e.g. in emphasis-like rules)
|
||||
self.ruler2 = Ruler[RuleFuncInline2Type]()
|
||||
for name, rule2 in _rules2:
|
||||
self.ruler2.push(name, rule2)
|
||||
|
||||
def skipToken(self, state: StateInline) -> None:
|
||||
"""Skip single token by running all rules in validation mode;
|
||||
returns `True` if any rule reported success
|
||||
"""
|
||||
ok = False
|
||||
pos = state.pos
|
||||
rules = self.ruler.getRules("")
|
||||
maxNesting = state.md.options["maxNesting"]
|
||||
cache = state.cache
|
||||
|
||||
if pos in cache:
|
||||
state.pos = cache[pos]
|
||||
return
|
||||
|
||||
if state.level < maxNesting:
|
||||
for rule in rules:
|
||||
# Increment state.level and decrement it later to limit recursion.
|
||||
# It's harmless to do here, because no tokens are created.
|
||||
# But ideally, we'd need a separate private state variable for this purpose.
|
||||
state.level += 1
|
||||
ok = rule(state, True)
|
||||
state.level -= 1
|
||||
if ok:
|
||||
break
|
||||
else:
|
||||
# Too much nesting, just skip until the end of the paragraph.
|
||||
#
|
||||
# NOTE: this will cause links to behave incorrectly in the following case,
|
||||
# when an amount of `[` is exactly equal to `maxNesting + 1`:
|
||||
#
|
||||
# [[[[[[[[[[[[[[[[[[[[[foo]()
|
||||
#
|
||||
# TODO: remove this workaround when CM standard will allow nested links
|
||||
# (we can replace it by preventing links from being parsed in
|
||||
# validation mode)
|
||||
#
|
||||
state.pos = state.posMax
|
||||
|
||||
if not ok:
|
||||
state.pos += 1
|
||||
cache[pos] = state.pos
|
||||
|
||||
def tokenize(self, state: StateInline) -> None:
|
||||
"""Generate tokens for input range."""
|
||||
ok = False
|
||||
rules = self.ruler.getRules("")
|
||||
end = state.posMax
|
||||
maxNesting = state.md.options["maxNesting"]
|
||||
|
||||
while state.pos < end:
|
||||
# Try all possible rules.
|
||||
# On success, rule should:
|
||||
#
|
||||
# - update `state.pos`
|
||||
# - update `state.tokens`
|
||||
# - return true
|
||||
|
||||
if state.level < maxNesting:
|
||||
for rule in rules:
|
||||
ok = rule(state, False)
|
||||
if ok:
|
||||
break
|
||||
|
||||
if ok:
|
||||
if state.pos >= end:
|
||||
break
|
||||
continue
|
||||
|
||||
state.pending += state.src[state.pos]
|
||||
state.pos += 1
|
||||
|
||||
if state.pending:
|
||||
state.pushPending()
|
||||
|
||||
def parse(
|
||||
self, src: str, md: MarkdownIt, env: EnvType, tokens: list[Token]
|
||||
) -> list[Token]:
|
||||
"""Process input string and push inline tokens into `tokens`"""
|
||||
state = StateInline(src, md, env, tokens)
|
||||
self.tokenize(state)
|
||||
rules2 = self.ruler2.getRules("")
|
||||
for rule in rules2:
|
||||
rule(state)
|
||||
return state.tokens
|
||||
Vendored
+48
@@ -0,0 +1,48 @@
|
||||
- package: markdown-it/markdown-it
|
||||
version: 13.0.1
|
||||
commit: e843acc9edad115cbf8cf85e676443f01658be08
|
||||
date: May 3, 2022
|
||||
notes:
|
||||
- Rename variables that use python built-in names, e.g.
|
||||
- `max` -> `maximum`
|
||||
- `len` -> `length`
|
||||
- `str` -> `string`
|
||||
- |
|
||||
Convert JS `for` loops to `while` loops
|
||||
this is generally the main difference between the codes,
|
||||
because in python you can't do e.g. `for {i=1;i<x;i++} {}`
|
||||
- |
|
||||
`env` is a common Python dictionary, and so does not have attribute access to keys,
|
||||
as with JavaScript dictionaries.
|
||||
`options` have attribute access only to core markdownit configuration options
|
||||
- |
|
||||
`Token.attrs` is a dictionary, instead of a list of lists.
|
||||
Upstream the list format is only used to guarantee order: https://github.com/markdown-it/markdown-it/issues/142,
|
||||
but in Python 3.7+ order of dictionaries is guaranteed.
|
||||
One should anyhow use the `attrGet`, `attrSet`, `attrPush` and `attrJoin` methods
|
||||
to manipulate `Token.attrs`, which have an identical signature to those upstream.
|
||||
- Use python version of `charCodeAt`
|
||||
- |
|
||||
Use `str` units instead of `int`s to represent Unicode codepoints.
|
||||
This provides a significant performance boost
|
||||
- |
|
||||
In markdown_it/rules_block/reference.py,
|
||||
record line range in state.env["references"] and add state.env["duplicate_refs"]
|
||||
This is to allow renderers to report on issues regarding references
|
||||
- |
|
||||
The `MarkdownIt.__init__` signature is slightly different for updating options,
|
||||
since you must always specify the config first, e.g.
|
||||
use `MarkdownIt("commonmark", {"html": False})` instead of `MarkdownIt({"html": False})`
|
||||
- The default configuration preset for `MarkdownIt` is "commonmark" not "default"
|
||||
- Allow custom renderer to be passed to `MarkdownIt`
|
||||
- |
|
||||
change render method signatures
|
||||
`func(tokens, idx, options, env, slf)` to
|
||||
`func(self, tokens, idx, options, env)`
|
||||
- |
|
||||
Extensions add render methods by format
|
||||
`MarkdownIt.add_render_rule(name, function, fmt="html")`,
|
||||
rather than `MarkdownIt.renderer.rules[name] = function`
|
||||
and renderers should declare a class property `__output__ = "html"`.
|
||||
This allows for extensibility to more than just HTML renderers
|
||||
- inline tokens in tables are assigned a map (this is helpful for propagation to children)
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
__all__ = ("commonmark", "default", "zero", "js_default", "gfm_like")
|
||||
|
||||
from . import commonmark, default, zero
|
||||
from ..utils import PresetType
|
||||
|
||||
js_default = default
|
||||
|
||||
|
||||
class gfm_like: # noqa: N801
|
||||
"""GitHub Flavoured Markdown (GFM) like.
|
||||
|
||||
This adds the linkify, table and strikethrough components to CommmonMark.
|
||||
|
||||
Note, it lacks task-list items and raw HTML filtering,
|
||||
to meet the the full GFM specification
|
||||
(see https://github.github.com/gfm/#autolinks-extension-).
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def make() -> PresetType:
|
||||
config = commonmark.make()
|
||||
config["components"]["core"]["rules"].append("linkify")
|
||||
config["components"]["block"]["rules"].append("table")
|
||||
config["components"]["inline"]["rules"].extend(["strikethrough", "linkify"])
|
||||
config["components"]["inline"]["rules2"].append("strikethrough")
|
||||
config["options"]["linkify"] = True
|
||||
config["options"]["html"] = True
|
||||
return config
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
"""Commonmark default options.
|
||||
|
||||
This differs to presets.default,
|
||||
primarily in that it allows HTML and does not enable components:
|
||||
|
||||
- block: table
|
||||
- inline: strikethrough
|
||||
"""
|
||||
from ..utils import PresetType
|
||||
|
||||
|
||||
def make() -> PresetType:
|
||||
return {
|
||||
"options": {
|
||||
"maxNesting": 20, # Internal protection, recursion limit
|
||||
"html": True, # Enable HTML tags in source,
|
||||
# this is just a shorthand for .enable(["html_inline", "html_block"])
|
||||
# used by the linkify rule:
|
||||
"linkify": False, # autoconvert URL-like texts to links
|
||||
# used by the replacements and smartquotes rules
|
||||
# Enable some language-neutral replacements + quotes beautification
|
||||
"typographer": False,
|
||||
# used by the smartquotes rule:
|
||||
# Double + single quotes replacement pairs, when typographer enabled,
|
||||
# and smartquotes on. Could be either a String or an Array.
|
||||
#
|
||||
# For example, you can use '«»„“' for Russian, '„“‚‘' for German,
|
||||
# and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
|
||||
"quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
|
||||
# Renderer specific; these options are used directly in the HTML renderer
|
||||
"xhtmlOut": True, # Use '/' to close single tags (<br />)
|
||||
"breaks": False, # Convert '\n' in paragraphs into <br>
|
||||
"langPrefix": "language-", # CSS language prefix for fenced blocks
|
||||
# Highlighter function. Should return escaped HTML,
|
||||
# or '' if the source string is not changed and should be escaped externally.
|
||||
# If result starts with <pre... internal wrapper is skipped.
|
||||
#
|
||||
# function (/*str, lang, attrs*/) { return ''; }
|
||||
#
|
||||
"highlight": None,
|
||||
},
|
||||
"components": {
|
||||
"core": {"rules": ["normalize", "block", "inline", "text_join"]},
|
||||
"block": {
|
||||
"rules": [
|
||||
"blockquote",
|
||||
"code",
|
||||
"fence",
|
||||
"heading",
|
||||
"hr",
|
||||
"html_block",
|
||||
"lheading",
|
||||
"list",
|
||||
"reference",
|
||||
"paragraph",
|
||||
]
|
||||
},
|
||||
"inline": {
|
||||
"rules": [
|
||||
"autolink",
|
||||
"backticks",
|
||||
"emphasis",
|
||||
"entity",
|
||||
"escape",
|
||||
"html_inline",
|
||||
"image",
|
||||
"link",
|
||||
"newline",
|
||||
"text",
|
||||
],
|
||||
"rules2": ["balance_pairs", "emphasis", "fragments_join"],
|
||||
},
|
||||
},
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"""markdown-it default options."""
|
||||
from ..utils import PresetType
|
||||
|
||||
|
||||
def make() -> PresetType:
|
||||
return {
|
||||
"options": {
|
||||
"maxNesting": 100, # Internal protection, recursion limit
|
||||
"html": False, # Enable HTML tags in source
|
||||
# this is just a shorthand for .disable(["html_inline", "html_block"])
|
||||
# used by the linkify rule:
|
||||
"linkify": False, # autoconvert URL-like texts to links
|
||||
# used by the replacements and smartquotes rules:
|
||||
# Enable some language-neutral replacements + quotes beautification
|
||||
"typographer": False,
|
||||
# used by the smartquotes rule:
|
||||
# Double + single quotes replacement pairs, when typographer enabled,
|
||||
# and smartquotes on. Could be either a String or an Array.
|
||||
# For example, you can use '«»„“' for Russian, '„“‚‘' for German,
|
||||
# and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
|
||||
"quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
|
||||
# Renderer specific; these options are used directly in the HTML renderer
|
||||
"xhtmlOut": False, # Use '/' to close single tags (<br />)
|
||||
"breaks": False, # Convert '\n' in paragraphs into <br>
|
||||
"langPrefix": "language-", # CSS language prefix for fenced blocks
|
||||
# Highlighter function. Should return escaped HTML,
|
||||
# or '' if the source string is not changed and should be escaped externally.
|
||||
# If result starts with <pre... internal wrapper is skipped.
|
||||
#
|
||||
# function (/*str, lang, attrs*/) { return ''; }
|
||||
#
|
||||
"highlight": None,
|
||||
},
|
||||
"components": {"core": {}, "block": {}, "inline": {}},
|
||||
}
|
||||
Vendored
+43
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
"Zero" preset, with nothing enabled. Useful for manual configuring of simple
|
||||
modes. For example, to parse bold/italic only.
|
||||
"""
|
||||
from ..utils import PresetType
|
||||
|
||||
|
||||
def make() -> PresetType:
|
||||
return {
|
||||
"options": {
|
||||
"maxNesting": 20, # Internal protection, recursion limit
|
||||
"html": False, # Enable HTML tags in source
|
||||
# this is just a shorthand for .disable(["html_inline", "html_block"])
|
||||
# used by the linkify rule:
|
||||
"linkify": False, # autoconvert URL-like texts to links
|
||||
# used by the replacements and smartquotes rules:
|
||||
# Enable some language-neutral replacements + quotes beautification
|
||||
"typographer": False,
|
||||
# used by the smartquotes rule:
|
||||
# Double + single quotes replacement pairs, when typographer enabled,
|
||||
# and smartquotes on. Could be either a String or an Array.
|
||||
# For example, you can use '«»„“' for Russian, '„“‚‘' for German,
|
||||
# and ['«\xA0', '\xA0»', '‹\xA0', '\xA0›'] for French (including nbsp).
|
||||
"quotes": "\u201c\u201d\u2018\u2019", # /* “”‘’ */
|
||||
# Renderer specific; these options are used directly in the HTML renderer
|
||||
"xhtmlOut": False, # Use '/' to close single tags (<br />)
|
||||
"breaks": False, # Convert '\n' in paragraphs into <br>
|
||||
"langPrefix": "language-", # CSS language prefix for fenced blocks
|
||||
# Highlighter function. Should return escaped HTML,
|
||||
# or '' if the source string is not changed and should be escaped externally.
|
||||
# If result starts with <pre... internal wrapper is skipped.
|
||||
# function (/*str, lang, attrs*/) { return ''; }
|
||||
"highlight": None,
|
||||
},
|
||||
"components": {
|
||||
"core": {"rules": ["normalize", "block", "inline", "text_join"]},
|
||||
"block": {"rules": ["paragraph"]},
|
||||
"inline": {
|
||||
"rules": ["text"],
|
||||
"rules2": ["balance_pairs", "fragments_join"],
|
||||
},
|
||||
},
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
# Marker file for PEP 561
|
||||
Vendored
+336
@@ -0,0 +1,336 @@
|
||||
"""
|
||||
class Renderer
|
||||
|
||||
Generates HTML from parsed token stream. Each instance has independent
|
||||
copy of rules. Those can be rewritten with ease. Also, you can add new
|
||||
rules if you create plugin and adds new token types.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Sequence
|
||||
import inspect
|
||||
from typing import Any, ClassVar, Protocol
|
||||
|
||||
from .common.utils import escapeHtml, unescapeAll
|
||||
from .token import Token
|
||||
from .utils import EnvType, OptionsDict
|
||||
|
||||
|
||||
class RendererProtocol(Protocol):
|
||||
__output__: ClassVar[str]
|
||||
|
||||
def render(
|
||||
self, tokens: Sequence[Token], options: OptionsDict, env: EnvType
|
||||
) -> Any:
|
||||
...
|
||||
|
||||
|
||||
class RendererHTML(RendererProtocol):
|
||||
"""Contains render rules for tokens. Can be updated and extended.
|
||||
|
||||
Example:
|
||||
|
||||
Each rule is called as independent static function with fixed signature:
|
||||
|
||||
::
|
||||
|
||||
class Renderer:
|
||||
def token_type_name(self, tokens, idx, options, env) {
|
||||
# ...
|
||||
return renderedHTML
|
||||
|
||||
::
|
||||
|
||||
class CustomRenderer(RendererHTML):
|
||||
def strong_open(self, tokens, idx, options, env):
|
||||
return '<b>'
|
||||
def strong_close(self, tokens, idx, options, env):
|
||||
return '</b>'
|
||||
|
||||
md = MarkdownIt(renderer_cls=CustomRenderer)
|
||||
|
||||
result = md.render(...)
|
||||
|
||||
See https://github.com/markdown-it/markdown-it/blob/master/lib/renderer.js
|
||||
for more details and examples.
|
||||
"""
|
||||
|
||||
__output__ = "html"
|
||||
|
||||
def __init__(self, parser: Any = None):
|
||||
self.rules = {
|
||||
k: v
|
||||
for k, v in inspect.getmembers(self, predicate=inspect.ismethod)
|
||||
if not (k.startswith("render") or k.startswith("_"))
|
||||
}
|
||||
|
||||
def render(
|
||||
self, tokens: Sequence[Token], options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
"""Takes token stream and generates HTML.
|
||||
|
||||
:param tokens: list on block tokens to render
|
||||
:param options: params of parser instance
|
||||
:param env: additional data from parsed input
|
||||
|
||||
"""
|
||||
result = ""
|
||||
|
||||
for i, token in enumerate(tokens):
|
||||
if token.type == "inline":
|
||||
if token.children:
|
||||
result += self.renderInline(token.children, options, env)
|
||||
elif token.type in self.rules:
|
||||
result += self.rules[token.type](tokens, i, options, env)
|
||||
else:
|
||||
result += self.renderToken(tokens, i, options, env)
|
||||
|
||||
return result
|
||||
|
||||
def renderInline(
|
||||
self, tokens: Sequence[Token], options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
"""The same as ``render``, but for single token of `inline` type.
|
||||
|
||||
:param tokens: list on block tokens to render
|
||||
:param options: params of parser instance
|
||||
:param env: additional data from parsed input (references, for example)
|
||||
"""
|
||||
result = ""
|
||||
|
||||
for i, token in enumerate(tokens):
|
||||
if token.type in self.rules:
|
||||
result += self.rules[token.type](tokens, i, options, env)
|
||||
else:
|
||||
result += self.renderToken(tokens, i, options, env)
|
||||
|
||||
return result
|
||||
|
||||
def renderToken(
|
||||
self,
|
||||
tokens: Sequence[Token],
|
||||
idx: int,
|
||||
options: OptionsDict,
|
||||
env: EnvType,
|
||||
) -> str:
|
||||
"""Default token renderer.
|
||||
|
||||
Can be overridden by custom function
|
||||
|
||||
:param idx: token index to render
|
||||
:param options: params of parser instance
|
||||
"""
|
||||
result = ""
|
||||
needLf = False
|
||||
token = tokens[idx]
|
||||
|
||||
# Tight list paragraphs
|
||||
if token.hidden:
|
||||
return ""
|
||||
|
||||
# Insert a newline between hidden paragraph and subsequent opening
|
||||
# block-level tag.
|
||||
#
|
||||
# For example, here we should insert a newline before blockquote:
|
||||
# - a
|
||||
# >
|
||||
#
|
||||
if token.block and token.nesting != -1 and idx and tokens[idx - 1].hidden:
|
||||
result += "\n"
|
||||
|
||||
# Add token name, e.g. `<img`
|
||||
result += ("</" if token.nesting == -1 else "<") + token.tag
|
||||
|
||||
# Encode attributes, e.g. `<img src="foo"`
|
||||
result += self.renderAttrs(token)
|
||||
|
||||
# Add a slash for self-closing tags, e.g. `<img src="foo" /`
|
||||
if token.nesting == 0 and options["xhtmlOut"]:
|
||||
result += " /"
|
||||
|
||||
# Check if we need to add a newline after this tag
|
||||
if token.block:
|
||||
needLf = True
|
||||
|
||||
if token.nesting == 1 and (idx + 1 < len(tokens)):
|
||||
nextToken = tokens[idx + 1]
|
||||
|
||||
if nextToken.type == "inline" or nextToken.hidden: # noqa: SIM114
|
||||
# Block-level tag containing an inline tag.
|
||||
#
|
||||
needLf = False
|
||||
|
||||
elif nextToken.nesting == -1 and nextToken.tag == token.tag:
|
||||
# Opening tag + closing tag of the same type. E.g. `<li></li>`.
|
||||
#
|
||||
needLf = False
|
||||
|
||||
result += ">\n" if needLf else ">"
|
||||
|
||||
return result
|
||||
|
||||
@staticmethod
|
||||
def renderAttrs(token: Token) -> str:
|
||||
"""Render token attributes to string."""
|
||||
result = ""
|
||||
|
||||
for key, value in token.attrItems():
|
||||
result += " " + escapeHtml(key) + '="' + escapeHtml(str(value)) + '"'
|
||||
|
||||
return result
|
||||
|
||||
def renderInlineAsText(
|
||||
self,
|
||||
tokens: Sequence[Token] | None,
|
||||
options: OptionsDict,
|
||||
env: EnvType,
|
||||
) -> str:
|
||||
"""Special kludge for image `alt` attributes to conform CommonMark spec.
|
||||
|
||||
Don't try to use it! Spec requires to show `alt` content with stripped markup,
|
||||
instead of simple escaping.
|
||||
|
||||
:param tokens: list on block tokens to render
|
||||
:param options: params of parser instance
|
||||
:param env: additional data from parsed input
|
||||
"""
|
||||
result = ""
|
||||
|
||||
for token in tokens or []:
|
||||
if token.type == "text":
|
||||
result += token.content
|
||||
elif token.type == "image":
|
||||
if token.children:
|
||||
result += self.renderInlineAsText(token.children, options, env)
|
||||
elif token.type == "softbreak":
|
||||
result += "\n"
|
||||
|
||||
return result
|
||||
|
||||
###################################################
|
||||
|
||||
def code_inline(
|
||||
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
return (
|
||||
"<code"
|
||||
+ self.renderAttrs(token)
|
||||
+ ">"
|
||||
+ escapeHtml(tokens[idx].content)
|
||||
+ "</code>"
|
||||
)
|
||||
|
||||
def code_block(
|
||||
self,
|
||||
tokens: Sequence[Token],
|
||||
idx: int,
|
||||
options: OptionsDict,
|
||||
env: EnvType,
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
|
||||
return (
|
||||
"<pre"
|
||||
+ self.renderAttrs(token)
|
||||
+ "><code>"
|
||||
+ escapeHtml(tokens[idx].content)
|
||||
+ "</code></pre>\n"
|
||||
)
|
||||
|
||||
def fence(
|
||||
self,
|
||||
tokens: Sequence[Token],
|
||||
idx: int,
|
||||
options: OptionsDict,
|
||||
env: EnvType,
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
info = unescapeAll(token.info).strip() if token.info else ""
|
||||
langName = ""
|
||||
langAttrs = ""
|
||||
|
||||
if info:
|
||||
arr = info.split(maxsplit=1)
|
||||
langName = arr[0]
|
||||
if len(arr) == 2:
|
||||
langAttrs = arr[1]
|
||||
|
||||
if options.highlight:
|
||||
highlighted = options.highlight(
|
||||
token.content, langName, langAttrs
|
||||
) or escapeHtml(token.content)
|
||||
else:
|
||||
highlighted = escapeHtml(token.content)
|
||||
|
||||
if highlighted.startswith("<pre"):
|
||||
return highlighted + "\n"
|
||||
|
||||
# If language exists, inject class gently, without modifying original token.
|
||||
# May be, one day we will add .deepClone() for token and simplify this part, but
|
||||
# now we prefer to keep things local.
|
||||
if info:
|
||||
# Fake token just to render attributes
|
||||
tmpToken = Token(type="", tag="", nesting=0, attrs=token.attrs.copy())
|
||||
tmpToken.attrJoin("class", options.langPrefix + langName)
|
||||
|
||||
return (
|
||||
"<pre><code"
|
||||
+ self.renderAttrs(tmpToken)
|
||||
+ ">"
|
||||
+ highlighted
|
||||
+ "</code></pre>\n"
|
||||
)
|
||||
|
||||
return (
|
||||
"<pre><code"
|
||||
+ self.renderAttrs(token)
|
||||
+ ">"
|
||||
+ highlighted
|
||||
+ "</code></pre>\n"
|
||||
)
|
||||
|
||||
def image(
|
||||
self,
|
||||
tokens: Sequence[Token],
|
||||
idx: int,
|
||||
options: OptionsDict,
|
||||
env: EnvType,
|
||||
) -> str:
|
||||
token = tokens[idx]
|
||||
|
||||
# "alt" attr MUST be set, even if empty. Because it's mandatory and
|
||||
# should be placed on proper position for tests.
|
||||
if token.children:
|
||||
token.attrSet("alt", self.renderInlineAsText(token.children, options, env))
|
||||
else:
|
||||
token.attrSet("alt", "")
|
||||
|
||||
return self.renderToken(tokens, idx, options, env)
|
||||
|
||||
def hardbreak(
|
||||
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
return "<br />\n" if options.xhtmlOut else "<br>\n"
|
||||
|
||||
def softbreak(
|
||||
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
return (
|
||||
("<br />\n" if options.xhtmlOut else "<br>\n") if options.breaks else "\n"
|
||||
)
|
||||
|
||||
def text(
|
||||
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
return escapeHtml(tokens[idx].content)
|
||||
|
||||
def html_block(
|
||||
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
return tokens[idx].content
|
||||
|
||||
def html_inline(
|
||||
self, tokens: Sequence[Token], idx: int, options: OptionsDict, env: EnvType
|
||||
) -> str:
|
||||
return tokens[idx].content
|
||||
Vendored
+276
@@ -0,0 +1,276 @@
|
||||
"""
|
||||
class Ruler
|
||||
|
||||
Helper class, used by [[MarkdownIt#core]], [[MarkdownIt#block]] and
|
||||
[[MarkdownIt#inline]] to manage sequences of functions (rules):
|
||||
|
||||
- keep rules in defined order
|
||||
- assign the name to each rule
|
||||
- enable/disable rules
|
||||
- add/replace rules
|
||||
- allow assign rules to additional named chains (in the same)
|
||||
- caching lists of active rules
|
||||
|
||||
You will not need use this class directly until write plugins. For simple
|
||||
rules control use [[MarkdownIt.disable]], [[MarkdownIt.enable]] and
|
||||
[[MarkdownIt.use]].
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from collections.abc import Iterable
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING, Generic, TypedDict, TypeVar
|
||||
import warnings
|
||||
|
||||
from markdown_it._compat import DATACLASS_KWARGS
|
||||
|
||||
from .utils import EnvType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from markdown_it import MarkdownIt
|
||||
|
||||
|
||||
class StateBase:
|
||||
def __init__(self, src: str, md: MarkdownIt, env: EnvType):
|
||||
self.src = src
|
||||
self.env = env
|
||||
self.md = md
|
||||
|
||||
@property
|
||||
def src(self) -> str:
|
||||
return self._src
|
||||
|
||||
@src.setter
|
||||
def src(self, value: str) -> None:
|
||||
self._src = value
|
||||
self._srcCharCode: tuple[int, ...] | None = None
|
||||
|
||||
@property
|
||||
def srcCharCode(self) -> tuple[int, ...]:
|
||||
warnings.warn(
|
||||
"StateBase.srcCharCode is deprecated. Use StateBase.src instead.",
|
||||
DeprecationWarning,
|
||||
stacklevel=2,
|
||||
)
|
||||
if self._srcCharCode is None:
|
||||
self._srcCharCode = tuple(ord(c) for c in self._src)
|
||||
return self._srcCharCode
|
||||
|
||||
|
||||
class RuleOptionsType(TypedDict, total=False):
|
||||
alt: list[str]
|
||||
|
||||
|
||||
RuleFuncTv = TypeVar("RuleFuncTv")
|
||||
"""A rule function, whose signature is dependent on the state type."""
|
||||
|
||||
|
||||
@dataclass(**DATACLASS_KWARGS)
|
||||
class Rule(Generic[RuleFuncTv]):
|
||||
name: str
|
||||
enabled: bool
|
||||
fn: RuleFuncTv = field(repr=False)
|
||||
alt: list[str]
|
||||
|
||||
|
||||
class Ruler(Generic[RuleFuncTv]):
|
||||
def __init__(self) -> None:
|
||||
# List of added rules.
|
||||
self.__rules__: list[Rule[RuleFuncTv]] = []
|
||||
# Cached rule chains.
|
||||
# First level - chain name, '' for default.
|
||||
# Second level - diginal anchor for fast filtering by charcodes.
|
||||
self.__cache__: dict[str, list[RuleFuncTv]] | None = None
|
||||
|
||||
def __find__(self, name: str) -> int:
|
||||
"""Find rule index by name"""
|
||||
for i, rule in enumerate(self.__rules__):
|
||||
if rule.name == name:
|
||||
return i
|
||||
return -1
|
||||
|
||||
def __compile__(self) -> None:
|
||||
"""Build rules lookup cache"""
|
||||
chains = {""}
|
||||
# collect unique names
|
||||
for rule in self.__rules__:
|
||||
if not rule.enabled:
|
||||
continue
|
||||
for name in rule.alt:
|
||||
chains.add(name)
|
||||
self.__cache__ = {}
|
||||
for chain in chains:
|
||||
self.__cache__[chain] = []
|
||||
for rule in self.__rules__:
|
||||
if not rule.enabled:
|
||||
continue
|
||||
if chain and (chain not in rule.alt):
|
||||
continue
|
||||
self.__cache__[chain].append(rule.fn)
|
||||
|
||||
def at(
|
||||
self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
|
||||
) -> None:
|
||||
"""Replace rule by name with new function & options.
|
||||
|
||||
:param ruleName: rule name to replace.
|
||||
:param fn: new rule function.
|
||||
:param options: new rule options (not mandatory).
|
||||
:raises: KeyError if name not found
|
||||
"""
|
||||
index = self.__find__(ruleName)
|
||||
options = options or {}
|
||||
if index == -1:
|
||||
raise KeyError(f"Parser rule not found: {ruleName}")
|
||||
self.__rules__[index].fn = fn
|
||||
self.__rules__[index].alt = options.get("alt", [])
|
||||
self.__cache__ = None
|
||||
|
||||
def before(
|
||||
self,
|
||||
beforeName: str,
|
||||
ruleName: str,
|
||||
fn: RuleFuncTv,
|
||||
options: RuleOptionsType | None = None,
|
||||
) -> None:
|
||||
"""Add new rule to chain before one with given name.
|
||||
|
||||
:param beforeName: new rule will be added before this one.
|
||||
:param ruleName: new rule will be added before this one.
|
||||
:param fn: new rule function.
|
||||
:param options: new rule options (not mandatory).
|
||||
:raises: KeyError if name not found
|
||||
"""
|
||||
index = self.__find__(beforeName)
|
||||
options = options or {}
|
||||
if index == -1:
|
||||
raise KeyError(f"Parser rule not found: {beforeName}")
|
||||
self.__rules__.insert(
|
||||
index, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
|
||||
)
|
||||
self.__cache__ = None
|
||||
|
||||
def after(
|
||||
self,
|
||||
afterName: str,
|
||||
ruleName: str,
|
||||
fn: RuleFuncTv,
|
||||
options: RuleOptionsType | None = None,
|
||||
) -> None:
|
||||
"""Add new rule to chain after one with given name.
|
||||
|
||||
:param afterName: new rule will be added after this one.
|
||||
:param ruleName: new rule will be added after this one.
|
||||
:param fn: new rule function.
|
||||
:param options: new rule options (not mandatory).
|
||||
:raises: KeyError if name not found
|
||||
"""
|
||||
index = self.__find__(afterName)
|
||||
options = options or {}
|
||||
if index == -1:
|
||||
raise KeyError(f"Parser rule not found: {afterName}")
|
||||
self.__rules__.insert(
|
||||
index + 1, Rule[RuleFuncTv](ruleName, True, fn, options.get("alt", []))
|
||||
)
|
||||
self.__cache__ = None
|
||||
|
||||
def push(
|
||||
self, ruleName: str, fn: RuleFuncTv, options: RuleOptionsType | None = None
|
||||
) -> None:
|
||||
"""Push new rule to the end of chain.
|
||||
|
||||
:param ruleName: new rule will be added to the end of chain.
|
||||
:param fn: new rule function.
|
||||
:param options: new rule options (not mandatory).
|
||||
|
||||
"""
|
||||
self.__rules__.append(
|
||||
Rule[RuleFuncTv](ruleName, True, fn, (options or {}).get("alt", []))
|
||||
)
|
||||
self.__cache__ = None
|
||||
|
||||
def enable(
|
||||
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
||||
) -> list[str]:
|
||||
"""Enable rules with given names.
|
||||
|
||||
:param names: name or list of rule names to enable.
|
||||
:param ignoreInvalid: ignore errors when rule not found
|
||||
:raises: KeyError if name not found and not ignoreInvalid
|
||||
:return: list of found rule names
|
||||
"""
|
||||
if isinstance(names, str):
|
||||
names = [names]
|
||||
result: list[str] = []
|
||||
for name in names:
|
||||
idx = self.__find__(name)
|
||||
if (idx < 0) and ignoreInvalid:
|
||||
continue
|
||||
if (idx < 0) and not ignoreInvalid:
|
||||
raise KeyError(f"Rules manager: invalid rule name {name}")
|
||||
self.__rules__[idx].enabled = True
|
||||
result.append(name)
|
||||
self.__cache__ = None
|
||||
return result
|
||||
|
||||
def enableOnly(
|
||||
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
||||
) -> list[str]:
|
||||
"""Enable rules with given names, and disable everything else.
|
||||
|
||||
:param names: name or list of rule names to enable.
|
||||
:param ignoreInvalid: ignore errors when rule not found
|
||||
:raises: KeyError if name not found and not ignoreInvalid
|
||||
:return: list of found rule names
|
||||
"""
|
||||
if isinstance(names, str):
|
||||
names = [names]
|
||||
for rule in self.__rules__:
|
||||
rule.enabled = False
|
||||
return self.enable(names, ignoreInvalid)
|
||||
|
||||
def disable(
|
||||
self, names: str | Iterable[str], ignoreInvalid: bool = False
|
||||
) -> list[str]:
|
||||
"""Disable rules with given names.
|
||||
|
||||
:param names: name or list of rule names to enable.
|
||||
:param ignoreInvalid: ignore errors when rule not found
|
||||
:raises: KeyError if name not found and not ignoreInvalid
|
||||
:return: list of found rule names
|
||||
"""
|
||||
if isinstance(names, str):
|
||||
names = [names]
|
||||
result = []
|
||||
for name in names:
|
||||
idx = self.__find__(name)
|
||||
if (idx < 0) and ignoreInvalid:
|
||||
continue
|
||||
if (idx < 0) and not ignoreInvalid:
|
||||
raise KeyError(f"Rules manager: invalid rule name {name}")
|
||||
self.__rules__[idx].enabled = False
|
||||
result.append(name)
|
||||
self.__cache__ = None
|
||||
return result
|
||||
|
||||
def getRules(self, chainName: str = "") -> list[RuleFuncTv]:
|
||||
"""Return array of active functions (rules) for given chain name.
|
||||
It analyzes rules configuration, compiles caches if not exists and returns result.
|
||||
|
||||
Default chain name is `''` (empty string). It can't be skipped.
|
||||
That's done intentionally, to keep signature monomorphic for high speed.
|
||||
|
||||
"""
|
||||
if self.__cache__ is None:
|
||||
self.__compile__()
|
||||
assert self.__cache__ is not None
|
||||
# Chain can be empty, if rules disabled. But we still have to return Array.
|
||||
return self.__cache__.get(chainName, []) or []
|
||||
|
||||
def get_all_rules(self) -> list[str]:
|
||||
"""Return all available rule names."""
|
||||
return [r.name for r in self.__rules__]
|
||||
|
||||
def get_active_rules(self) -> list[str]:
|
||||
"""Return the active rule names."""
|
||||
return [r.name for r in self.__rules__ if r.enabled]
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
__all__ = (
|
||||
"StateBlock",
|
||||
"paragraph",
|
||||
"heading",
|
||||
"lheading",
|
||||
"code",
|
||||
"fence",
|
||||
"hr",
|
||||
"list_block",
|
||||
"reference",
|
||||
"blockquote",
|
||||
"html_block",
|
||||
"table",
|
||||
)
|
||||
|
||||
from .blockquote import blockquote
|
||||
from .code import code
|
||||
from .fence import fence
|
||||
from .heading import heading
|
||||
from .hr import hr
|
||||
from .html_block import html_block
|
||||
from .lheading import lheading
|
||||
from .list import list_block
|
||||
from .paragraph import paragraph
|
||||
from .reference import reference
|
||||
from .state_block import StateBlock
|
||||
from .table import table
|
||||
+299
@@ -0,0 +1,299 @@
|
||||
# Block quotes
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from ..common.utils import isStrSpace
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def blockquote(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug(
|
||||
"entering blockquote: %s, %s, %s, %s", state, startLine, endLine, silent
|
||||
)
|
||||
|
||||
oldLineMax = state.lineMax
|
||||
pos = state.bMarks[startLine] + state.tShift[startLine]
|
||||
max = state.eMarks[startLine]
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
# check the block quote marker
|
||||
try:
|
||||
if state.src[pos] != ">":
|
||||
return False
|
||||
except IndexError:
|
||||
return False
|
||||
pos += 1
|
||||
|
||||
# we know that it's going to be a valid blockquote,
|
||||
# so no point trying to find the end of it in silent mode
|
||||
if silent:
|
||||
return True
|
||||
|
||||
# set offset past spaces and ">"
|
||||
initial = offset = state.sCount[startLine] + 1
|
||||
|
||||
try:
|
||||
second_char: str | None = state.src[pos]
|
||||
except IndexError:
|
||||
second_char = None
|
||||
|
||||
# skip one optional space after '>'
|
||||
if second_char == " ":
|
||||
# ' > test '
|
||||
# ^ -- position start of line here:
|
||||
pos += 1
|
||||
initial += 1
|
||||
offset += 1
|
||||
adjustTab = False
|
||||
spaceAfterMarker = True
|
||||
elif second_char == "\t":
|
||||
spaceAfterMarker = True
|
||||
|
||||
if (state.bsCount[startLine] + offset) % 4 == 3:
|
||||
# ' >\t test '
|
||||
# ^ -- position start of line here (tab has width==1)
|
||||
pos += 1
|
||||
initial += 1
|
||||
offset += 1
|
||||
adjustTab = False
|
||||
else:
|
||||
# ' >\t test '
|
||||
# ^ -- position start of line here + shift bsCount slightly
|
||||
# to make extra space appear
|
||||
adjustTab = True
|
||||
|
||||
else:
|
||||
spaceAfterMarker = False
|
||||
|
||||
oldBMarks = [state.bMarks[startLine]]
|
||||
state.bMarks[startLine] = pos
|
||||
|
||||
while pos < max:
|
||||
ch = state.src[pos]
|
||||
|
||||
if isStrSpace(ch):
|
||||
if ch == "\t":
|
||||
offset += (
|
||||
4
|
||||
- (offset + state.bsCount[startLine] + (1 if adjustTab else 0)) % 4
|
||||
)
|
||||
else:
|
||||
offset += 1
|
||||
|
||||
else:
|
||||
break
|
||||
|
||||
pos += 1
|
||||
|
||||
oldBSCount = [state.bsCount[startLine]]
|
||||
state.bsCount[startLine] = (
|
||||
state.sCount[startLine] + 1 + (1 if spaceAfterMarker else 0)
|
||||
)
|
||||
|
||||
lastLineEmpty = pos >= max
|
||||
|
||||
oldSCount = [state.sCount[startLine]]
|
||||
state.sCount[startLine] = offset - initial
|
||||
|
||||
oldTShift = [state.tShift[startLine]]
|
||||
state.tShift[startLine] = pos - state.bMarks[startLine]
|
||||
|
||||
terminatorRules = state.md.block.ruler.getRules("blockquote")
|
||||
|
||||
oldParentType = state.parentType
|
||||
state.parentType = "blockquote"
|
||||
|
||||
# Search the end of the block
|
||||
#
|
||||
# Block ends with either:
|
||||
# 1. an empty line outside:
|
||||
# ```
|
||||
# > test
|
||||
#
|
||||
# ```
|
||||
# 2. an empty line inside:
|
||||
# ```
|
||||
# >
|
||||
# test
|
||||
# ```
|
||||
# 3. another tag:
|
||||
# ```
|
||||
# > test
|
||||
# - - -
|
||||
# ```
|
||||
|
||||
# for (nextLine = startLine + 1; nextLine < endLine; nextLine++) {
|
||||
nextLine = startLine + 1
|
||||
while nextLine < endLine:
|
||||
# check if it's outdented, i.e. it's inside list item and indented
|
||||
# less than said list item:
|
||||
#
|
||||
# ```
|
||||
# 1. anything
|
||||
# > current blockquote
|
||||
# 2. checking this line
|
||||
# ```
|
||||
isOutdented = state.sCount[nextLine] < state.blkIndent
|
||||
|
||||
pos = state.bMarks[nextLine] + state.tShift[nextLine]
|
||||
max = state.eMarks[nextLine]
|
||||
|
||||
if pos >= max:
|
||||
# Case 1: line is not inside the blockquote, and this line is empty.
|
||||
break
|
||||
|
||||
evaluatesTrue = state.src[pos] == ">" and not isOutdented
|
||||
pos += 1
|
||||
if evaluatesTrue:
|
||||
# This line is inside the blockquote.
|
||||
|
||||
# set offset past spaces and ">"
|
||||
initial = offset = state.sCount[nextLine] + 1
|
||||
|
||||
try:
|
||||
next_char: str | None = state.src[pos]
|
||||
except IndexError:
|
||||
next_char = None
|
||||
|
||||
# skip one optional space after '>'
|
||||
if next_char == " ":
|
||||
# ' > test '
|
||||
# ^ -- position start of line here:
|
||||
pos += 1
|
||||
initial += 1
|
||||
offset += 1
|
||||
adjustTab = False
|
||||
spaceAfterMarker = True
|
||||
elif next_char == "\t":
|
||||
spaceAfterMarker = True
|
||||
|
||||
if (state.bsCount[nextLine] + offset) % 4 == 3:
|
||||
# ' >\t test '
|
||||
# ^ -- position start of line here (tab has width==1)
|
||||
pos += 1
|
||||
initial += 1
|
||||
offset += 1
|
||||
adjustTab = False
|
||||
else:
|
||||
# ' >\t test '
|
||||
# ^ -- position start of line here + shift bsCount slightly
|
||||
# to make extra space appear
|
||||
adjustTab = True
|
||||
|
||||
else:
|
||||
spaceAfterMarker = False
|
||||
|
||||
oldBMarks.append(state.bMarks[nextLine])
|
||||
state.bMarks[nextLine] = pos
|
||||
|
||||
while pos < max:
|
||||
ch = state.src[pos]
|
||||
|
||||
if isStrSpace(ch):
|
||||
if ch == "\t":
|
||||
offset += (
|
||||
4
|
||||
- (
|
||||
offset
|
||||
+ state.bsCount[nextLine]
|
||||
+ (1 if adjustTab else 0)
|
||||
)
|
||||
% 4
|
||||
)
|
||||
else:
|
||||
offset += 1
|
||||
else:
|
||||
break
|
||||
|
||||
pos += 1
|
||||
|
||||
lastLineEmpty = pos >= max
|
||||
|
||||
oldBSCount.append(state.bsCount[nextLine])
|
||||
state.bsCount[nextLine] = (
|
||||
state.sCount[nextLine] + 1 + (1 if spaceAfterMarker else 0)
|
||||
)
|
||||
|
||||
oldSCount.append(state.sCount[nextLine])
|
||||
state.sCount[nextLine] = offset - initial
|
||||
|
||||
oldTShift.append(state.tShift[nextLine])
|
||||
state.tShift[nextLine] = pos - state.bMarks[nextLine]
|
||||
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
# Case 2: line is not inside the blockquote, and the last line was empty.
|
||||
if lastLineEmpty:
|
||||
break
|
||||
|
||||
# Case 3: another tag found.
|
||||
terminate = False
|
||||
|
||||
for terminatorRule in terminatorRules:
|
||||
if terminatorRule(state, nextLine, endLine, True):
|
||||
terminate = True
|
||||
break
|
||||
|
||||
if terminate:
|
||||
# Quirk to enforce "hard termination mode" for paragraphs;
|
||||
# normally if you call `tokenize(state, startLine, nextLine)`,
|
||||
# paragraphs will look below nextLine for paragraph continuation,
|
||||
# but if blockquote is terminated by another tag, they shouldn't
|
||||
state.lineMax = nextLine
|
||||
|
||||
if state.blkIndent != 0:
|
||||
# state.blkIndent was non-zero, we now set it to zero,
|
||||
# so we need to re-calculate all offsets to appear as
|
||||
# if indent wasn't changed
|
||||
oldBMarks.append(state.bMarks[nextLine])
|
||||
oldBSCount.append(state.bsCount[nextLine])
|
||||
oldTShift.append(state.tShift[nextLine])
|
||||
oldSCount.append(state.sCount[nextLine])
|
||||
state.sCount[nextLine] -= state.blkIndent
|
||||
|
||||
break
|
||||
|
||||
oldBMarks.append(state.bMarks[nextLine])
|
||||
oldBSCount.append(state.bsCount[nextLine])
|
||||
oldTShift.append(state.tShift[nextLine])
|
||||
oldSCount.append(state.sCount[nextLine])
|
||||
|
||||
# A negative indentation means that this is a paragraph continuation
|
||||
#
|
||||
state.sCount[nextLine] = -1
|
||||
|
||||
nextLine += 1
|
||||
|
||||
oldIndent = state.blkIndent
|
||||
state.blkIndent = 0
|
||||
|
||||
token = state.push("blockquote_open", "blockquote", 1)
|
||||
token.markup = ">"
|
||||
token.map = lines = [startLine, 0]
|
||||
|
||||
state.md.block.tokenize(state, startLine, nextLine)
|
||||
|
||||
token = state.push("blockquote_close", "blockquote", -1)
|
||||
token.markup = ">"
|
||||
|
||||
state.lineMax = oldLineMax
|
||||
state.parentType = oldParentType
|
||||
lines[1] = state.line
|
||||
|
||||
# Restore original tShift; this might not be necessary since the parser
|
||||
# has already been here, but just to make sure we can do that.
|
||||
for i, item in enumerate(oldTShift):
|
||||
state.bMarks[i + startLine] = oldBMarks[i]
|
||||
state.tShift[i + startLine] = item
|
||||
state.sCount[i + startLine] = oldSCount[i]
|
||||
state.bsCount[i + startLine] = oldBSCount[i]
|
||||
|
||||
state.blkIndent = oldIndent
|
||||
|
||||
return True
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
"""Code block (4 spaces padded)."""
|
||||
import logging
|
||||
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def code(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug("entering code: %s, %s, %s, %s", state, startLine, endLine, silent)
|
||||
|
||||
if not state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
last = nextLine = startLine + 1
|
||||
|
||||
while nextLine < endLine:
|
||||
if state.isEmpty(nextLine):
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
if state.is_code_block(nextLine):
|
||||
nextLine += 1
|
||||
last = nextLine
|
||||
continue
|
||||
|
||||
break
|
||||
|
||||
state.line = last
|
||||
|
||||
token = state.push("code_block", "code", 0)
|
||||
token.content = state.getLines(startLine, last, 4 + state.blkIndent, False) + "\n"
|
||||
token.map = [startLine, state.line]
|
||||
|
||||
return True
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
# fences (``` lang, ~~~ lang)
|
||||
import logging
|
||||
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def fence(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug("entering fence: %s, %s, %s, %s", state, startLine, endLine, silent)
|
||||
|
||||
haveEndMarker = False
|
||||
pos = state.bMarks[startLine] + state.tShift[startLine]
|
||||
maximum = state.eMarks[startLine]
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
if pos + 3 > maximum:
|
||||
return False
|
||||
|
||||
marker = state.src[pos]
|
||||
|
||||
if marker not in ("~", "`"):
|
||||
return False
|
||||
|
||||
# scan marker length
|
||||
mem = pos
|
||||
pos = state.skipCharsStr(pos, marker)
|
||||
|
||||
length = pos - mem
|
||||
|
||||
if length < 3:
|
||||
return False
|
||||
|
||||
markup = state.src[mem:pos]
|
||||
params = state.src[pos:maximum]
|
||||
|
||||
if marker == "`" and marker in params:
|
||||
return False
|
||||
|
||||
# Since start is found, we can report success here in validation mode
|
||||
if silent:
|
||||
return True
|
||||
|
||||
# search end of block
|
||||
nextLine = startLine
|
||||
|
||||
while True:
|
||||
nextLine += 1
|
||||
if nextLine >= endLine:
|
||||
# unclosed block should be autoclosed by end of document.
|
||||
# also block seems to be autoclosed by end of parent
|
||||
break
|
||||
|
||||
pos = mem = state.bMarks[nextLine] + state.tShift[nextLine]
|
||||
maximum = state.eMarks[nextLine]
|
||||
|
||||
if pos < maximum and state.sCount[nextLine] < state.blkIndent:
|
||||
# non-empty line with negative indent should stop the list:
|
||||
# - ```
|
||||
# test
|
||||
break
|
||||
|
||||
try:
|
||||
if state.src[pos] != marker:
|
||||
continue
|
||||
except IndexError:
|
||||
break
|
||||
|
||||
if state.is_code_block(nextLine):
|
||||
continue
|
||||
|
||||
pos = state.skipCharsStr(pos, marker)
|
||||
|
||||
# closing code fence must be at least as long as the opening one
|
||||
if pos - mem < length:
|
||||
continue
|
||||
|
||||
# make sure tail has spaces only
|
||||
pos = state.skipSpaces(pos)
|
||||
|
||||
if pos < maximum:
|
||||
continue
|
||||
|
||||
haveEndMarker = True
|
||||
# found!
|
||||
break
|
||||
|
||||
# If a fence has heading spaces, they should be removed from its inner block
|
||||
length = state.sCount[startLine]
|
||||
|
||||
state.line = nextLine + (1 if haveEndMarker else 0)
|
||||
|
||||
token = state.push("fence", "code", 0)
|
||||
token.info = params
|
||||
token.content = state.getLines(startLine + 1, nextLine, length, True)
|
||||
token.markup = markup
|
||||
token.map = [startLine, state.line]
|
||||
|
||||
return True
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
""" Atex heading (#, ##, ...) """
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
from ..common.utils import isStrSpace
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def heading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug("entering heading: %s, %s, %s, %s", state, startLine, endLine, silent)
|
||||
|
||||
pos = state.bMarks[startLine] + state.tShift[startLine]
|
||||
maximum = state.eMarks[startLine]
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
ch: str | None = state.src[pos]
|
||||
|
||||
if ch != "#" or pos >= maximum:
|
||||
return False
|
||||
|
||||
# count heading level
|
||||
level = 1
|
||||
pos += 1
|
||||
try:
|
||||
ch = state.src[pos]
|
||||
except IndexError:
|
||||
ch = None
|
||||
while ch == "#" and pos < maximum and level <= 6:
|
||||
level += 1
|
||||
pos += 1
|
||||
try:
|
||||
ch = state.src[pos]
|
||||
except IndexError:
|
||||
ch = None
|
||||
|
||||
if level > 6 or (pos < maximum and not isStrSpace(ch)):
|
||||
return False
|
||||
|
||||
if silent:
|
||||
return True
|
||||
|
||||
# Let's cut tails like ' ### ' from the end of string
|
||||
|
||||
maximum = state.skipSpacesBack(maximum, pos)
|
||||
tmp = state.skipCharsStrBack(maximum, "#", pos)
|
||||
if tmp > pos and isStrSpace(state.src[tmp - 1]):
|
||||
maximum = tmp
|
||||
|
||||
state.line = startLine + 1
|
||||
|
||||
token = state.push("heading_open", "h" + str(level), 1)
|
||||
token.markup = "########"[:level]
|
||||
token.map = [startLine, state.line]
|
||||
|
||||
token = state.push("inline", "", 0)
|
||||
token.content = state.src[pos:maximum].strip()
|
||||
token.map = [startLine, state.line]
|
||||
token.children = []
|
||||
|
||||
token = state.push("heading_close", "h" + str(level), -1)
|
||||
token.markup = "########"[:level]
|
||||
|
||||
return True
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
"""Horizontal rule
|
||||
|
||||
At least 3 of these characters on a line * - _
|
||||
"""
|
||||
import logging
|
||||
|
||||
from ..common.utils import isStrSpace
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def hr(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug("entering hr: %s, %s, %s, %s", state, startLine, endLine, silent)
|
||||
|
||||
pos = state.bMarks[startLine] + state.tShift[startLine]
|
||||
maximum = state.eMarks[startLine]
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
try:
|
||||
marker = state.src[pos]
|
||||
except IndexError:
|
||||
return False
|
||||
pos += 1
|
||||
|
||||
# Check hr marker
|
||||
if marker not in ("*", "-", "_"):
|
||||
return False
|
||||
|
||||
# markers can be mixed with spaces, but there should be at least 3 of them
|
||||
|
||||
cnt = 1
|
||||
while pos < maximum:
|
||||
ch = state.src[pos]
|
||||
pos += 1
|
||||
if ch != marker and not isStrSpace(ch):
|
||||
return False
|
||||
if ch == marker:
|
||||
cnt += 1
|
||||
|
||||
if cnt < 3:
|
||||
return False
|
||||
|
||||
if silent:
|
||||
return True
|
||||
|
||||
state.line = startLine + 1
|
||||
|
||||
token = state.push("hr", "hr", 0)
|
||||
token.map = [startLine, state.line]
|
||||
token.markup = marker * (cnt + 1)
|
||||
|
||||
return True
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
# HTML block
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
from ..common.html_blocks import block_names
|
||||
from ..common.html_re import HTML_OPEN_CLOSE_TAG_STR
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# An array of opening and corresponding closing sequences for html tags,
|
||||
# last argument defines whether it can terminate a paragraph or not
|
||||
HTML_SEQUENCES: list[tuple[re.Pattern[str], re.Pattern[str], bool]] = [
|
||||
(
|
||||
re.compile(r"^<(script|pre|style|textarea)(?=(\s|>|$))", re.IGNORECASE),
|
||||
re.compile(r"<\/(script|pre|style|textarea)>", re.IGNORECASE),
|
||||
True,
|
||||
),
|
||||
(re.compile(r"^<!--"), re.compile(r"-->"), True),
|
||||
(re.compile(r"^<\?"), re.compile(r"\?>"), True),
|
||||
(re.compile(r"^<![A-Z]"), re.compile(r">"), True),
|
||||
(re.compile(r"^<!\[CDATA\["), re.compile(r"\]\]>"), True),
|
||||
(
|
||||
re.compile("^</?(" + "|".join(block_names) + ")(?=(\\s|/?>|$))", re.IGNORECASE),
|
||||
re.compile(r"^$"),
|
||||
True,
|
||||
),
|
||||
(re.compile(HTML_OPEN_CLOSE_TAG_STR + "\\s*$"), re.compile(r"^$"), False),
|
||||
]
|
||||
|
||||
|
||||
def html_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug(
|
||||
"entering html_block: %s, %s, %s, %s", state, startLine, endLine, silent
|
||||
)
|
||||
pos = state.bMarks[startLine] + state.tShift[startLine]
|
||||
maximum = state.eMarks[startLine]
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
if not state.md.options.get("html", None):
|
||||
return False
|
||||
|
||||
if state.src[pos] != "<":
|
||||
return False
|
||||
|
||||
lineText = state.src[pos:maximum]
|
||||
|
||||
html_seq = None
|
||||
for HTML_SEQUENCE in HTML_SEQUENCES:
|
||||
if HTML_SEQUENCE[0].search(lineText):
|
||||
html_seq = HTML_SEQUENCE
|
||||
break
|
||||
|
||||
if not html_seq:
|
||||
return False
|
||||
|
||||
if silent:
|
||||
# true if this sequence can be a terminator, false otherwise
|
||||
return html_seq[2]
|
||||
|
||||
nextLine = startLine + 1
|
||||
|
||||
# If we are here - we detected HTML block.
|
||||
# Let's roll down till block end.
|
||||
if not html_seq[1].search(lineText):
|
||||
while nextLine < endLine:
|
||||
if state.sCount[nextLine] < state.blkIndent:
|
||||
break
|
||||
|
||||
pos = state.bMarks[nextLine] + state.tShift[nextLine]
|
||||
maximum = state.eMarks[nextLine]
|
||||
lineText = state.src[pos:maximum]
|
||||
|
||||
if html_seq[1].search(lineText):
|
||||
if len(lineText) != 0:
|
||||
nextLine += 1
|
||||
break
|
||||
nextLine += 1
|
||||
|
||||
state.line = nextLine
|
||||
|
||||
token = state.push("html_block", "", 0)
|
||||
token.map = [startLine, nextLine]
|
||||
token.content = state.getLines(startLine, nextLine, state.blkIndent, True)
|
||||
|
||||
return True
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
# lheading (---, ==)
|
||||
import logging
|
||||
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def lheading(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug("entering lheading: %s, %s, %s, %s", state, startLine, endLine, silent)
|
||||
|
||||
level = None
|
||||
nextLine = startLine + 1
|
||||
ruler = state.md.block.ruler
|
||||
terminatorRules = ruler.getRules("paragraph")
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
oldParentType = state.parentType
|
||||
state.parentType = "paragraph" # use paragraph to match terminatorRules
|
||||
|
||||
# jump line-by-line until empty one or EOF
|
||||
while nextLine < endLine and not state.isEmpty(nextLine):
|
||||
# this would be a code block normally, but after paragraph
|
||||
# it's considered a lazy continuation regardless of what's there
|
||||
if state.sCount[nextLine] - state.blkIndent > 3:
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
# Check for underline in setext header
|
||||
if state.sCount[nextLine] >= state.blkIndent:
|
||||
pos = state.bMarks[nextLine] + state.tShift[nextLine]
|
||||
maximum = state.eMarks[nextLine]
|
||||
|
||||
if pos < maximum:
|
||||
marker = state.src[pos]
|
||||
|
||||
if marker in ("-", "="):
|
||||
pos = state.skipCharsStr(pos, marker)
|
||||
pos = state.skipSpaces(pos)
|
||||
|
||||
# /* = */
|
||||
if pos >= maximum:
|
||||
level = 1 if marker == "=" else 2
|
||||
break
|
||||
|
||||
# quirk for blockquotes, this line should already be checked by that rule
|
||||
if state.sCount[nextLine] < 0:
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
# Some tags can terminate paragraph without empty line.
|
||||
terminate = False
|
||||
for terminatorRule in terminatorRules:
|
||||
if terminatorRule(state, nextLine, endLine, True):
|
||||
terminate = True
|
||||
break
|
||||
if terminate:
|
||||
break
|
||||
|
||||
nextLine += 1
|
||||
|
||||
if not level:
|
||||
# Didn't find valid underline
|
||||
return False
|
||||
|
||||
content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
|
||||
|
||||
state.line = nextLine + 1
|
||||
|
||||
token = state.push("heading_open", "h" + str(level), 1)
|
||||
token.markup = marker
|
||||
token.map = [startLine, state.line]
|
||||
|
||||
token = state.push("inline", "", 0)
|
||||
token.content = content
|
||||
token.map = [startLine, state.line - 1]
|
||||
token.children = []
|
||||
|
||||
token = state.push("heading_close", "h" + str(level), -1)
|
||||
token.markup = marker
|
||||
|
||||
state.parentType = oldParentType
|
||||
|
||||
return True
|
||||
+345
@@ -0,0 +1,345 @@
|
||||
# Lists
|
||||
import logging
|
||||
|
||||
from ..common.utils import isStrSpace
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# Search `[-+*][\n ]`, returns next pos after marker on success
|
||||
# or -1 on fail.
|
||||
def skipBulletListMarker(state: StateBlock, startLine: int) -> int:
|
||||
pos = state.bMarks[startLine] + state.tShift[startLine]
|
||||
maximum = state.eMarks[startLine]
|
||||
|
||||
try:
|
||||
marker = state.src[pos]
|
||||
except IndexError:
|
||||
return -1
|
||||
pos += 1
|
||||
|
||||
if marker not in ("*", "-", "+"):
|
||||
return -1
|
||||
|
||||
if pos < maximum:
|
||||
ch = state.src[pos]
|
||||
|
||||
if not isStrSpace(ch):
|
||||
# " -test " - is not a list item
|
||||
return -1
|
||||
|
||||
return pos
|
||||
|
||||
|
||||
# Search `\d+[.)][\n ]`, returns next pos after marker on success
|
||||
# or -1 on fail.
|
||||
def skipOrderedListMarker(state: StateBlock, startLine: int) -> int:
|
||||
start = state.bMarks[startLine] + state.tShift[startLine]
|
||||
pos = start
|
||||
maximum = state.eMarks[startLine]
|
||||
|
||||
# List marker should have at least 2 chars (digit + dot)
|
||||
if pos + 1 >= maximum:
|
||||
return -1
|
||||
|
||||
ch = state.src[pos]
|
||||
pos += 1
|
||||
|
||||
ch_ord = ord(ch)
|
||||
# /* 0 */ /* 9 */
|
||||
if ch_ord < 0x30 or ch_ord > 0x39:
|
||||
return -1
|
||||
|
||||
while True:
|
||||
# EOL -> fail
|
||||
if pos >= maximum:
|
||||
return -1
|
||||
|
||||
ch = state.src[pos]
|
||||
pos += 1
|
||||
|
||||
# /* 0 */ /* 9 */
|
||||
ch_ord = ord(ch)
|
||||
if ch_ord >= 0x30 and ch_ord <= 0x39:
|
||||
# List marker should have no more than 9 digits
|
||||
# (prevents integer overflow in browsers)
|
||||
if pos - start >= 10:
|
||||
return -1
|
||||
|
||||
continue
|
||||
|
||||
# found valid marker
|
||||
if ch in (")", "."):
|
||||
break
|
||||
|
||||
return -1
|
||||
|
||||
if pos < maximum:
|
||||
ch = state.src[pos]
|
||||
|
||||
if not isStrSpace(ch):
|
||||
# " 1.test " - is not a list item
|
||||
return -1
|
||||
|
||||
return pos
|
||||
|
||||
|
||||
def markTightParagraphs(state: StateBlock, idx: int) -> None:
|
||||
level = state.level + 2
|
||||
|
||||
i = idx + 2
|
||||
length = len(state.tokens) - 2
|
||||
while i < length:
|
||||
if state.tokens[i].level == level and state.tokens[i].type == "paragraph_open":
|
||||
state.tokens[i + 2].hidden = True
|
||||
state.tokens[i].hidden = True
|
||||
i += 2
|
||||
i += 1
|
||||
|
||||
|
||||
def list_block(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug("entering list: %s, %s, %s, %s", state, startLine, endLine, silent)
|
||||
|
||||
isTerminatingParagraph = False
|
||||
tight = True
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
# Special case:
|
||||
# - item 1
|
||||
# - item 2
|
||||
# - item 3
|
||||
# - item 4
|
||||
# - this one is a paragraph continuation
|
||||
if (
|
||||
state.listIndent >= 0
|
||||
and state.sCount[startLine] - state.listIndent >= 4
|
||||
and state.sCount[startLine] < state.blkIndent
|
||||
):
|
||||
return False
|
||||
|
||||
# limit conditions when list can interrupt
|
||||
# a paragraph (validation mode only)
|
||||
# Next list item should still terminate previous list item
|
||||
#
|
||||
# This code can fail if plugins use blkIndent as well as lists,
|
||||
# but I hope the spec gets fixed long before that happens.
|
||||
#
|
||||
if (
|
||||
silent
|
||||
and state.parentType == "paragraph"
|
||||
and state.sCount[startLine] >= state.blkIndent
|
||||
):
|
||||
isTerminatingParagraph = True
|
||||
|
||||
# Detect list type and position after marker
|
||||
posAfterMarker = skipOrderedListMarker(state, startLine)
|
||||
if posAfterMarker >= 0:
|
||||
isOrdered = True
|
||||
start = state.bMarks[startLine] + state.tShift[startLine]
|
||||
markerValue = int(state.src[start : posAfterMarker - 1])
|
||||
|
||||
# If we're starting a new ordered list right after
|
||||
# a paragraph, it should start with 1.
|
||||
if isTerminatingParagraph and markerValue != 1:
|
||||
return False
|
||||
else:
|
||||
posAfterMarker = skipBulletListMarker(state, startLine)
|
||||
if posAfterMarker >= 0:
|
||||
isOrdered = False
|
||||
else:
|
||||
return False
|
||||
|
||||
# If we're starting a new unordered list right after
|
||||
# a paragraph, first line should not be empty.
|
||||
if (
|
||||
isTerminatingParagraph
|
||||
and state.skipSpaces(posAfterMarker) >= state.eMarks[startLine]
|
||||
):
|
||||
return False
|
||||
|
||||
# We should terminate list on style change. Remember first one to compare.
|
||||
markerChar = state.src[posAfterMarker - 1]
|
||||
|
||||
# For validation mode we can terminate immediately
|
||||
if silent:
|
||||
return True
|
||||
|
||||
# Start list
|
||||
listTokIdx = len(state.tokens)
|
||||
|
||||
if isOrdered:
|
||||
token = state.push("ordered_list_open", "ol", 1)
|
||||
if markerValue != 1:
|
||||
token.attrs = {"start": markerValue}
|
||||
|
||||
else:
|
||||
token = state.push("bullet_list_open", "ul", 1)
|
||||
|
||||
token.map = listLines = [startLine, 0]
|
||||
token.markup = markerChar
|
||||
|
||||
#
|
||||
# Iterate list items
|
||||
#
|
||||
|
||||
nextLine = startLine
|
||||
prevEmptyEnd = False
|
||||
terminatorRules = state.md.block.ruler.getRules("list")
|
||||
|
||||
oldParentType = state.parentType
|
||||
state.parentType = "list"
|
||||
|
||||
while nextLine < endLine:
|
||||
pos = posAfterMarker
|
||||
maximum = state.eMarks[nextLine]
|
||||
|
||||
initial = offset = (
|
||||
state.sCount[nextLine]
|
||||
+ posAfterMarker
|
||||
- (state.bMarks[startLine] + state.tShift[startLine])
|
||||
)
|
||||
|
||||
while pos < maximum:
|
||||
ch = state.src[pos]
|
||||
|
||||
if ch == "\t":
|
||||
offset += 4 - (offset + state.bsCount[nextLine]) % 4
|
||||
elif ch == " ":
|
||||
offset += 1
|
||||
else:
|
||||
break
|
||||
|
||||
pos += 1
|
||||
|
||||
contentStart = pos
|
||||
|
||||
# trimming space in "- \n 3" case, indent is 1 here
|
||||
indentAfterMarker = 1 if contentStart >= maximum else offset - initial
|
||||
|
||||
# If we have more than 4 spaces, the indent is 1
|
||||
# (the rest is just indented code block)
|
||||
if indentAfterMarker > 4:
|
||||
indentAfterMarker = 1
|
||||
|
||||
# " - test"
|
||||
# ^^^^^ - calculating total length of this thing
|
||||
indent = initial + indentAfterMarker
|
||||
|
||||
# Run subparser & write tokens
|
||||
token = state.push("list_item_open", "li", 1)
|
||||
token.markup = markerChar
|
||||
token.map = itemLines = [startLine, 0]
|
||||
if isOrdered:
|
||||
token.info = state.src[start : posAfterMarker - 1]
|
||||
|
||||
# change current state, then restore it after parser subcall
|
||||
oldTight = state.tight
|
||||
oldTShift = state.tShift[startLine]
|
||||
oldSCount = state.sCount[startLine]
|
||||
|
||||
# - example list
|
||||
# ^ listIndent position will be here
|
||||
# ^ blkIndent position will be here
|
||||
#
|
||||
oldListIndent = state.listIndent
|
||||
state.listIndent = state.blkIndent
|
||||
state.blkIndent = indent
|
||||
|
||||
state.tight = True
|
||||
state.tShift[startLine] = contentStart - state.bMarks[startLine]
|
||||
state.sCount[startLine] = offset
|
||||
|
||||
if contentStart >= maximum and state.isEmpty(startLine + 1):
|
||||
# workaround for this case
|
||||
# (list item is empty, list terminates before "foo"):
|
||||
# ~~~~~~~~
|
||||
# -
|
||||
#
|
||||
# foo
|
||||
# ~~~~~~~~
|
||||
state.line = min(state.line + 2, endLine)
|
||||
else:
|
||||
# NOTE in list.js this was:
|
||||
# state.md.block.tokenize(state, startLine, endLine, True)
|
||||
# but tokeniz does not take the final parameter
|
||||
state.md.block.tokenize(state, startLine, endLine)
|
||||
|
||||
# If any of list item is tight, mark list as tight
|
||||
if (not state.tight) or prevEmptyEnd:
|
||||
tight = False
|
||||
|
||||
# Item become loose if finish with empty line,
|
||||
# but we should filter last element, because it means list finish
|
||||
prevEmptyEnd = (state.line - startLine) > 1 and state.isEmpty(state.line - 1)
|
||||
|
||||
state.blkIndent = state.listIndent
|
||||
state.listIndent = oldListIndent
|
||||
state.tShift[startLine] = oldTShift
|
||||
state.sCount[startLine] = oldSCount
|
||||
state.tight = oldTight
|
||||
|
||||
token = state.push("list_item_close", "li", -1)
|
||||
token.markup = markerChar
|
||||
|
||||
nextLine = startLine = state.line
|
||||
itemLines[1] = nextLine
|
||||
|
||||
if nextLine >= endLine:
|
||||
break
|
||||
|
||||
contentStart = state.bMarks[startLine]
|
||||
|
||||
#
|
||||
# Try to check if list is terminated or continued.
|
||||
#
|
||||
if state.sCount[nextLine] < state.blkIndent:
|
||||
break
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
break
|
||||
|
||||
# fail if terminating block found
|
||||
terminate = False
|
||||
for terminatorRule in terminatorRules:
|
||||
if terminatorRule(state, nextLine, endLine, True):
|
||||
terminate = True
|
||||
break
|
||||
|
||||
if terminate:
|
||||
break
|
||||
|
||||
# fail if list has another type
|
||||
if isOrdered:
|
||||
posAfterMarker = skipOrderedListMarker(state, nextLine)
|
||||
if posAfterMarker < 0:
|
||||
break
|
||||
start = state.bMarks[nextLine] + state.tShift[nextLine]
|
||||
else:
|
||||
posAfterMarker = skipBulletListMarker(state, nextLine)
|
||||
if posAfterMarker < 0:
|
||||
break
|
||||
|
||||
if markerChar != state.src[posAfterMarker - 1]:
|
||||
break
|
||||
|
||||
# Finalize list
|
||||
if isOrdered:
|
||||
token = state.push("ordered_list_close", "ol", -1)
|
||||
else:
|
||||
token = state.push("bullet_list_close", "ul", -1)
|
||||
|
||||
token.markup = markerChar
|
||||
|
||||
listLines[1] = nextLine
|
||||
state.line = nextLine
|
||||
|
||||
state.parentType = oldParentType
|
||||
|
||||
# mark paragraphs tight if needed
|
||||
if tight:
|
||||
markTightParagraphs(state, listTokIdx)
|
||||
|
||||
return True
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
"""Paragraph."""
|
||||
import logging
|
||||
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def paragraph(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug(
|
||||
"entering paragraph: %s, %s, %s, %s", state, startLine, endLine, silent
|
||||
)
|
||||
|
||||
nextLine = startLine + 1
|
||||
ruler = state.md.block.ruler
|
||||
terminatorRules = ruler.getRules("paragraph")
|
||||
endLine = state.lineMax
|
||||
|
||||
oldParentType = state.parentType
|
||||
state.parentType = "paragraph"
|
||||
|
||||
# jump line-by-line until empty one or EOF
|
||||
while nextLine < endLine:
|
||||
if state.isEmpty(nextLine):
|
||||
break
|
||||
# this would be a code block normally, but after paragraph
|
||||
# it's considered a lazy continuation regardless of what's there
|
||||
if state.sCount[nextLine] - state.blkIndent > 3:
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
# quirk for blockquotes, this line should already be checked by that rule
|
||||
if state.sCount[nextLine] < 0:
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
# Some tags can terminate paragraph without empty line.
|
||||
terminate = False
|
||||
for terminatorRule in terminatorRules:
|
||||
if terminatorRule(state, nextLine, endLine, True):
|
||||
terminate = True
|
||||
break
|
||||
|
||||
if terminate:
|
||||
break
|
||||
|
||||
nextLine += 1
|
||||
|
||||
content = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
|
||||
|
||||
state.line = nextLine
|
||||
|
||||
token = state.push("paragraph_open", "p", 1)
|
||||
token.map = [startLine, state.line]
|
||||
|
||||
token = state.push("inline", "", 0)
|
||||
token.content = content
|
||||
token.map = [startLine, state.line]
|
||||
token.children = []
|
||||
|
||||
token = state.push("paragraph_close", "p", -1)
|
||||
|
||||
state.parentType = oldParentType
|
||||
|
||||
return True
|
||||
+215
@@ -0,0 +1,215 @@
|
||||
import logging
|
||||
|
||||
from ..common.utils import charCodeAt, isSpace, normalizeReference
|
||||
from .state_block import StateBlock
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def reference(state: StateBlock, startLine: int, _endLine: int, silent: bool) -> bool:
|
||||
LOGGER.debug(
|
||||
"entering reference: %s, %s, %s, %s", state, startLine, _endLine, silent
|
||||
)
|
||||
|
||||
lines = 0
|
||||
pos = state.bMarks[startLine] + state.tShift[startLine]
|
||||
maximum = state.eMarks[startLine]
|
||||
nextLine = startLine + 1
|
||||
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
|
||||
if state.src[pos] != "[":
|
||||
return False
|
||||
|
||||
# Simple check to quickly interrupt scan on [link](url) at the start of line.
|
||||
# Can be useful on practice: https:#github.com/markdown-it/markdown-it/issues/54
|
||||
while pos < maximum:
|
||||
# /* ] */ /* \ */ /* : */
|
||||
if state.src[pos] == "]" and state.src[pos - 1] != "\\":
|
||||
if pos + 1 == maximum:
|
||||
return False
|
||||
if state.src[pos + 1] != ":":
|
||||
return False
|
||||
break
|
||||
pos += 1
|
||||
|
||||
endLine = state.lineMax
|
||||
|
||||
# jump line-by-line until empty one or EOF
|
||||
terminatorRules = state.md.block.ruler.getRules("reference")
|
||||
|
||||
oldParentType = state.parentType
|
||||
state.parentType = "reference"
|
||||
|
||||
while nextLine < endLine and not state.isEmpty(nextLine):
|
||||
# this would be a code block normally, but after paragraph
|
||||
# it's considered a lazy continuation regardless of what's there
|
||||
if state.sCount[nextLine] - state.blkIndent > 3:
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
# quirk for blockquotes, this line should already be checked by that rule
|
||||
if state.sCount[nextLine] < 0:
|
||||
nextLine += 1
|
||||
continue
|
||||
|
||||
# Some tags can terminate paragraph without empty line.
|
||||
terminate = False
|
||||
for terminatorRule in terminatorRules:
|
||||
if terminatorRule(state, nextLine, endLine, True):
|
||||
terminate = True
|
||||
break
|
||||
|
||||
if terminate:
|
||||
break
|
||||
|
||||
nextLine += 1
|
||||
|
||||
string = state.getLines(startLine, nextLine, state.blkIndent, False).strip()
|
||||
maximum = len(string)
|
||||
|
||||
labelEnd = None
|
||||
pos = 1
|
||||
while pos < maximum:
|
||||
ch = charCodeAt(string, pos)
|
||||
if ch == 0x5B: # /* [ */
|
||||
return False
|
||||
elif ch == 0x5D: # /* ] */
|
||||
labelEnd = pos
|
||||
break
|
||||
elif ch == 0x0A: # /* \n */
|
||||
lines += 1
|
||||
elif ch == 0x5C: # /* \ */
|
||||
pos += 1
|
||||
if pos < maximum and charCodeAt(string, pos) == 0x0A:
|
||||
lines += 1
|
||||
pos += 1
|
||||
|
||||
if (
|
||||
labelEnd is None or labelEnd < 0 or charCodeAt(string, labelEnd + 1) != 0x3A
|
||||
): # /* : */
|
||||
return False
|
||||
|
||||
# [label]: destination 'title'
|
||||
# ^^^ skip optional whitespace here
|
||||
pos = labelEnd + 2
|
||||
while pos < maximum:
|
||||
ch = charCodeAt(string, pos)
|
||||
if ch == 0x0A:
|
||||
lines += 1
|
||||
elif isSpace(ch):
|
||||
pass
|
||||
else:
|
||||
break
|
||||
pos += 1
|
||||
|
||||
# [label]: destination 'title'
|
||||
# ^^^^^^^^^^^ parse this
|
||||
res = state.md.helpers.parseLinkDestination(string, pos, maximum)
|
||||
if not res.ok:
|
||||
return False
|
||||
|
||||
href = state.md.normalizeLink(res.str)
|
||||
if not state.md.validateLink(href):
|
||||
return False
|
||||
|
||||
pos = res.pos
|
||||
lines += res.lines
|
||||
|
||||
# save cursor state, we could require to rollback later
|
||||
destEndPos = pos
|
||||
destEndLineNo = lines
|
||||
|
||||
# [label]: destination 'title'
|
||||
# ^^^ skipping those spaces
|
||||
start = pos
|
||||
while pos < maximum:
|
||||
ch = charCodeAt(string, pos)
|
||||
if ch == 0x0A:
|
||||
lines += 1
|
||||
elif isSpace(ch):
|
||||
pass
|
||||
else:
|
||||
break
|
||||
pos += 1
|
||||
|
||||
# [label]: destination 'title'
|
||||
# ^^^^^^^ parse this
|
||||
res = state.md.helpers.parseLinkTitle(string, pos, maximum)
|
||||
if pos < maximum and start != pos and res.ok:
|
||||
title = res.str
|
||||
pos = res.pos
|
||||
lines += res.lines
|
||||
else:
|
||||
title = ""
|
||||
pos = destEndPos
|
||||
lines = destEndLineNo
|
||||
|
||||
# skip trailing spaces until the rest of the line
|
||||
while pos < maximum:
|
||||
ch = charCodeAt(string, pos)
|
||||
if not isSpace(ch):
|
||||
break
|
||||
pos += 1
|
||||
|
||||
if pos < maximum and charCodeAt(string, pos) != 0x0A and title:
|
||||
# garbage at the end of the line after title,
|
||||
# but it could still be a valid reference if we roll back
|
||||
title = ""
|
||||
pos = destEndPos
|
||||
lines = destEndLineNo
|
||||
while pos < maximum:
|
||||
ch = charCodeAt(string, pos)
|
||||
if not isSpace(ch):
|
||||
break
|
||||
pos += 1
|
||||
|
||||
if pos < maximum and charCodeAt(string, pos) != 0x0A:
|
||||
# garbage at the end of the line
|
||||
return False
|
||||
|
||||
label = normalizeReference(string[1:labelEnd])
|
||||
if not label:
|
||||
# CommonMark 0.20 disallows empty labels
|
||||
return False
|
||||
|
||||
# Reference can not terminate anything. This check is for safety only.
|
||||
if silent:
|
||||
return True
|
||||
|
||||
if "references" not in state.env:
|
||||
state.env["references"] = {}
|
||||
|
||||
state.line = startLine + lines + 1
|
||||
|
||||
# note, this is not part of markdown-it JS, but is useful for renderers
|
||||
if state.md.options.get("inline_definitions", False):
|
||||
token = state.push("definition", "", 0)
|
||||
token.meta = {
|
||||
"id": label,
|
||||
"title": title,
|
||||
"url": href,
|
||||
"label": string[1:labelEnd],
|
||||
}
|
||||
token.map = [startLine, state.line]
|
||||
|
||||
if label not in state.env["references"]:
|
||||
state.env["references"][label] = {
|
||||
"title": title,
|
||||
"href": href,
|
||||
"map": [startLine, state.line],
|
||||
}
|
||||
else:
|
||||
state.env.setdefault("duplicate_refs", []).append(
|
||||
{
|
||||
"title": title,
|
||||
"href": href,
|
||||
"label": label,
|
||||
"map": [startLine, state.line],
|
||||
}
|
||||
)
|
||||
|
||||
state.parentType = oldParentType
|
||||
|
||||
return True
|
||||
+261
@@ -0,0 +1,261 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Literal
|
||||
|
||||
from ..common.utils import isStrSpace
|
||||
from ..ruler import StateBase
|
||||
from ..token import Token
|
||||
from ..utils import EnvType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from markdown_it.main import MarkdownIt
|
||||
|
||||
|
||||
class StateBlock(StateBase):
|
||||
def __init__(
|
||||
self, src: str, md: MarkdownIt, env: EnvType, tokens: list[Token]
|
||||
) -> None:
|
||||
self.src = src
|
||||
|
||||
# link to parser instance
|
||||
self.md = md
|
||||
|
||||
self.env = env
|
||||
|
||||
#
|
||||
# Internal state variables
|
||||
#
|
||||
|
||||
self.tokens = tokens
|
||||
|
||||
self.bMarks: list[int] = [] # line begin offsets for fast jumps
|
||||
self.eMarks: list[int] = [] # line end offsets for fast jumps
|
||||
# offsets of the first non-space characters (tabs not expanded)
|
||||
self.tShift: list[int] = []
|
||||
self.sCount: list[int] = [] # indents for each line (tabs expanded)
|
||||
|
||||
# An amount of virtual spaces (tabs expanded) between beginning
|
||||
# of each line (bMarks) and real beginning of that line.
|
||||
#
|
||||
# It exists only as a hack because blockquotes override bMarks
|
||||
# losing information in the process.
|
||||
#
|
||||
# It's used only when expanding tabs, you can think about it as
|
||||
# an initial tab length, e.g. bsCount=21 applied to string `\t123`
|
||||
# means first tab should be expanded to 4-21%4 === 3 spaces.
|
||||
#
|
||||
self.bsCount: list[int] = []
|
||||
|
||||
# block parser variables
|
||||
self.blkIndent = 0 # required block content indent (for example, if we are
|
||||
# inside a list, it would be positioned after list marker)
|
||||
self.line = 0 # line index in src
|
||||
self.lineMax = 0 # lines count
|
||||
self.tight = False # loose/tight mode for lists
|
||||
self.ddIndent = -1 # indent of the current dd block (-1 if there isn't any)
|
||||
self.listIndent = -1 # indent of the current list block (-1 if there isn't any)
|
||||
|
||||
# can be 'blockquote', 'list', 'root', 'paragraph' or 'reference'
|
||||
# used in lists to determine if they interrupt a paragraph
|
||||
self.parentType = "root"
|
||||
|
||||
self.level = 0
|
||||
|
||||
# renderer
|
||||
self.result = ""
|
||||
|
||||
# Create caches
|
||||
# Generate markers.
|
||||
indent_found = False
|
||||
|
||||
start = pos = indent = offset = 0
|
||||
length = len(self.src)
|
||||
|
||||
for pos, character in enumerate(self.src):
|
||||
if not indent_found:
|
||||
if isStrSpace(character):
|
||||
indent += 1
|
||||
|
||||
if character == "\t":
|
||||
offset += 4 - offset % 4
|
||||
else:
|
||||
offset += 1
|
||||
continue
|
||||
else:
|
||||
indent_found = True
|
||||
|
||||
if character == "\n" or pos == length - 1:
|
||||
if character != "\n":
|
||||
pos += 1
|
||||
self.bMarks.append(start)
|
||||
self.eMarks.append(pos)
|
||||
self.tShift.append(indent)
|
||||
self.sCount.append(offset)
|
||||
self.bsCount.append(0)
|
||||
|
||||
indent_found = False
|
||||
indent = 0
|
||||
offset = 0
|
||||
start = pos + 1
|
||||
|
||||
# Push fake entry to simplify cache bounds checks
|
||||
self.bMarks.append(length)
|
||||
self.eMarks.append(length)
|
||||
self.tShift.append(0)
|
||||
self.sCount.append(0)
|
||||
self.bsCount.append(0)
|
||||
|
||||
self.lineMax = len(self.bMarks) - 1 # don't count last fake line
|
||||
|
||||
# pre-check if code blocks are enabled, to speed up is_code_block method
|
||||
self._code_enabled = "code" in self.md["block"].ruler.get_active_rules()
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"{self.__class__.__name__}"
|
||||
f"(line={self.line},level={self.level},tokens={len(self.tokens)})"
|
||||
)
|
||||
|
||||
def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token:
|
||||
"""Push new token to "stream"."""
|
||||
token = Token(ttype, tag, nesting)
|
||||
token.block = True
|
||||
if nesting < 0:
|
||||
self.level -= 1 # closing tag
|
||||
token.level = self.level
|
||||
if nesting > 0:
|
||||
self.level += 1 # opening tag
|
||||
self.tokens.append(token)
|
||||
return token
|
||||
|
||||
def isEmpty(self, line: int) -> bool:
|
||||
"""."""
|
||||
return (self.bMarks[line] + self.tShift[line]) >= self.eMarks[line]
|
||||
|
||||
def skipEmptyLines(self, from_pos: int) -> int:
|
||||
"""."""
|
||||
while from_pos < self.lineMax:
|
||||
try:
|
||||
if (self.bMarks[from_pos] + self.tShift[from_pos]) < self.eMarks[
|
||||
from_pos
|
||||
]:
|
||||
break
|
||||
except IndexError:
|
||||
pass
|
||||
from_pos += 1
|
||||
return from_pos
|
||||
|
||||
def skipSpaces(self, pos: int) -> int:
|
||||
"""Skip spaces from given position."""
|
||||
while True:
|
||||
try:
|
||||
current = self.src[pos]
|
||||
except IndexError:
|
||||
break
|
||||
if not isStrSpace(current):
|
||||
break
|
||||
pos += 1
|
||||
return pos
|
||||
|
||||
def skipSpacesBack(self, pos: int, minimum: int) -> int:
|
||||
"""Skip spaces from given position in reverse."""
|
||||
if pos <= minimum:
|
||||
return pos
|
||||
while pos > minimum:
|
||||
pos -= 1
|
||||
if not isStrSpace(self.src[pos]):
|
||||
return pos + 1
|
||||
return pos
|
||||
|
||||
def skipChars(self, pos: int, code: int) -> int:
|
||||
"""Skip character code from given position."""
|
||||
while True:
|
||||
try:
|
||||
current = self.srcCharCode[pos]
|
||||
except IndexError:
|
||||
break
|
||||
if current != code:
|
||||
break
|
||||
pos += 1
|
||||
return pos
|
||||
|
||||
def skipCharsStr(self, pos: int, ch: str) -> int:
|
||||
"""Skip character string from given position."""
|
||||
while True:
|
||||
try:
|
||||
current = self.src[pos]
|
||||
except IndexError:
|
||||
break
|
||||
if current != ch:
|
||||
break
|
||||
pos += 1
|
||||
return pos
|
||||
|
||||
def skipCharsBack(self, pos: int, code: int, minimum: int) -> int:
|
||||
"""Skip character code reverse from given position - 1."""
|
||||
if pos <= minimum:
|
||||
return pos
|
||||
while pos > minimum:
|
||||
pos -= 1
|
||||
if code != self.srcCharCode[pos]:
|
||||
return pos + 1
|
||||
return pos
|
||||
|
||||
def skipCharsStrBack(self, pos: int, ch: str, minimum: int) -> int:
|
||||
"""Skip character string reverse from given position - 1."""
|
||||
if pos <= minimum:
|
||||
return pos
|
||||
while pos > minimum:
|
||||
pos -= 1
|
||||
if ch != self.src[pos]:
|
||||
return pos + 1
|
||||
return pos
|
||||
|
||||
def getLines(self, begin: int, end: int, indent: int, keepLastLF: bool) -> str:
|
||||
"""Cut lines range from source."""
|
||||
line = begin
|
||||
if begin >= end:
|
||||
return ""
|
||||
|
||||
queue = [""] * (end - begin)
|
||||
|
||||
i = 1
|
||||
while line < end:
|
||||
lineIndent = 0
|
||||
lineStart = first = self.bMarks[line]
|
||||
last = (
|
||||
self.eMarks[line] + 1
|
||||
if line + 1 < end or keepLastLF
|
||||
else self.eMarks[line]
|
||||
)
|
||||
|
||||
while (first < last) and (lineIndent < indent):
|
||||
ch = self.src[first]
|
||||
if isStrSpace(ch):
|
||||
if ch == "\t":
|
||||
lineIndent += 4 - (lineIndent + self.bsCount[line]) % 4
|
||||
else:
|
||||
lineIndent += 1
|
||||
elif first - lineStart < self.tShift[line]:
|
||||
lineIndent += 1
|
||||
else:
|
||||
break
|
||||
first += 1
|
||||
|
||||
if lineIndent > indent:
|
||||
# partially expanding tabs in code blocks, e.g '\t\tfoobar'
|
||||
# with indent=2 becomes ' \tfoobar'
|
||||
queue[i - 1] = (" " * (lineIndent - indent)) + self.src[first:last]
|
||||
else:
|
||||
queue[i - 1] = self.src[first:last]
|
||||
|
||||
line += 1
|
||||
i += 1
|
||||
|
||||
return "".join(queue)
|
||||
|
||||
def is_code_block(self, line: int) -> bool:
|
||||
"""Check if line is a code block,
|
||||
i.e. the code block rule is enabled and text is indented by more than 3 spaces.
|
||||
"""
|
||||
return self._code_enabled and (self.sCount[line] - self.blkIndent) >= 4
|
||||
+236
@@ -0,0 +1,236 @@
|
||||
# GFM table, https://github.github.com/gfm/#tables-extension-
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
from ..common.utils import charStrAt, isStrSpace
|
||||
from .state_block import StateBlock
|
||||
|
||||
headerLineRe = re.compile(r"^:?-+:?$")
|
||||
enclosingPipesRe = re.compile(r"^\||\|$")
|
||||
|
||||
|
||||
def getLine(state: StateBlock, line: int) -> str:
|
||||
pos = state.bMarks[line] + state.tShift[line]
|
||||
maximum = state.eMarks[line]
|
||||
|
||||
# return state.src.substr(pos, max - pos)
|
||||
return state.src[pos:maximum]
|
||||
|
||||
|
||||
def escapedSplit(string: str) -> list[str]:
|
||||
result: list[str] = []
|
||||
pos = 0
|
||||
max = len(string)
|
||||
isEscaped = False
|
||||
lastPos = 0
|
||||
current = ""
|
||||
ch = charStrAt(string, pos)
|
||||
|
||||
while pos < max:
|
||||
if ch == "|":
|
||||
if not isEscaped:
|
||||
# pipe separating cells, '|'
|
||||
result.append(current + string[lastPos:pos])
|
||||
current = ""
|
||||
lastPos = pos + 1
|
||||
else:
|
||||
# escaped pipe, '\|'
|
||||
current += string[lastPos : pos - 1]
|
||||
lastPos = pos
|
||||
|
||||
isEscaped = ch == "\\"
|
||||
pos += 1
|
||||
|
||||
ch = charStrAt(string, pos)
|
||||
|
||||
result.append(current + string[lastPos:])
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def table(state: StateBlock, startLine: int, endLine: int, silent: bool) -> bool:
|
||||
tbodyLines = None
|
||||
|
||||
# should have at least two lines
|
||||
if startLine + 2 > endLine:
|
||||
return False
|
||||
|
||||
nextLine = startLine + 1
|
||||
|
||||
if state.sCount[nextLine] < state.blkIndent:
|
||||
return False
|
||||
|
||||
if state.is_code_block(nextLine):
|
||||
return False
|
||||
|
||||
# first character of the second line should be '|', '-', ':',
|
||||
# and no other characters are allowed but spaces;
|
||||
# basically, this is the equivalent of /^[-:|][-:|\s]*$/ regexp
|
||||
|
||||
pos = state.bMarks[nextLine] + state.tShift[nextLine]
|
||||
if pos >= state.eMarks[nextLine]:
|
||||
return False
|
||||
first_ch = state.src[pos]
|
||||
pos += 1
|
||||
if first_ch not in ("|", "-", ":"):
|
||||
return False
|
||||
|
||||
if pos >= state.eMarks[nextLine]:
|
||||
return False
|
||||
second_ch = state.src[pos]
|
||||
pos += 1
|
||||
if second_ch not in ("|", "-", ":") and not isStrSpace(second_ch):
|
||||
return False
|
||||
|
||||
# if first character is '-', then second character must not be a space
|
||||
# (due to parsing ambiguity with list)
|
||||
if first_ch == "-" and isStrSpace(second_ch):
|
||||
return False
|
||||
|
||||
while pos < state.eMarks[nextLine]:
|
||||
ch = state.src[pos]
|
||||
|
||||
if ch not in ("|", "-", ":") and not isStrSpace(ch):
|
||||
return False
|
||||
|
||||
pos += 1
|
||||
|
||||
lineText = getLine(state, startLine + 1)
|
||||
|
||||
columns = lineText.split("|")
|
||||
aligns = []
|
||||
for i in range(len(columns)):
|
||||
t = columns[i].strip()
|
||||
if not t:
|
||||
# allow empty columns before and after table, but not in between columns;
|
||||
# e.g. allow ` |---| `, disallow ` ---||--- `
|
||||
if i == 0 or i == len(columns) - 1:
|
||||
continue
|
||||
else:
|
||||
return False
|
||||
|
||||
if not headerLineRe.search(t):
|
||||
return False
|
||||
if charStrAt(t, len(t) - 1) == ":":
|
||||
aligns.append("center" if charStrAt(t, 0) == ":" else "right")
|
||||
elif charStrAt(t, 0) == ":":
|
||||
aligns.append("left")
|
||||
else:
|
||||
aligns.append("")
|
||||
|
||||
lineText = getLine(state, startLine).strip()
|
||||
if "|" not in lineText:
|
||||
return False
|
||||
if state.is_code_block(startLine):
|
||||
return False
|
||||
columns = escapedSplit(lineText)
|
||||
if columns and columns[0] == "":
|
||||
columns.pop(0)
|
||||
if columns and columns[-1] == "":
|
||||
columns.pop()
|
||||
|
||||
# header row will define an amount of columns in the entire table,
|
||||
# and align row should be exactly the same (the rest of the rows can differ)
|
||||
columnCount = len(columns)
|
||||
if columnCount == 0 or columnCount != len(aligns):
|
||||
return False
|
||||
|
||||
if silent:
|
||||
return True
|
||||
|
||||
oldParentType = state.parentType
|
||||
state.parentType = "table"
|
||||
|
||||
# use 'blockquote' lists for termination because it's
|
||||
# the most similar to tables
|
||||
terminatorRules = state.md.block.ruler.getRules("blockquote")
|
||||
|
||||
token = state.push("table_open", "table", 1)
|
||||
token.map = tableLines = [startLine, 0]
|
||||
|
||||
token = state.push("thead_open", "thead", 1)
|
||||
token.map = [startLine, startLine + 1]
|
||||
|
||||
token = state.push("tr_open", "tr", 1)
|
||||
token.map = [startLine, startLine + 1]
|
||||
|
||||
for i in range(len(columns)):
|
||||
token = state.push("th_open", "th", 1)
|
||||
if aligns[i]:
|
||||
token.attrs = {"style": "text-align:" + aligns[i]}
|
||||
|
||||
token = state.push("inline", "", 0)
|
||||
# note in markdown-it this map was removed in v12.0.0 however, we keep it,
|
||||
# since it is helpful to propagate to children tokens
|
||||
token.map = [startLine, startLine + 1]
|
||||
token.content = columns[i].strip()
|
||||
token.children = []
|
||||
|
||||
token = state.push("th_close", "th", -1)
|
||||
|
||||
token = state.push("tr_close", "tr", -1)
|
||||
token = state.push("thead_close", "thead", -1)
|
||||
|
||||
nextLine = startLine + 2
|
||||
while nextLine < endLine:
|
||||
if state.sCount[nextLine] < state.blkIndent:
|
||||
break
|
||||
|
||||
terminate = False
|
||||
for i in range(len(terminatorRules)):
|
||||
if terminatorRules[i](state, nextLine, endLine, True):
|
||||
terminate = True
|
||||
break
|
||||
|
||||
if terminate:
|
||||
break
|
||||
lineText = getLine(state, nextLine).strip()
|
||||
if not lineText:
|
||||
break
|
||||
if state.is_code_block(nextLine):
|
||||
break
|
||||
columns = escapedSplit(lineText)
|
||||
if columns and columns[0] == "":
|
||||
columns.pop(0)
|
||||
if columns and columns[-1] == "":
|
||||
columns.pop()
|
||||
|
||||
if nextLine == startLine + 2:
|
||||
token = state.push("tbody_open", "tbody", 1)
|
||||
token.map = tbodyLines = [startLine + 2, 0]
|
||||
|
||||
token = state.push("tr_open", "tr", 1)
|
||||
token.map = [nextLine, nextLine + 1]
|
||||
|
||||
for i in range(columnCount):
|
||||
token = state.push("td_open", "td", 1)
|
||||
if aligns[i]:
|
||||
token.attrs = {"style": "text-align:" + aligns[i]}
|
||||
|
||||
token = state.push("inline", "", 0)
|
||||
# note in markdown-it this map was removed in v12.0.0 however, we keep it,
|
||||
# since it is helpful to propagate to children tokens
|
||||
token.map = [nextLine, nextLine + 1]
|
||||
try:
|
||||
token.content = columns[i].strip() if columns[i] else ""
|
||||
except IndexError:
|
||||
token.content = ""
|
||||
token.children = []
|
||||
|
||||
token = state.push("td_close", "td", -1)
|
||||
|
||||
token = state.push("tr_close", "tr", -1)
|
||||
|
||||
nextLine += 1
|
||||
|
||||
if tbodyLines:
|
||||
token = state.push("tbody_close", "tbody", -1)
|
||||
tbodyLines[1] = nextLine
|
||||
|
||||
token = state.push("table_close", "table", -1)
|
||||
|
||||
tableLines[1] = nextLine
|
||||
state.parentType = oldParentType
|
||||
state.line = nextLine
|
||||
return True
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
__all__ = (
|
||||
"StateCore",
|
||||
"normalize",
|
||||
"block",
|
||||
"inline",
|
||||
"replace",
|
||||
"smartquotes",
|
||||
"linkify",
|
||||
"text_join",
|
||||
)
|
||||
|
||||
from .block import block
|
||||
from .inline import inline
|
||||
from .linkify import linkify
|
||||
from .normalize import normalize
|
||||
from .replacements import replace
|
||||
from .smartquotes import smartquotes
|
||||
from .state_core import StateCore
|
||||
from .text_join import text_join
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
from ..token import Token
|
||||
from .state_core import StateCore
|
||||
|
||||
|
||||
def block(state: StateCore) -> None:
|
||||
if state.inlineMode:
|
||||
token = Token("inline", "", 0)
|
||||
token.content = state.src
|
||||
token.map = [0, 1]
|
||||
token.children = []
|
||||
state.tokens.append(token)
|
||||
else:
|
||||
state.md.block.parse(state.src, state.md, state.env, state.tokens)
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
from .state_core import StateCore
|
||||
|
||||
|
||||
def inline(state: StateCore) -> None:
|
||||
"""Parse inlines"""
|
||||
for token in state.tokens:
|
||||
if token.type == "inline":
|
||||
if token.children is None:
|
||||
token.children = []
|
||||
state.md.inline.parse(token.content, state.md, state.env, token.children)
|
||||
+149
@@ -0,0 +1,149 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Protocol
|
||||
|
||||
from ..common.utils import arrayReplaceAt, isLinkClose, isLinkOpen
|
||||
from ..token import Token
|
||||
from .state_core import StateCore
|
||||
|
||||
HTTP_RE = re.compile(r"^http://")
|
||||
MAILTO_RE = re.compile(r"^mailto:")
|
||||
TEST_MAILTO_RE = re.compile(r"^mailto:", flags=re.IGNORECASE)
|
||||
|
||||
|
||||
def linkify(state: StateCore) -> None:
|
||||
"""Rule for identifying plain-text links."""
|
||||
if not state.md.options.linkify:
|
||||
return
|
||||
|
||||
if not state.md.linkify:
|
||||
raise ModuleNotFoundError("Linkify enabled but not installed.")
|
||||
|
||||
for inline_token in state.tokens:
|
||||
if inline_token.type != "inline" or not state.md.linkify.pretest(
|
||||
inline_token.content
|
||||
):
|
||||
continue
|
||||
|
||||
tokens = inline_token.children
|
||||
|
||||
htmlLinkLevel = 0
|
||||
|
||||
# We scan from the end, to keep position when new tags added.
|
||||
# Use reversed logic in links start/end match
|
||||
assert tokens is not None
|
||||
i = len(tokens)
|
||||
while i >= 1:
|
||||
i -= 1
|
||||
assert isinstance(tokens, list)
|
||||
currentToken = tokens[i]
|
||||
|
||||
# Skip content of markdown links
|
||||
if currentToken.type == "link_close":
|
||||
i -= 1
|
||||
while (
|
||||
tokens[i].level != currentToken.level
|
||||
and tokens[i].type != "link_open"
|
||||
):
|
||||
i -= 1
|
||||
continue
|
||||
|
||||
# Skip content of html tag links
|
||||
if currentToken.type == "html_inline":
|
||||
if isLinkOpen(currentToken.content) and htmlLinkLevel > 0:
|
||||
htmlLinkLevel -= 1
|
||||
if isLinkClose(currentToken.content):
|
||||
htmlLinkLevel += 1
|
||||
if htmlLinkLevel > 0:
|
||||
continue
|
||||
|
||||
if currentToken.type == "text" and state.md.linkify.test(
|
||||
currentToken.content
|
||||
):
|
||||
text = currentToken.content
|
||||
links: list[_LinkType] = state.md.linkify.match(text) or []
|
||||
|
||||
# Now split string to nodes
|
||||
nodes = []
|
||||
level = currentToken.level
|
||||
lastPos = 0
|
||||
|
||||
# forbid escape sequence at the start of the string,
|
||||
# this avoids http\://example.com/ from being linkified as
|
||||
# http:<a href="//example.com/">//example.com/</a>
|
||||
if (
|
||||
links
|
||||
and links[0].index == 0
|
||||
and i > 0
|
||||
and tokens[i - 1].type == "text_special"
|
||||
):
|
||||
links = links[1:]
|
||||
|
||||
for link in links:
|
||||
url = link.url
|
||||
fullUrl = state.md.normalizeLink(url)
|
||||
if not state.md.validateLink(fullUrl):
|
||||
continue
|
||||
|
||||
urlText = link.text
|
||||
|
||||
# Linkifier might send raw hostnames like "example.com", where url
|
||||
# starts with domain name. So we prepend http:// in those cases,
|
||||
# and remove it afterwards.
|
||||
if not link.schema:
|
||||
urlText = HTTP_RE.sub(
|
||||
"", state.md.normalizeLinkText("http://" + urlText)
|
||||
)
|
||||
elif link.schema == "mailto:" and TEST_MAILTO_RE.search(urlText):
|
||||
urlText = MAILTO_RE.sub(
|
||||
"", state.md.normalizeLinkText("mailto:" + urlText)
|
||||
)
|
||||
else:
|
||||
urlText = state.md.normalizeLinkText(urlText)
|
||||
|
||||
pos = link.index
|
||||
|
||||
if pos > lastPos:
|
||||
token = Token("text", "", 0)
|
||||
token.content = text[lastPos:pos]
|
||||
token.level = level
|
||||
nodes.append(token)
|
||||
|
||||
token = Token("link_open", "a", 1)
|
||||
token.attrs = {"href": fullUrl}
|
||||
token.level = level
|
||||
level += 1
|
||||
token.markup = "linkify"
|
||||
token.info = "auto"
|
||||
nodes.append(token)
|
||||
|
||||
token = Token("text", "", 0)
|
||||
token.content = urlText
|
||||
token.level = level
|
||||
nodes.append(token)
|
||||
|
||||
token = Token("link_close", "a", -1)
|
||||
level -= 1
|
||||
token.level = level
|
||||
token.markup = "linkify"
|
||||
token.info = "auto"
|
||||
nodes.append(token)
|
||||
|
||||
lastPos = link.last_index
|
||||
|
||||
if lastPos < len(text):
|
||||
token = Token("text", "", 0)
|
||||
token.content = text[lastPos:]
|
||||
token.level = level
|
||||
nodes.append(token)
|
||||
|
||||
inline_token.children = tokens = arrayReplaceAt(tokens, i, nodes)
|
||||
|
||||
|
||||
class _LinkType(Protocol):
|
||||
url: str
|
||||
text: str
|
||||
index: int
|
||||
last_index: int
|
||||
schema: str | None
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
"""Normalize input string."""
|
||||
import re
|
||||
|
||||
from .state_core import StateCore
|
||||
|
||||
# https://spec.commonmark.org/0.29/#line-ending
|
||||
NEWLINES_RE = re.compile(r"\r\n?|\n")
|
||||
NULL_RE = re.compile(r"\0")
|
||||
|
||||
|
||||
def normalize(state: StateCore) -> None:
|
||||
# Normalize newlines
|
||||
string = NEWLINES_RE.sub("\n", state.src)
|
||||
|
||||
# Replace NULL characters
|
||||
string = NULL_RE.sub("\uFFFD", string)
|
||||
|
||||
state.src = string
|
||||
+126
@@ -0,0 +1,126 @@
|
||||
"""Simple typographic replacements
|
||||
|
||||
* ``(c)``, ``(C)`` → ©
|
||||
* ``(tm)``, ``(TM)`` → ™
|
||||
* ``(r)``, ``(R)`` → ®
|
||||
* ``+-`` → ±
|
||||
* ``...`` → …
|
||||
* ``?....`` → ?..
|
||||
* ``!....`` → !..
|
||||
* ``????????`` → ???
|
||||
* ``!!!!!`` → !!!
|
||||
* ``,,,`` → ,
|
||||
* ``--`` → &ndash
|
||||
* ``---`` → &mdash
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
|
||||
from ..token import Token
|
||||
from .state_core import StateCore
|
||||
|
||||
LOGGER = logging.getLogger(__name__)
|
||||
|
||||
# TODO:
|
||||
# - fractionals 1/2, 1/4, 3/4 -> ½, ¼, ¾
|
||||
# - multiplication 2 x 4 -> 2 × 4
|
||||
|
||||
RARE_RE = re.compile(r"\+-|\.\.|\?\?\?\?|!!!!|,,|--")
|
||||
|
||||
# Workaround for phantomjs - need regex without /g flag,
|
||||
# or root check will fail every second time
|
||||
# SCOPED_ABBR_TEST_RE = r"\((c|tm|r)\)"
|
||||
|
||||
SCOPED_ABBR_RE = re.compile(r"\((c|tm|r)\)", flags=re.IGNORECASE)
|
||||
|
||||
PLUS_MINUS_RE = re.compile(r"\+-")
|
||||
|
||||
ELLIPSIS_RE = re.compile(r"\.{2,}")
|
||||
|
||||
ELLIPSIS_QUESTION_EXCLAMATION_RE = re.compile(r"([?!])…")
|
||||
|
||||
QUESTION_EXCLAMATION_RE = re.compile(r"([?!]){4,}")
|
||||
|
||||
COMMA_RE = re.compile(r",{2,}")
|
||||
|
||||
EM_DASH_RE = re.compile(r"(^|[^-])---(?=[^-]|$)", flags=re.MULTILINE)
|
||||
|
||||
EN_DASH_RE = re.compile(r"(^|\s)--(?=\s|$)", flags=re.MULTILINE)
|
||||
|
||||
EN_DASH_INDENT_RE = re.compile(r"(^|[^-\s])--(?=[^-\s]|$)", flags=re.MULTILINE)
|
||||
|
||||
|
||||
SCOPED_ABBR = {"c": "©", "r": "®", "tm": "™"}
|
||||
|
||||
|
||||
def replaceFn(match: re.Match[str]) -> str:
|
||||
return SCOPED_ABBR[match.group(1).lower()]
|
||||
|
||||
|
||||
def replace_scoped(inlineTokens: list[Token]) -> None:
|
||||
inside_autolink = 0
|
||||
|
||||
for token in inlineTokens:
|
||||
if token.type == "text" and not inside_autolink:
|
||||
token.content = SCOPED_ABBR_RE.sub(replaceFn, token.content)
|
||||
|
||||
if token.type == "link_open" and token.info == "auto":
|
||||
inside_autolink -= 1
|
||||
|
||||
if token.type == "link_close" and token.info == "auto":
|
||||
inside_autolink += 1
|
||||
|
||||
|
||||
def replace_rare(inlineTokens: list[Token]) -> None:
|
||||
inside_autolink = 0
|
||||
|
||||
for token in inlineTokens:
|
||||
if (
|
||||
token.type == "text"
|
||||
and (not inside_autolink)
|
||||
and RARE_RE.search(token.content)
|
||||
):
|
||||
# +- -> ±
|
||||
token.content = PLUS_MINUS_RE.sub("±", token.content)
|
||||
|
||||
# .., ..., ....... -> …
|
||||
token.content = ELLIPSIS_RE.sub("…", token.content)
|
||||
|
||||
# but ?..... & !..... -> ?.. & !..
|
||||
token.content = ELLIPSIS_QUESTION_EXCLAMATION_RE.sub("\\1..", token.content)
|
||||
token.content = QUESTION_EXCLAMATION_RE.sub("\\1\\1\\1", token.content)
|
||||
|
||||
# ,, ,,, ,,,, -> ,
|
||||
token.content = COMMA_RE.sub(",", token.content)
|
||||
|
||||
# em-dash
|
||||
token.content = EM_DASH_RE.sub("\\1\u2014", token.content)
|
||||
|
||||
# en-dash
|
||||
token.content = EN_DASH_RE.sub("\\1\u2013", token.content)
|
||||
token.content = EN_DASH_INDENT_RE.sub("\\1\u2013", token.content)
|
||||
|
||||
if token.type == "link_open" and token.info == "auto":
|
||||
inside_autolink -= 1
|
||||
|
||||
if token.type == "link_close" and token.info == "auto":
|
||||
inside_autolink += 1
|
||||
|
||||
|
||||
def replace(state: StateCore) -> None:
|
||||
if not state.md.options.typographer:
|
||||
return
|
||||
|
||||
for token in state.tokens:
|
||||
if token.type != "inline":
|
||||
continue
|
||||
if token.children is None:
|
||||
continue
|
||||
|
||||
if SCOPED_ABBR_RE.search(token.content):
|
||||
replace_scoped(token.children)
|
||||
|
||||
if RARE_RE.search(token.content):
|
||||
replace_rare(token.children)
|
||||
+202
@@ -0,0 +1,202 @@
|
||||
"""Convert straight quotation marks to typographic ones
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from ..common.utils import charCodeAt, isMdAsciiPunct, isPunctChar, isWhiteSpace
|
||||
from ..token import Token
|
||||
from .state_core import StateCore
|
||||
|
||||
QUOTE_TEST_RE = re.compile(r"['\"]")
|
||||
QUOTE_RE = re.compile(r"['\"]")
|
||||
APOSTROPHE = "\u2019" # ’
|
||||
|
||||
|
||||
def replaceAt(string: str, index: int, ch: str) -> str:
|
||||
# When the index is negative, the behavior is different from the js version.
|
||||
# But basically, the index will not be negative.
|
||||
assert index >= 0
|
||||
return string[:index] + ch + string[index + 1 :]
|
||||
|
||||
|
||||
def process_inlines(tokens: list[Token], state: StateCore) -> None:
|
||||
stack: list[dict[str, Any]] = []
|
||||
|
||||
for i, token in enumerate(tokens):
|
||||
thisLevel = token.level
|
||||
|
||||
j = 0
|
||||
for j in range(len(stack))[::-1]:
|
||||
if stack[j]["level"] <= thisLevel:
|
||||
break
|
||||
else:
|
||||
# When the loop is terminated without a "break".
|
||||
# Subtract 1 to get the same index as the js version.
|
||||
j -= 1
|
||||
|
||||
stack = stack[: j + 1]
|
||||
|
||||
if token.type != "text":
|
||||
continue
|
||||
|
||||
text = token.content
|
||||
pos = 0
|
||||
maximum = len(text)
|
||||
|
||||
while pos < maximum:
|
||||
goto_outer = False
|
||||
lastIndex = pos
|
||||
t = QUOTE_RE.search(text[lastIndex:])
|
||||
if not t:
|
||||
break
|
||||
|
||||
canOpen = canClose = True
|
||||
pos = t.start(0) + lastIndex + 1
|
||||
isSingle = t.group(0) == "'"
|
||||
|
||||
# Find previous character,
|
||||
# default to space if it's the beginning of the line
|
||||
lastChar: None | int = 0x20
|
||||
|
||||
if t.start(0) + lastIndex - 1 >= 0:
|
||||
lastChar = charCodeAt(text, t.start(0) + lastIndex - 1)
|
||||
else:
|
||||
for j in range(i)[::-1]:
|
||||
if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak":
|
||||
break
|
||||
# should skip all tokens except 'text', 'html_inline' or 'code_inline'
|
||||
if not tokens[j].content:
|
||||
continue
|
||||
|
||||
lastChar = charCodeAt(tokens[j].content, len(tokens[j].content) - 1)
|
||||
break
|
||||
|
||||
# Find next character,
|
||||
# default to space if it's the end of the line
|
||||
nextChar: None | int = 0x20
|
||||
|
||||
if pos < maximum:
|
||||
nextChar = charCodeAt(text, pos)
|
||||
else:
|
||||
for j in range(i + 1, len(tokens)):
|
||||
# nextChar defaults to 0x20
|
||||
if tokens[j].type == "softbreak" or tokens[j].type == "hardbreak":
|
||||
break
|
||||
# should skip all tokens except 'text', 'html_inline' or 'code_inline'
|
||||
if not tokens[j].content:
|
||||
continue
|
||||
|
||||
nextChar = charCodeAt(tokens[j].content, 0)
|
||||
break
|
||||
|
||||
isLastPunctChar = lastChar is not None and (
|
||||
isMdAsciiPunct(lastChar) or isPunctChar(chr(lastChar))
|
||||
)
|
||||
isNextPunctChar = nextChar is not None and (
|
||||
isMdAsciiPunct(nextChar) or isPunctChar(chr(nextChar))
|
||||
)
|
||||
|
||||
isLastWhiteSpace = lastChar is not None and isWhiteSpace(lastChar)
|
||||
isNextWhiteSpace = nextChar is not None and isWhiteSpace(nextChar)
|
||||
|
||||
if isNextWhiteSpace: # noqa: SIM114
|
||||
canOpen = False
|
||||
elif isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar):
|
||||
canOpen = False
|
||||
|
||||
if isLastWhiteSpace: # noqa: SIM114
|
||||
canClose = False
|
||||
elif isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar):
|
||||
canClose = False
|
||||
|
||||
if nextChar == 0x22 and t.group(0) == '"': # 0x22: " # noqa: SIM102
|
||||
if (
|
||||
lastChar is not None and lastChar >= 0x30 and lastChar <= 0x39
|
||||
): # 0x30: 0, 0x39: 9
|
||||
# special case: 1"" - count first quote as an inch
|
||||
canClose = canOpen = False
|
||||
|
||||
if canOpen and canClose:
|
||||
# Replace quotes in the middle of punctuation sequence, but not
|
||||
# in the middle of the words, i.e.:
|
||||
#
|
||||
# 1. foo " bar " baz - not replaced
|
||||
# 2. foo-"-bar-"-baz - replaced
|
||||
# 3. foo"bar"baz - not replaced
|
||||
canOpen = isLastPunctChar
|
||||
canClose = isNextPunctChar
|
||||
|
||||
if not canOpen and not canClose:
|
||||
# middle of word
|
||||
if isSingle:
|
||||
token.content = replaceAt(
|
||||
token.content, t.start(0) + lastIndex, APOSTROPHE
|
||||
)
|
||||
continue
|
||||
|
||||
if canClose:
|
||||
# this could be a closing quote, rewind the stack to get a match
|
||||
for j in range(len(stack))[::-1]:
|
||||
item = stack[j]
|
||||
if stack[j]["level"] < thisLevel:
|
||||
break
|
||||
if item["single"] == isSingle and stack[j]["level"] == thisLevel:
|
||||
item = stack[j]
|
||||
|
||||
if isSingle:
|
||||
openQuote = state.md.options.quotes[2]
|
||||
closeQuote = state.md.options.quotes[3]
|
||||
else:
|
||||
openQuote = state.md.options.quotes[0]
|
||||
closeQuote = state.md.options.quotes[1]
|
||||
|
||||
# replace token.content *before* tokens[item.token].content,
|
||||
# because, if they are pointing at the same token, replaceAt
|
||||
# could mess up indices when quote length != 1
|
||||
token.content = replaceAt(
|
||||
token.content, t.start(0) + lastIndex, closeQuote
|
||||
)
|
||||
tokens[item["token"]].content = replaceAt(
|
||||
tokens[item["token"]].content, item["pos"], openQuote
|
||||
)
|
||||
|
||||
pos += len(closeQuote) - 1
|
||||
if item["token"] == i:
|
||||
pos += len(openQuote) - 1
|
||||
|
||||
text = token.content
|
||||
maximum = len(text)
|
||||
|
||||
stack = stack[:j]
|
||||
goto_outer = True
|
||||
break
|
||||
if goto_outer:
|
||||
goto_outer = False
|
||||
continue
|
||||
|
||||
if canOpen:
|
||||
stack.append(
|
||||
{
|
||||
"token": i,
|
||||
"pos": t.start(0) + lastIndex,
|
||||
"single": isSingle,
|
||||
"level": thisLevel,
|
||||
}
|
||||
)
|
||||
elif canClose and isSingle:
|
||||
token.content = replaceAt(
|
||||
token.content, t.start(0) + lastIndex, APOSTROPHE
|
||||
)
|
||||
|
||||
|
||||
def smartquotes(state: StateCore) -> None:
|
||||
if not state.md.options.typographer:
|
||||
return
|
||||
|
||||
for token in state.tokens:
|
||||
if token.type != "inline" or not QUOTE_RE.search(token.content):
|
||||
continue
|
||||
if token.children is not None:
|
||||
process_inlines(token.children, state)
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ..ruler import StateBase
|
||||
from ..token import Token
|
||||
from ..utils import EnvType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from markdown_it import MarkdownIt
|
||||
|
||||
|
||||
class StateCore(StateBase):
|
||||
def __init__(
|
||||
self,
|
||||
src: str,
|
||||
md: MarkdownIt,
|
||||
env: EnvType,
|
||||
tokens: list[Token] | None = None,
|
||||
) -> None:
|
||||
self.src = src
|
||||
self.md = md # link to parser instance
|
||||
self.env = env
|
||||
self.tokens: list[Token] = tokens or []
|
||||
self.inlineMode = False
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
"""Join raw text tokens with the rest of the text
|
||||
|
||||
This is set as a separate rule to provide an opportunity for plugins
|
||||
to run text replacements after text join, but before escape join.
|
||||
|
||||
For example, `\\:)` shouldn't be replaced with an emoji.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from ..token import Token
|
||||
from .state_core import StateCore
|
||||
|
||||
|
||||
def text_join(state: StateCore) -> None:
|
||||
"""Join raw text for escape sequences (`text_special`) tokens with the rest of the text"""
|
||||
|
||||
for inline_token in state.tokens[:]:
|
||||
if inline_token.type != "inline":
|
||||
continue
|
||||
|
||||
# convert text_special to text and join all adjacent text nodes
|
||||
new_tokens: list[Token] = []
|
||||
for child_token in inline_token.children or []:
|
||||
if child_token.type == "text_special":
|
||||
child_token.type = "text"
|
||||
if (
|
||||
child_token.type == "text"
|
||||
and new_tokens
|
||||
and new_tokens[-1].type == "text"
|
||||
):
|
||||
new_tokens[-1].content += child_token.content
|
||||
else:
|
||||
new_tokens.append(child_token)
|
||||
inline_token.children = new_tokens
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
__all__ = (
|
||||
"StateInline",
|
||||
"text",
|
||||
"fragments_join",
|
||||
"link_pairs",
|
||||
"linkify",
|
||||
"escape",
|
||||
"newline",
|
||||
"backtick",
|
||||
"emphasis",
|
||||
"image",
|
||||
"link",
|
||||
"autolink",
|
||||
"entity",
|
||||
"html_inline",
|
||||
"strikethrough",
|
||||
)
|
||||
from . import emphasis, strikethrough
|
||||
from .autolink import autolink
|
||||
from .backticks import backtick
|
||||
from .balance_pairs import link_pairs
|
||||
from .entity import entity
|
||||
from .escape import escape
|
||||
from .fragments_join import fragments_join
|
||||
from .html_inline import html_inline
|
||||
from .image import image
|
||||
from .link import link
|
||||
from .linkify import linkify
|
||||
from .newline import newline
|
||||
from .state_inline import StateInline
|
||||
from .text import text
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
# Process autolinks '<protocol:...>'
|
||||
import re
|
||||
|
||||
from .state_inline import StateInline
|
||||
|
||||
EMAIL_RE = re.compile(
|
||||
r"^([a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*)$" # noqa: E501
|
||||
)
|
||||
AUTOLINK_RE = re.compile(r"^([a-zA-Z][a-zA-Z0-9+.\-]{1,31}):([^<>\x00-\x20]*)$")
|
||||
|
||||
|
||||
def autolink(state: StateInline, silent: bool) -> bool:
|
||||
pos = state.pos
|
||||
|
||||
if state.src[pos] != "<":
|
||||
return False
|
||||
|
||||
start = state.pos
|
||||
maximum = state.posMax
|
||||
|
||||
while True:
|
||||
pos += 1
|
||||
if pos >= maximum:
|
||||
return False
|
||||
|
||||
ch = state.src[pos]
|
||||
|
||||
if ch == "<":
|
||||
return False
|
||||
if ch == ">":
|
||||
break
|
||||
|
||||
url = state.src[start + 1 : pos]
|
||||
|
||||
if AUTOLINK_RE.search(url) is not None:
|
||||
fullUrl = state.md.normalizeLink(url)
|
||||
if not state.md.validateLink(fullUrl):
|
||||
return False
|
||||
|
||||
if not silent:
|
||||
token = state.push("link_open", "a", 1)
|
||||
token.attrs = {"href": fullUrl}
|
||||
token.markup = "autolink"
|
||||
token.info = "auto"
|
||||
|
||||
token = state.push("text", "", 0)
|
||||
token.content = state.md.normalizeLinkText(url)
|
||||
|
||||
token = state.push("link_close", "a", -1)
|
||||
token.markup = "autolink"
|
||||
token.info = "auto"
|
||||
|
||||
state.pos += len(url) + 2
|
||||
return True
|
||||
|
||||
if EMAIL_RE.search(url) is not None:
|
||||
fullUrl = state.md.normalizeLink("mailto:" + url)
|
||||
if not state.md.validateLink(fullUrl):
|
||||
return False
|
||||
|
||||
if not silent:
|
||||
token = state.push("link_open", "a", 1)
|
||||
token.attrs = {"href": fullUrl}
|
||||
token.markup = "autolink"
|
||||
token.info = "auto"
|
||||
|
||||
token = state.push("text", "", 0)
|
||||
token.content = state.md.normalizeLinkText(url)
|
||||
|
||||
token = state.push("link_close", "a", -1)
|
||||
token.markup = "autolink"
|
||||
token.info = "auto"
|
||||
|
||||
state.pos += len(url) + 2
|
||||
return True
|
||||
|
||||
return False
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
# Parse backticks
|
||||
import re
|
||||
|
||||
from .state_inline import StateInline
|
||||
|
||||
regex = re.compile("^ (.+) $")
|
||||
|
||||
|
||||
def backtick(state: StateInline, silent: bool) -> bool:
|
||||
pos = state.pos
|
||||
|
||||
if state.src[pos] != "`":
|
||||
return False
|
||||
|
||||
start = pos
|
||||
pos += 1
|
||||
maximum = state.posMax
|
||||
|
||||
# scan marker length
|
||||
while pos < maximum and (state.src[pos] == "`"):
|
||||
pos += 1
|
||||
|
||||
marker = state.src[start:pos]
|
||||
openerLength = len(marker)
|
||||
|
||||
if state.backticksScanned and state.backticks.get(openerLength, 0) <= start:
|
||||
if not silent:
|
||||
state.pending += marker
|
||||
state.pos += openerLength
|
||||
return True
|
||||
|
||||
matchStart = matchEnd = pos
|
||||
|
||||
# Nothing found in the cache, scan until the end of the line (or until marker is found)
|
||||
while True:
|
||||
try:
|
||||
matchStart = state.src.index("`", matchEnd)
|
||||
except ValueError:
|
||||
break
|
||||
matchEnd = matchStart + 1
|
||||
|
||||
# scan marker length
|
||||
while matchEnd < maximum and (state.src[matchEnd] == "`"):
|
||||
matchEnd += 1
|
||||
|
||||
closerLength = matchEnd - matchStart
|
||||
|
||||
if closerLength == openerLength:
|
||||
# Found matching closer length.
|
||||
if not silent:
|
||||
token = state.push("code_inline", "code", 0)
|
||||
token.markup = marker
|
||||
token.content = state.src[pos:matchStart].replace("\n", " ")
|
||||
if (
|
||||
token.content.startswith(" ")
|
||||
and token.content.endswith(" ")
|
||||
and len(token.content.strip()) > 0
|
||||
):
|
||||
token.content = token.content[1:-1]
|
||||
state.pos = matchEnd
|
||||
return True
|
||||
|
||||
# Some different length found, put it in cache as upper limit of where closer can be found
|
||||
state.backticks[closerLength] = matchStart
|
||||
|
||||
# Scanned through the end, didn't find anything
|
||||
state.backticksScanned = True
|
||||
|
||||
if not silent:
|
||||
state.pending += marker
|
||||
state.pos += openerLength
|
||||
return True
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
"""Balance paired characters (*, _, etc) in inline tokens."""
|
||||
from __future__ import annotations
|
||||
|
||||
from .state_inline import Delimiter, StateInline
|
||||
|
||||
|
||||
def processDelimiters(state: StateInline, delimiters: list[Delimiter]) -> None:
|
||||
"""For each opening emphasis-like marker find a matching closing one."""
|
||||
if not delimiters:
|
||||
return
|
||||
|
||||
openersBottom = {}
|
||||
maximum = len(delimiters)
|
||||
|
||||
# headerIdx is the first delimiter of the current (where closer is) delimiter run
|
||||
headerIdx = 0
|
||||
lastTokenIdx = -2 # needs any value lower than -1
|
||||
jumps: list[int] = []
|
||||
closerIdx = 0
|
||||
while closerIdx < maximum:
|
||||
closer = delimiters[closerIdx]
|
||||
|
||||
jumps.append(0)
|
||||
|
||||
# markers belong to same delimiter run if:
|
||||
# - they have adjacent tokens
|
||||
# - AND markers are the same
|
||||
#
|
||||
if (
|
||||
delimiters[headerIdx].marker != closer.marker
|
||||
or lastTokenIdx != closer.token - 1
|
||||
):
|
||||
headerIdx = closerIdx
|
||||
lastTokenIdx = closer.token
|
||||
|
||||
# Length is only used for emphasis-specific "rule of 3",
|
||||
# if it's not defined (in strikethrough or 3rd party plugins),
|
||||
# we can default it to 0 to disable those checks.
|
||||
#
|
||||
closer.length = closer.length or 0
|
||||
|
||||
if not closer.close:
|
||||
closerIdx += 1
|
||||
continue
|
||||
|
||||
# Previously calculated lower bounds (previous fails)
|
||||
# for each marker, each delimiter length modulo 3,
|
||||
# and for whether this closer can be an opener;
|
||||
# https://github.com/commonmark/cmark/commit/34250e12ccebdc6372b8b49c44fab57c72443460
|
||||
if closer.marker not in openersBottom:
|
||||
openersBottom[closer.marker] = [-1, -1, -1, -1, -1, -1]
|
||||
|
||||
minOpenerIdx = openersBottom[closer.marker][
|
||||
(3 if closer.open else 0) + (closer.length % 3)
|
||||
]
|
||||
|
||||
openerIdx = headerIdx - jumps[headerIdx] - 1
|
||||
|
||||
newMinOpenerIdx = openerIdx
|
||||
|
||||
while openerIdx > minOpenerIdx:
|
||||
opener = delimiters[openerIdx]
|
||||
|
||||
if opener.marker != closer.marker:
|
||||
openerIdx -= jumps[openerIdx] + 1
|
||||
continue
|
||||
|
||||
if opener.open and opener.end < 0:
|
||||
isOddMatch = False
|
||||
|
||||
# from spec:
|
||||
#
|
||||
# If one of the delimiters can both open and close emphasis, then the
|
||||
# sum of the lengths of the delimiter runs containing the opening and
|
||||
# closing delimiters must not be a multiple of 3 unless both lengths
|
||||
# are multiples of 3.
|
||||
#
|
||||
if (
|
||||
(opener.close or closer.open)
|
||||
and ((opener.length + closer.length) % 3 == 0)
|
||||
and (opener.length % 3 != 0 or closer.length % 3 != 0)
|
||||
):
|
||||
isOddMatch = True
|
||||
|
||||
if not isOddMatch:
|
||||
# If previous delimiter cannot be an opener, we can safely skip
|
||||
# the entire sequence in future checks. This is required to make
|
||||
# sure algorithm has linear complexity (see *_*_*_*_*_... case).
|
||||
#
|
||||
if openerIdx > 0 and not delimiters[openerIdx - 1].open:
|
||||
lastJump = jumps[openerIdx - 1] + 1
|
||||
else:
|
||||
lastJump = 0
|
||||
|
||||
jumps[closerIdx] = closerIdx - openerIdx + lastJump
|
||||
jumps[openerIdx] = lastJump
|
||||
|
||||
closer.open = False
|
||||
opener.end = closerIdx
|
||||
opener.close = False
|
||||
newMinOpenerIdx = -1
|
||||
|
||||
# treat next token as start of run,
|
||||
# it optimizes skips in **<...>**a**<...>** pathological case
|
||||
lastTokenIdx = -2
|
||||
|
||||
break
|
||||
|
||||
openerIdx -= jumps[openerIdx] + 1
|
||||
|
||||
if newMinOpenerIdx != -1:
|
||||
# If match for this delimiter run failed, we want to set lower bound for
|
||||
# future lookups. This is required to make sure algorithm has linear
|
||||
# complexity.
|
||||
#
|
||||
# See details here:
|
||||
# https:#github.com/commonmark/cmark/issues/178#issuecomment-270417442
|
||||
#
|
||||
openersBottom[closer.marker][
|
||||
(3 if closer.open else 0) + ((closer.length or 0) % 3)
|
||||
] = newMinOpenerIdx
|
||||
|
||||
closerIdx += 1
|
||||
|
||||
|
||||
def link_pairs(state: StateInline) -> None:
|
||||
tokens_meta = state.tokens_meta
|
||||
maximum = len(state.tokens_meta)
|
||||
|
||||
processDelimiters(state, state.delimiters)
|
||||
|
||||
curr = 0
|
||||
while curr < maximum:
|
||||
curr_meta = tokens_meta[curr]
|
||||
if curr_meta and "delimiters" in curr_meta:
|
||||
processDelimiters(state, curr_meta["delimiters"])
|
||||
curr += 1
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
# Process *this* and _that_
|
||||
#
|
||||
from __future__ import annotations
|
||||
|
||||
from .state_inline import Delimiter, StateInline
|
||||
|
||||
|
||||
def tokenize(state: StateInline, silent: bool) -> bool:
|
||||
"""Insert each marker as a separate text token, and add it to delimiter list"""
|
||||
start = state.pos
|
||||
marker = state.src[start]
|
||||
|
||||
if silent:
|
||||
return False
|
||||
|
||||
if marker not in ("_", "*"):
|
||||
return False
|
||||
|
||||
scanned = state.scanDelims(state.pos, marker == "*")
|
||||
|
||||
for _ in range(scanned.length):
|
||||
token = state.push("text", "", 0)
|
||||
token.content = marker
|
||||
state.delimiters.append(
|
||||
Delimiter(
|
||||
marker=ord(marker),
|
||||
length=scanned.length,
|
||||
token=len(state.tokens) - 1,
|
||||
end=-1,
|
||||
open=scanned.can_open,
|
||||
close=scanned.can_close,
|
||||
)
|
||||
)
|
||||
|
||||
state.pos += scanned.length
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None:
|
||||
i = len(delimiters) - 1
|
||||
while i >= 0:
|
||||
startDelim = delimiters[i]
|
||||
|
||||
# /* _ */ /* * */
|
||||
if startDelim.marker != 0x5F and startDelim.marker != 0x2A:
|
||||
i -= 1
|
||||
continue
|
||||
|
||||
# Process only opening markers
|
||||
if startDelim.end == -1:
|
||||
i -= 1
|
||||
continue
|
||||
|
||||
endDelim = delimiters[startDelim.end]
|
||||
|
||||
# If the previous delimiter has the same marker and is adjacent to this one,
|
||||
# merge those into one strong delimiter.
|
||||
#
|
||||
# `<em><em>whatever</em></em>` -> `<strong>whatever</strong>`
|
||||
#
|
||||
isStrong = (
|
||||
i > 0
|
||||
and delimiters[i - 1].end == startDelim.end + 1
|
||||
# check that first two markers match and adjacent
|
||||
and delimiters[i - 1].marker == startDelim.marker
|
||||
and delimiters[i - 1].token == startDelim.token - 1
|
||||
# check that last two markers are adjacent (we can safely assume they match)
|
||||
and delimiters[startDelim.end + 1].token == endDelim.token + 1
|
||||
)
|
||||
|
||||
ch = chr(startDelim.marker)
|
||||
|
||||
token = state.tokens[startDelim.token]
|
||||
token.type = "strong_open" if isStrong else "em_open"
|
||||
token.tag = "strong" if isStrong else "em"
|
||||
token.nesting = 1
|
||||
token.markup = ch + ch if isStrong else ch
|
||||
token.content = ""
|
||||
|
||||
token = state.tokens[endDelim.token]
|
||||
token.type = "strong_close" if isStrong else "em_close"
|
||||
token.tag = "strong" if isStrong else "em"
|
||||
token.nesting = -1
|
||||
token.markup = ch + ch if isStrong else ch
|
||||
token.content = ""
|
||||
|
||||
if isStrong:
|
||||
state.tokens[delimiters[i - 1].token].content = ""
|
||||
state.tokens[delimiters[startDelim.end + 1].token].content = ""
|
||||
i -= 1
|
||||
|
||||
i -= 1
|
||||
|
||||
|
||||
def postProcess(state: StateInline) -> None:
|
||||
"""Walk through delimiter list and replace text tokens with tags."""
|
||||
_postProcess(state, state.delimiters)
|
||||
|
||||
for token in state.tokens_meta:
|
||||
if token and "delimiters" in token:
|
||||
_postProcess(state, token["delimiters"])
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
# Process html entity - {, ¯, ", ...
|
||||
import re
|
||||
|
||||
from ..common.entities import entities
|
||||
from ..common.utils import fromCodePoint, isValidEntityCode
|
||||
from .state_inline import StateInline
|
||||
|
||||
DIGITAL_RE = re.compile(r"^&#((?:x[a-f0-9]{1,6}|[0-9]{1,7}));", re.IGNORECASE)
|
||||
NAMED_RE = re.compile(r"^&([a-z][a-z0-9]{1,31});", re.IGNORECASE)
|
||||
|
||||
|
||||
def entity(state: StateInline, silent: bool) -> bool:
|
||||
pos = state.pos
|
||||
maximum = state.posMax
|
||||
|
||||
if state.src[pos] != "&":
|
||||
return False
|
||||
|
||||
if pos + 1 >= maximum:
|
||||
return False
|
||||
|
||||
if state.src[pos + 1] == "#":
|
||||
if match := DIGITAL_RE.search(state.src[pos:]):
|
||||
if not silent:
|
||||
match1 = match.group(1)
|
||||
code = (
|
||||
int(match1[1:], 16) if match1[0].lower() == "x" else int(match1, 10)
|
||||
)
|
||||
|
||||
token = state.push("text_special", "", 0)
|
||||
token.content = (
|
||||
fromCodePoint(code)
|
||||
if isValidEntityCode(code)
|
||||
else fromCodePoint(0xFFFD)
|
||||
)
|
||||
token.markup = match.group(0)
|
||||
token.info = "entity"
|
||||
|
||||
state.pos += len(match.group(0))
|
||||
return True
|
||||
|
||||
else:
|
||||
if (match := NAMED_RE.search(state.src[pos:])) and match.group(1) in entities:
|
||||
if not silent:
|
||||
token = state.push("text_special", "", 0)
|
||||
token.content = entities[match.group(1)]
|
||||
token.markup = match.group(0)
|
||||
token.info = "entity"
|
||||
|
||||
state.pos += len(match.group(0))
|
||||
return True
|
||||
|
||||
return False
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
"""
|
||||
Process escaped chars and hardbreaks
|
||||
"""
|
||||
from ..common.utils import isStrSpace
|
||||
from .state_inline import StateInline
|
||||
|
||||
|
||||
def escape(state: StateInline, silent: bool) -> bool:
|
||||
"""Process escaped chars and hardbreaks."""
|
||||
pos = state.pos
|
||||
maximum = state.posMax
|
||||
|
||||
if state.src[pos] != "\\":
|
||||
return False
|
||||
|
||||
pos += 1
|
||||
|
||||
# '\' at the end of the inline block
|
||||
if pos >= maximum:
|
||||
return False
|
||||
|
||||
ch1 = state.src[pos]
|
||||
ch1_ord = ord(ch1)
|
||||
if ch1 == "\n":
|
||||
if not silent:
|
||||
state.push("hardbreak", "br", 0)
|
||||
pos += 1
|
||||
# skip leading whitespaces from next line
|
||||
while pos < maximum:
|
||||
ch = state.src[pos]
|
||||
if not isStrSpace(ch):
|
||||
break
|
||||
pos += 1
|
||||
|
||||
state.pos = pos
|
||||
return True
|
||||
|
||||
escapedStr = state.src[pos]
|
||||
|
||||
if ch1_ord >= 0xD800 and ch1_ord <= 0xDBFF and pos + 1 < maximum:
|
||||
ch2 = state.src[pos + 1]
|
||||
ch2_ord = ord(ch2)
|
||||
if ch2_ord >= 0xDC00 and ch2_ord <= 0xDFFF:
|
||||
escapedStr += ch2
|
||||
pos += 1
|
||||
|
||||
origStr = "\\" + escapedStr
|
||||
|
||||
if not silent:
|
||||
token = state.push("text_special", "", 0)
|
||||
token.content = escapedStr if ch1 in _ESCAPED else origStr
|
||||
token.markup = origStr
|
||||
token.info = "escape"
|
||||
|
||||
state.pos = pos + 1
|
||||
return True
|
||||
|
||||
|
||||
_ESCAPED = {
|
||||
"!",
|
||||
'"',
|
||||
"#",
|
||||
"$",
|
||||
"%",
|
||||
"&",
|
||||
"'",
|
||||
"(",
|
||||
")",
|
||||
"*",
|
||||
"+",
|
||||
",",
|
||||
"-",
|
||||
".",
|
||||
"/",
|
||||
":",
|
||||
";",
|
||||
"<",
|
||||
"=",
|
||||
">",
|
||||
"?",
|
||||
"@",
|
||||
"[",
|
||||
"\\",
|
||||
"]",
|
||||
"^",
|
||||
"_",
|
||||
"`",
|
||||
"{",
|
||||
"|",
|
||||
"}",
|
||||
"~",
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
from .state_inline import StateInline
|
||||
|
||||
|
||||
def fragments_join(state: StateInline) -> None:
|
||||
"""
|
||||
Clean up tokens after emphasis and strikethrough postprocessing:
|
||||
merge adjacent text nodes into one and re-calculate all token levels
|
||||
|
||||
This is necessary because initially emphasis delimiter markers (``*, _, ~``)
|
||||
are treated as their own separate text tokens. Then emphasis rule either
|
||||
leaves them as text (needed to merge with adjacent text) or turns them
|
||||
into opening/closing tags (which messes up levels inside).
|
||||
"""
|
||||
level = 0
|
||||
maximum = len(state.tokens)
|
||||
|
||||
curr = last = 0
|
||||
while curr < maximum:
|
||||
# re-calculate levels after emphasis/strikethrough turns some text nodes
|
||||
# into opening/closing tags
|
||||
if state.tokens[curr].nesting < 0:
|
||||
level -= 1 # closing tag
|
||||
state.tokens[curr].level = level
|
||||
if state.tokens[curr].nesting > 0:
|
||||
level += 1 # opening tag
|
||||
|
||||
if (
|
||||
state.tokens[curr].type == "text"
|
||||
and curr + 1 < maximum
|
||||
and state.tokens[curr + 1].type == "text"
|
||||
):
|
||||
# collapse two adjacent text nodes
|
||||
state.tokens[curr + 1].content = (
|
||||
state.tokens[curr].content + state.tokens[curr + 1].content
|
||||
)
|
||||
else:
|
||||
if curr != last:
|
||||
state.tokens[last] = state.tokens[curr]
|
||||
last += 1
|
||||
curr += 1
|
||||
|
||||
if curr != last:
|
||||
del state.tokens[last:]
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
# Process html tags
|
||||
from ..common.html_re import HTML_TAG_RE
|
||||
from ..common.utils import isLinkClose, isLinkOpen
|
||||
from .state_inline import StateInline
|
||||
|
||||
|
||||
def isLetter(ch: int) -> bool:
|
||||
lc = ch | 0x20 # to lower case
|
||||
# /* a */ and /* z */
|
||||
return (lc >= 0x61) and (lc <= 0x7A)
|
||||
|
||||
|
||||
def html_inline(state: StateInline, silent: bool) -> bool:
|
||||
pos = state.pos
|
||||
|
||||
if not state.md.options.get("html", None):
|
||||
return False
|
||||
|
||||
# Check start
|
||||
maximum = state.posMax
|
||||
if state.src[pos] != "<" or pos + 2 >= maximum:
|
||||
return False
|
||||
|
||||
# Quick fail on second char
|
||||
ch = state.src[pos + 1]
|
||||
if ch not in ("!", "?", "/") and not isLetter(ord(ch)): # /* / */
|
||||
return False
|
||||
|
||||
match = HTML_TAG_RE.search(state.src[pos:])
|
||||
if not match:
|
||||
return False
|
||||
|
||||
if not silent:
|
||||
token = state.push("html_inline", "", 0)
|
||||
token.content = state.src[pos : pos + len(match.group(0))]
|
||||
|
||||
if isLinkOpen(token.content):
|
||||
state.linkLevel += 1
|
||||
if isLinkClose(token.content):
|
||||
state.linkLevel -= 1
|
||||
|
||||
state.pos += len(match.group(0))
|
||||
return True
|
||||
+148
@@ -0,0 +1,148 @@
|
||||
# Process 
|
||||
from __future__ import annotations
|
||||
|
||||
from ..common.utils import isStrSpace, normalizeReference
|
||||
from ..token import Token
|
||||
from .state_inline import StateInline
|
||||
|
||||
|
||||
def image(state: StateInline, silent: bool) -> bool:
|
||||
label = None
|
||||
href = ""
|
||||
oldPos = state.pos
|
||||
max = state.posMax
|
||||
|
||||
if state.src[state.pos] != "!":
|
||||
return False
|
||||
|
||||
if state.pos + 1 < state.posMax and state.src[state.pos + 1] != "[":
|
||||
return False
|
||||
|
||||
labelStart = state.pos + 2
|
||||
labelEnd = state.md.helpers.parseLinkLabel(state, state.pos + 1, False)
|
||||
|
||||
# parser failed to find ']', so it's not a valid link
|
||||
if labelEnd < 0:
|
||||
return False
|
||||
|
||||
pos = labelEnd + 1
|
||||
|
||||
if pos < max and state.src[pos] == "(":
|
||||
#
|
||||
# Inline link
|
||||
#
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^ skipping these spaces
|
||||
pos += 1
|
||||
while pos < max:
|
||||
ch = state.src[pos]
|
||||
if not isStrSpace(ch) and ch != "\n":
|
||||
break
|
||||
pos += 1
|
||||
|
||||
if pos >= max:
|
||||
return False
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^^^^^ parsing link destination
|
||||
start = pos
|
||||
res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax)
|
||||
if res.ok:
|
||||
href = state.md.normalizeLink(res.str)
|
||||
if state.md.validateLink(href):
|
||||
pos = res.pos
|
||||
else:
|
||||
href = ""
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^ skipping these spaces
|
||||
start = pos
|
||||
while pos < max:
|
||||
ch = state.src[pos]
|
||||
if not isStrSpace(ch) and ch != "\n":
|
||||
break
|
||||
pos += 1
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^^^^^^ parsing link title
|
||||
res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax)
|
||||
if pos < max and start != pos and res.ok:
|
||||
title = res.str
|
||||
pos = res.pos
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^ skipping these spaces
|
||||
while pos < max:
|
||||
ch = state.src[pos]
|
||||
if not isStrSpace(ch) and ch != "\n":
|
||||
break
|
||||
pos += 1
|
||||
else:
|
||||
title = ""
|
||||
|
||||
if pos >= max or state.src[pos] != ")":
|
||||
state.pos = oldPos
|
||||
return False
|
||||
|
||||
pos += 1
|
||||
|
||||
else:
|
||||
#
|
||||
# Link reference
|
||||
#
|
||||
if "references" not in state.env:
|
||||
return False
|
||||
|
||||
# /* [ */
|
||||
if pos < max and state.src[pos] == "[":
|
||||
start = pos + 1
|
||||
pos = state.md.helpers.parseLinkLabel(state, pos)
|
||||
if pos >= 0:
|
||||
label = state.src[start:pos]
|
||||
pos += 1
|
||||
else:
|
||||
pos = labelEnd + 1
|
||||
else:
|
||||
pos = labelEnd + 1
|
||||
|
||||
# covers label == '' and label == undefined
|
||||
# (collapsed reference link and shortcut reference link respectively)
|
||||
if not label:
|
||||
label = state.src[labelStart:labelEnd]
|
||||
|
||||
label = normalizeReference(label)
|
||||
|
||||
ref = state.env["references"].get(label, None)
|
||||
if not ref:
|
||||
state.pos = oldPos
|
||||
return False
|
||||
|
||||
href = ref["href"]
|
||||
title = ref["title"]
|
||||
|
||||
#
|
||||
# We found the end of the link, and know for a fact it's a valid link
|
||||
# so all that's left to do is to call tokenizer.
|
||||
#
|
||||
if not silent:
|
||||
content = state.src[labelStart:labelEnd]
|
||||
|
||||
tokens: list[Token] = []
|
||||
state.md.inline.parse(content, state.md, state.env, tokens)
|
||||
|
||||
token = state.push("image", "img", 0)
|
||||
token.attrs = {"src": href, "alt": ""}
|
||||
token.children = tokens or None
|
||||
token.content = content
|
||||
|
||||
if title:
|
||||
token.attrSet("title", title)
|
||||
|
||||
# note, this is not part of markdown-it JS, but is useful for renderers
|
||||
if label and state.md.options.get("store_labels", False):
|
||||
token.meta["label"] = label
|
||||
|
||||
state.pos = pos
|
||||
state.posMax = max
|
||||
return True
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
# Process [link](<to> "stuff")
|
||||
|
||||
from ..common.utils import isStrSpace, normalizeReference
|
||||
from .state_inline import StateInline
|
||||
|
||||
|
||||
def link(state: StateInline, silent: bool) -> bool:
|
||||
href = ""
|
||||
title = ""
|
||||
label = None
|
||||
oldPos = state.pos
|
||||
maximum = state.posMax
|
||||
start = state.pos
|
||||
parseReference = True
|
||||
|
||||
if state.src[state.pos] != "[":
|
||||
return False
|
||||
|
||||
labelStart = state.pos + 1
|
||||
labelEnd = state.md.helpers.parseLinkLabel(state, state.pos, True)
|
||||
|
||||
# parser failed to find ']', so it's not a valid link
|
||||
if labelEnd < 0:
|
||||
return False
|
||||
|
||||
pos = labelEnd + 1
|
||||
|
||||
if pos < maximum and state.src[pos] == "(":
|
||||
#
|
||||
# Inline link
|
||||
#
|
||||
|
||||
# might have found a valid shortcut link, disable reference parsing
|
||||
parseReference = False
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^ skipping these spaces
|
||||
pos += 1
|
||||
while pos < maximum:
|
||||
ch = state.src[pos]
|
||||
if not isStrSpace(ch) and ch != "\n":
|
||||
break
|
||||
pos += 1
|
||||
|
||||
if pos >= maximum:
|
||||
return False
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^^^^^ parsing link destination
|
||||
start = pos
|
||||
res = state.md.helpers.parseLinkDestination(state.src, pos, state.posMax)
|
||||
if res.ok:
|
||||
href = state.md.normalizeLink(res.str)
|
||||
if state.md.validateLink(href):
|
||||
pos = res.pos
|
||||
else:
|
||||
href = ""
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^ skipping these spaces
|
||||
start = pos
|
||||
while pos < maximum:
|
||||
ch = state.src[pos]
|
||||
if not isStrSpace(ch) and ch != "\n":
|
||||
break
|
||||
pos += 1
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^^^^^^ parsing link title
|
||||
res = state.md.helpers.parseLinkTitle(state.src, pos, state.posMax)
|
||||
if pos < maximum and start != pos and res.ok:
|
||||
title = res.str
|
||||
pos = res.pos
|
||||
|
||||
# [link]( <href> "title" )
|
||||
# ^^ skipping these spaces
|
||||
while pos < maximum:
|
||||
ch = state.src[pos]
|
||||
if not isStrSpace(ch) and ch != "\n":
|
||||
break
|
||||
pos += 1
|
||||
|
||||
if pos >= maximum or state.src[pos] != ")":
|
||||
# parsing a valid shortcut link failed, fallback to reference
|
||||
parseReference = True
|
||||
|
||||
pos += 1
|
||||
|
||||
if parseReference:
|
||||
#
|
||||
# Link reference
|
||||
#
|
||||
if "references" not in state.env:
|
||||
return False
|
||||
|
||||
if pos < maximum and state.src[pos] == "[":
|
||||
start = pos + 1
|
||||
pos = state.md.helpers.parseLinkLabel(state, pos)
|
||||
if pos >= 0:
|
||||
label = state.src[start:pos]
|
||||
pos += 1
|
||||
else:
|
||||
pos = labelEnd + 1
|
||||
|
||||
else:
|
||||
pos = labelEnd + 1
|
||||
|
||||
# covers label == '' and label == undefined
|
||||
# (collapsed reference link and shortcut reference link respectively)
|
||||
if not label:
|
||||
label = state.src[labelStart:labelEnd]
|
||||
|
||||
label = normalizeReference(label)
|
||||
|
||||
ref = (
|
||||
state.env["references"][label] if label in state.env["references"] else None
|
||||
)
|
||||
if not ref:
|
||||
state.pos = oldPos
|
||||
return False
|
||||
|
||||
href = ref["href"]
|
||||
title = ref["title"]
|
||||
|
||||
#
|
||||
# We found the end of the link, and know for a fact it's a valid link
|
||||
# so all that's left to do is to call tokenizer.
|
||||
#
|
||||
if not silent:
|
||||
state.pos = labelStart
|
||||
state.posMax = labelEnd
|
||||
|
||||
token = state.push("link_open", "a", 1)
|
||||
token.attrs = {"href": href}
|
||||
|
||||
if title:
|
||||
token.attrSet("title", title)
|
||||
|
||||
# note, this is not part of markdown-it JS, but is useful for renderers
|
||||
if label and state.md.options.get("store_labels", False):
|
||||
token.meta["label"] = label
|
||||
|
||||
state.linkLevel += 1
|
||||
state.md.inline.tokenize(state)
|
||||
state.linkLevel -= 1
|
||||
|
||||
token = state.push("link_close", "a", -1)
|
||||
|
||||
state.pos = pos
|
||||
state.posMax = maximum
|
||||
return True
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
"""Process links like https://example.org/"""
|
||||
import re
|
||||
|
||||
from .state_inline import StateInline
|
||||
|
||||
# RFC3986: scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
|
||||
SCHEME_RE = re.compile(r"(?:^|[^a-z0-9.+-])([a-z][a-z0-9.+-]*)$", re.IGNORECASE)
|
||||
|
||||
|
||||
def linkify(state: StateInline, silent: bool) -> bool:
|
||||
"""Rule for identifying plain-text links."""
|
||||
if not state.md.options.linkify:
|
||||
return False
|
||||
if state.linkLevel > 0:
|
||||
return False
|
||||
if not state.md.linkify:
|
||||
raise ModuleNotFoundError("Linkify enabled but not installed.")
|
||||
|
||||
pos = state.pos
|
||||
maximum = state.posMax
|
||||
|
||||
if (
|
||||
(pos + 3) > maximum
|
||||
or state.src[pos] != ":"
|
||||
or state.src[pos + 1] != "/"
|
||||
or state.src[pos + 2] != "/"
|
||||
):
|
||||
return False
|
||||
|
||||
if not (match := SCHEME_RE.match(state.pending)):
|
||||
return False
|
||||
|
||||
proto = match.group(1)
|
||||
if not (link := state.md.linkify.match_at_start(state.src[pos - len(proto) :])):
|
||||
return False
|
||||
url: str = link.url
|
||||
|
||||
# disallow '*' at the end of the link (conflicts with emphasis)
|
||||
url = url.rstrip("*")
|
||||
|
||||
full_url = state.md.normalizeLink(url)
|
||||
if not state.md.validateLink(full_url):
|
||||
return False
|
||||
|
||||
if not silent:
|
||||
state.pending = state.pending[: -len(proto)]
|
||||
|
||||
token = state.push("link_open", "a", 1)
|
||||
token.attrs = {"href": full_url}
|
||||
token.markup = "linkify"
|
||||
token.info = "auto"
|
||||
|
||||
token = state.push("text", "", 0)
|
||||
token.content = state.md.normalizeLinkText(url)
|
||||
|
||||
token = state.push("link_close", "a", -1)
|
||||
token.markup = "linkify"
|
||||
token.info = "auto"
|
||||
|
||||
state.pos += len(url) - len(proto)
|
||||
return True
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
"""Proceess '\n'."""
|
||||
from ..common.utils import charStrAt, isStrSpace
|
||||
from .state_inline import StateInline
|
||||
|
||||
|
||||
def newline(state: StateInline, silent: bool) -> bool:
|
||||
pos = state.pos
|
||||
|
||||
if state.src[pos] != "\n":
|
||||
return False
|
||||
|
||||
pmax = len(state.pending) - 1
|
||||
maximum = state.posMax
|
||||
|
||||
# ' \n' -> hardbreak
|
||||
# Lookup in pending chars is bad practice! Don't copy to other rules!
|
||||
# Pending string is stored in concat mode, indexed lookups will cause
|
||||
# conversion to flat mode.
|
||||
if not silent:
|
||||
if pmax >= 0 and charStrAt(state.pending, pmax) == " ":
|
||||
if pmax >= 1 and charStrAt(state.pending, pmax - 1) == " ":
|
||||
# Find whitespaces tail of pending chars.
|
||||
ws = pmax - 1
|
||||
while ws >= 1 and charStrAt(state.pending, ws - 1) == " ":
|
||||
ws -= 1
|
||||
state.pending = state.pending[:ws]
|
||||
|
||||
state.push("hardbreak", "br", 0)
|
||||
else:
|
||||
state.pending = state.pending[:-1]
|
||||
state.push("softbreak", "br", 0)
|
||||
|
||||
else:
|
||||
state.push("softbreak", "br", 0)
|
||||
|
||||
pos += 1
|
||||
|
||||
# skip heading spaces for next line
|
||||
while pos < maximum and isStrSpace(state.src[pos]):
|
||||
pos += 1
|
||||
|
||||
state.pos = pos
|
||||
return True
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import namedtuple
|
||||
from dataclasses import dataclass
|
||||
from typing import TYPE_CHECKING, Any, Literal
|
||||
|
||||
from .._compat import DATACLASS_KWARGS
|
||||
from ..common.utils import isMdAsciiPunct, isPunctChar, isWhiteSpace
|
||||
from ..ruler import StateBase
|
||||
from ..token import Token
|
||||
from ..utils import EnvType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from markdown_it import MarkdownIt
|
||||
|
||||
|
||||
@dataclass(**DATACLASS_KWARGS)
|
||||
class Delimiter:
|
||||
# Char code of the starting marker (number).
|
||||
marker: int
|
||||
|
||||
# Total length of these series of delimiters.
|
||||
length: int
|
||||
|
||||
# A position of the token this delimiter corresponds to.
|
||||
token: int
|
||||
|
||||
# If this delimiter is matched as a valid opener, `end` will be
|
||||
# equal to its position, otherwise it's `-1`.
|
||||
end: int
|
||||
|
||||
# Boolean flags that determine if this delimiter could open or close
|
||||
# an emphasis.
|
||||
open: bool
|
||||
close: bool
|
||||
|
||||
level: bool | None = None
|
||||
|
||||
|
||||
Scanned = namedtuple("Scanned", ["can_open", "can_close", "length"])
|
||||
|
||||
|
||||
class StateInline(StateBase):
|
||||
def __init__(
|
||||
self, src: str, md: MarkdownIt, env: EnvType, outTokens: list[Token]
|
||||
) -> None:
|
||||
self.src = src
|
||||
self.env = env
|
||||
self.md = md
|
||||
self.tokens = outTokens
|
||||
self.tokens_meta: list[dict[str, Any] | None] = [None] * len(outTokens)
|
||||
|
||||
self.pos = 0
|
||||
self.posMax = len(self.src)
|
||||
self.level = 0
|
||||
self.pending = ""
|
||||
self.pendingLevel = 0
|
||||
|
||||
# Stores { start: end } pairs. Useful for backtrack
|
||||
# optimization of pairs parse (emphasis, strikes).
|
||||
self.cache: dict[int, int] = {}
|
||||
|
||||
# List of emphasis-like delimiters for current tag
|
||||
self.delimiters: list[Delimiter] = []
|
||||
|
||||
# Stack of delimiter lists for upper level tags
|
||||
self._prev_delimiters: list[list[Delimiter]] = []
|
||||
|
||||
# backticklength => last seen position
|
||||
self.backticks: dict[int, int] = {}
|
||||
self.backticksScanned = False
|
||||
|
||||
# Counter used to disable inline linkify-it execution
|
||||
# inside <a> and markdown links
|
||||
self.linkLevel = 0
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return (
|
||||
f"{self.__class__.__name__}"
|
||||
f"(pos=[{self.pos} of {self.posMax}], token={len(self.tokens)})"
|
||||
)
|
||||
|
||||
def pushPending(self) -> Token:
|
||||
token = Token("text", "", 0)
|
||||
token.content = self.pending
|
||||
token.level = self.pendingLevel
|
||||
self.tokens.append(token)
|
||||
self.pending = ""
|
||||
return token
|
||||
|
||||
def push(self, ttype: str, tag: str, nesting: Literal[-1, 0, 1]) -> Token:
|
||||
"""Push new token to "stream".
|
||||
If pending text exists - flush it as text token
|
||||
"""
|
||||
if self.pending:
|
||||
self.pushPending()
|
||||
|
||||
token = Token(ttype, tag, nesting)
|
||||
token_meta = None
|
||||
|
||||
if nesting < 0:
|
||||
# closing tag
|
||||
self.level -= 1
|
||||
self.delimiters = self._prev_delimiters.pop()
|
||||
|
||||
token.level = self.level
|
||||
|
||||
if nesting > 0:
|
||||
# opening tag
|
||||
self.level += 1
|
||||
self._prev_delimiters.append(self.delimiters)
|
||||
self.delimiters = []
|
||||
token_meta = {"delimiters": self.delimiters}
|
||||
|
||||
self.pendingLevel = self.level
|
||||
self.tokens.append(token)
|
||||
self.tokens_meta.append(token_meta)
|
||||
return token
|
||||
|
||||
def scanDelims(self, start: int, canSplitWord: bool) -> Scanned:
|
||||
"""
|
||||
Scan a sequence of emphasis-like markers, and determine whether
|
||||
it can start an emphasis sequence or end an emphasis sequence.
|
||||
|
||||
- start - position to scan from (it should point at a valid marker);
|
||||
- canSplitWord - determine if these markers can be found inside a word
|
||||
|
||||
"""
|
||||
pos = start
|
||||
maximum = self.posMax
|
||||
marker = self.src[start]
|
||||
|
||||
# treat beginning of the line as a whitespace
|
||||
lastChar = self.src[start - 1] if start > 0 else " "
|
||||
|
||||
while pos < maximum and self.src[pos] == marker:
|
||||
pos += 1
|
||||
|
||||
count = pos - start
|
||||
|
||||
# treat end of the line as a whitespace
|
||||
nextChar = self.src[pos] if pos < maximum else " "
|
||||
|
||||
isLastPunctChar = isMdAsciiPunct(ord(lastChar)) or isPunctChar(lastChar)
|
||||
isNextPunctChar = isMdAsciiPunct(ord(nextChar)) or isPunctChar(nextChar)
|
||||
|
||||
isLastWhiteSpace = isWhiteSpace(ord(lastChar))
|
||||
isNextWhiteSpace = isWhiteSpace(ord(nextChar))
|
||||
|
||||
left_flanking = not (
|
||||
isNextWhiteSpace
|
||||
or (isNextPunctChar and not (isLastWhiteSpace or isLastPunctChar))
|
||||
)
|
||||
right_flanking = not (
|
||||
isLastWhiteSpace
|
||||
or (isLastPunctChar and not (isNextWhiteSpace or isNextPunctChar))
|
||||
)
|
||||
|
||||
if not canSplitWord:
|
||||
can_open = left_flanking and ((not right_flanking) or isLastPunctChar)
|
||||
can_close = right_flanking and ((not left_flanking) or isNextPunctChar)
|
||||
else:
|
||||
can_open = left_flanking
|
||||
can_close = right_flanking
|
||||
|
||||
return Scanned(can_open, can_close, count)
|
||||
+127
@@ -0,0 +1,127 @@
|
||||
# ~~strike through~~
|
||||
from __future__ import annotations
|
||||
|
||||
from .state_inline import Delimiter, StateInline
|
||||
|
||||
|
||||
def tokenize(state: StateInline, silent: bool) -> bool:
|
||||
"""Insert each marker as a separate text token, and add it to delimiter list"""
|
||||
start = state.pos
|
||||
ch = state.src[start]
|
||||
|
||||
if silent:
|
||||
return False
|
||||
|
||||
if ch != "~":
|
||||
return False
|
||||
|
||||
scanned = state.scanDelims(state.pos, True)
|
||||
length = scanned.length
|
||||
|
||||
if length < 2:
|
||||
return False
|
||||
|
||||
if length % 2:
|
||||
token = state.push("text", "", 0)
|
||||
token.content = ch
|
||||
length -= 1
|
||||
|
||||
i = 0
|
||||
while i < length:
|
||||
token = state.push("text", "", 0)
|
||||
token.content = ch + ch
|
||||
state.delimiters.append(
|
||||
Delimiter(
|
||||
marker=ord(ch),
|
||||
length=0, # disable "rule of 3" length checks meant for emphasis
|
||||
token=len(state.tokens) - 1,
|
||||
end=-1,
|
||||
open=scanned.can_open,
|
||||
close=scanned.can_close,
|
||||
)
|
||||
)
|
||||
|
||||
i += 2
|
||||
|
||||
state.pos += scanned.length
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def _postProcess(state: StateInline, delimiters: list[Delimiter]) -> None:
|
||||
loneMarkers = []
|
||||
maximum = len(delimiters)
|
||||
|
||||
i = 0
|
||||
while i < maximum:
|
||||
startDelim = delimiters[i]
|
||||
|
||||
if startDelim.marker != 0x7E: # /* ~ */
|
||||
i += 1
|
||||
continue
|
||||
|
||||
if startDelim.end == -1:
|
||||
i += 1
|
||||
continue
|
||||
|
||||
endDelim = delimiters[startDelim.end]
|
||||
|
||||
token = state.tokens[startDelim.token]
|
||||
token.type = "s_open"
|
||||
token.tag = "s"
|
||||
token.nesting = 1
|
||||
token.markup = "~~"
|
||||
token.content = ""
|
||||
|
||||
token = state.tokens[endDelim.token]
|
||||
token.type = "s_close"
|
||||
token.tag = "s"
|
||||
token.nesting = -1
|
||||
token.markup = "~~"
|
||||
token.content = ""
|
||||
|
||||
if (
|
||||
state.tokens[endDelim.token - 1].type == "text"
|
||||
and state.tokens[endDelim.token - 1].content == "~"
|
||||
):
|
||||
loneMarkers.append(endDelim.token - 1)
|
||||
|
||||
i += 1
|
||||
|
||||
# If a marker sequence has an odd number of characters, it's split
|
||||
# like this: `~~~~~` -> `~` + `~~` + `~~`, leaving one marker at the
|
||||
# start of the sequence.
|
||||
#
|
||||
# So, we have to move all those markers after subsequent s_close tags.
|
||||
#
|
||||
while loneMarkers:
|
||||
i = loneMarkers.pop()
|
||||
j = i + 1
|
||||
|
||||
while (j < len(state.tokens)) and (state.tokens[j].type == "s_close"):
|
||||
j += 1
|
||||
|
||||
j -= 1
|
||||
|
||||
if i != j:
|
||||
token = state.tokens[j]
|
||||
state.tokens[j] = state.tokens[i]
|
||||
state.tokens[i] = token
|
||||
|
||||
|
||||
def postProcess(state: StateInline) -> None:
|
||||
"""Walk through delimiter list and replace text tokens with tags."""
|
||||
tokens_meta = state.tokens_meta
|
||||
maximum = len(state.tokens_meta)
|
||||
_postProcess(state, state.delimiters)
|
||||
|
||||
curr = 0
|
||||
while curr < maximum:
|
||||
try:
|
||||
curr_meta = tokens_meta[curr]
|
||||
except IndexError:
|
||||
pass
|
||||
else:
|
||||
if curr_meta and "delimiters" in curr_meta:
|
||||
_postProcess(state, curr_meta["delimiters"])
|
||||
curr += 1
|
||||
Loaded 100 of 926 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user