Author SHA1 Message Date
funkpower d0efc56312 The Sundays the calendar was not naming, and a calendar that keeps every day
Nine Sundays went unnamed in every jurisdiction. Three were missing from the
movable cycle outright: the Paralytic, the Samaritan Woman and the Blind Man,
so the fourth, fifth and sixth Sundays of Pascha reported only the saint of the
fixed date. Six more are reckoned from a fixed feast rather than from Pascha —
before and after the Exaltation, the Forefathers, before and after the
Nativity, before and after the Theophany — and were not modelled at all.

The three Pentecostarion Sundays rank with Thomas Sunday and the Myrrh-bearing
Women, so a vigil-rank saint still keeps the day and the Sunday is commemorated
on it. The six fixed-cycle ones never name a day: they are found in
ecclesiastical space, so the old calendar and the new get them on the right
morning, and they join the commemorations. Where a short window holds no Sunday
the Typikon says what to do and this follows it; where the books disagree, the
day goes unmarked rather than carrying an answer this calendar cannot defend.

`week` says where a day falls in the count from Pentecost, which is how the
books head the long ordinary stretch. It runs on across the new year and stops
at the Triodion, whose Sundays have names instead of numbers.

`--every-day` gives ics an event for every day, ferias included. The default
still thins the calendar, which is right for a subscription and wrong for a
reader who wants the saint of each morning; and the description now leads with
the commemorations rather than burying them under the church date.

Checked against 1.1.2 over every jurisdiction from 2015 to 2035: rank, feast
and title move on the three new Sundays and nowhere else. No fast, obligation,
binding or season changes on any day.
2026-09-21 09:28:27 -04:00
funkpower 93b597302a 1.1.2 — one sentence, in all five places a reader meets it
1.1.1 changed the description in Cargo.toml and in the npm package and
missed pyproject.toml, which is the one maturin publishes. PyPI took the
old summary and neither registry lets that be edited afterwards, so the
correction needs a version of its own.

The two READMEs had drifted further than the description fields. A
registry page leads with the README rather than the summary, and npm's
opened by saying the package needs no network without ever saying it
covers the Byzantine Catholic churches — which is most of what the
sentence was changed to convey.

Five files now carry it, and a test reads all five and names the ones
that disagree. It was written against the mistake above and fails on it.
2026-09-21 07:46:58 -04:00
funkpower dde50192c7 1.1.1
The README stops explaining how the project tests and releases itself.
Someone arriving at it wants to know what a day of the Great Fast
permits, not how the wheels get built; the parity suite and the release
workflow are in docs/, where the person who needs them will look.

The published description now says how many churches are covered, on
both registries. That is a number in two files nobody editing the
jurisdiction table will open, so a test pins it and names them.
2026-09-21 07:29:05 -04:00
funkpower 5f26563334 no change; checking that a workflow step added by a push actually runs 2026-09-18 16:17:17 -04:00
funkpower 33441113ce ask every binding the same question and insist on the same answer
There is one engine and nine doors into it, and nothing until now checked
that the doors agree. CI tested each binding against itself: the Python
wheel imported, the C demo compiled, the npm package type-checked. None
of that would have caught a field that crosses one boundary wrong, which
is the failure this library is most exposed to, because a wrong answer
about a fast day looks exactly like a right one.

So: twelve days, chosen where the bindings could plausibly differ, and
all twenty-two fields compared against what the command line says. The
days are Pascha itself, the Nativity on both calendars, a Wednesday of
the Great Fast under Byzantine Catholic law and again at the Typikon, a
weekday of the Nativity Fast where Greek and Slavic usage part, the one
Orthodox church on the Gregorian Paschalion, and a day with no feast.

A release now runs what a push runs. It had been gated on cargo test
alone, so the C ABI, the Lua binding, the Python parity check and the
README examples were checked on the branch that led to a release and not
on the release. Neither registry will reuse a version, so the gate
belongs before the upload.

Writing it found three things. The npm exports map did not expose the
wasm by package path, so a bundler asked for typikon/web/typikon_bg.wasm
was told no such path exists and had to reach into node_modules; the
documented init() call was never affected. The suite could hang instead
of fail, because the test web server was backgrounded inside a subshell
and killed by job spec, leaving bash in do_wait forever. And pointing
XDG_CONFIG_HOME at a path that does not exist isolates typikon and
breaks every other program that keeps state under it, a browser included.

A surface whose toolchain is missing is named as skipped, and fewer than
three surfaces running is a failure rather than a pass, so a container
with nothing installed cannot come out green.
2026-09-18 16:08:41 -04:00
41 changed files with 1411 additions and 58 deletions
+15
View File
@@ -119,3 +119,18 @@ jobs:
run: |
cargo build --release
python3 tests/readme-examples.py
# Every binding is the same engine reached by a different door, so the
# answers have to be identical, and the only way to know is to ask them
# all the same question. Twelve days chosen where they could plausibly
# differ, twenty-two fields each, against what the command line says.
#
# Chromium is installed for this: the web build is the one artifact whose
# real home is somewhere Node cannot stand in for, and loading it with
# Node's bytes proves the glue, not the fetch.
- name: Every binding agrees
run: |
apt-get install -y --no-install-recommends chromium
version=$(awk '/^name = "wasm-bindgen"$/{getline; gsub(/[",]/,""); print $3; exit}' Cargo.lock)
export PATH="/tmp/wasm-bindgen-$version-x86_64-unknown-linux-musl:$PATH"
tests/parity.sh
+24 -1
View File
@@ -32,8 +32,20 @@ jobs:
echo "tag=$tag crate=$crate"
[ "$tag" = "$crate" ] || { echo "::error::tag $tag != Cargo.toml $crate"; exit 1; }
# What CI runs on every push, run again here. A release is the one build
# nobody gets to re-run after the fact: PyPI will not reuse a version and
# neither will npm, so the gate belongs before the upload rather than
# only on the branch that led to it.
- name: Tests
run: cargo test
run: |
rustup component add clippy
cargo clippy --all-targets -- -D warnings
cargo clippy --features python --all-targets -- -D warnings
cargo clippy --features capi --all-targets -- -D warnings
rustup target add wasm32-unknown-unknown
cargo clippy --lib --features wasm --target wasm32-unknown-unknown -- -D warnings
cargo test
cargo test --features capi
- name: Build wheels and sdist
run: |
@@ -76,6 +88,17 @@ jobs:
npm/build.sh
node npm/test.mjs
# The whole point of a release is that every door leads to the same
# engine. Checked here against what is about to be uploaded, and again
# after the fact with --published against what actually was.
- name: Every binding agrees
run: |
apt-get install -y --no-install-recommends chromium luajit
version=$(awk '/^name = "wasm-bindgen"$/{getline; gsub(/[",]/,""); print $3; exit}' Cargo.lock)
export PATH="/tmp/wasm-bindgen-$version-x86_64-unknown-linux-musl:$PATH"
tests/parity.sh
python3 tests/readme-examples.py
- name: Publish
env:
# A project-scoped token, not the account-wide one. PyPI's trusted
+102
View File
@@ -4,6 +4,108 @@ Notable changes, in the terms [docs/versioning.md](docs/versioning.md) sets out.
**Calendar** entries change what a day reports, whatever the version number
does.
## 1.2.0
### Calendar
- **The Pentecostarion keeps all of its Sundays.** The Sunday of the Paralytic,
the Sunday of the Samaritan Woman and the Sunday of the Blind Man were absent
from the movable cycle altogether, so the third, fourth and fifth Sundays
after Thomas Sunday reported only the saint of the fixed date. Every
jurisdiction was affected. In 2027 that is 18 and 25 April and 2 May by the
Gregorian paschalion, 23 and 30 May and 6 June by the Julian one. They rank
with Thomas Sunday and the Myrrh-bearing Women, so a fixed feast of vigil
rank still names the day and the Sunday is commemorated on it: 25 April 2027
stays St Mark and gains the Samaritan Woman.
- **The Sundays reckoned from a fixed feast are kept.** Six more that the
calendar never named: the Sundays before and after the Exaltation, the Sunday
of the Holy Forefathers, the Sundays before and after the Nativity, and the
Sundays before and after the Theophany. They are found in ecclesiastical
space, so the old calendar and the new both get them on the right morning,
and they join the day's commemorations rather than displacing its saint.
Two years in the cycle leave a window without a Sunday in it, and the Typikon
says where those go: a Nativity on a Sunday puts the Sunday after it on 26
December, and a 1 January on a Sunday keeps the Sunday before the Theophany
with the Circumcision. The two remaining cases, the Theophany itself or the
Exaltation on a Sunday, go unmarked, because the books disagree about where
what belongs in them should land.
### Added
- `week`: where the day falls in the count from Pentecost, worded as the books
head it — `the 32nd Sunday after Pentecost`, or `the 32nd week after
Pentecost` on the days between. Null through the Triodion and the
Pentecostarion, whose Sundays carry names instead of numbers. The count runs
on across the new year from the Pentecost that opened it, and stops at the
next Sunday of the Publican and the Pharisee. It is in the JSON, a column in
`csv` and `tsv`, a line in the single-day view, and a getter on every
binding.
- `--every-day`: one event per day in `--format ics`, ferias included. The
default still thins the calendar to the days carrying a feast or a fast,
which is right for a subscription and wrong for a reader who wants the saint
of each morning.
### Changed
- The iCalendar description leads with the day's commemorations, one to a line,
then the fast and its reason, then the season, the week and the church date.
They were last before, after the church date, and a client showing three
lines of a popover showed everything except what the day commemorates. The
summary now carries the rank's mark beside the fasting glyph, as the text
view has always done, and the fast is stated on every event rather than only
on the days that keep one.
- `typikon::export::to_ics_with` and `Ics` are the way to reach the new option
from the library. `to_ics` is unchanged and still writes the thinned
calendar.
## 1.1.2
### Fixed
- The published description says what the package covers, and says the same
thing in both registries. PyPI takes its summary from `pyproject.toml`, which
1.1.1 did not update, so it went out with the old one-line text while npm got
the new one. The two READMEs had drifted apart as well: npm's opened without
mentioning the Byzantine Catholic churches at all. All four now carry one
sentence, and a test fails if any of them moves without the others.
## 1.1.1
### Fixed
- The npm package's files are reachable through its exports map. A bundler
asked for `typikon/web/typikon_bg.wasm` was told no such path is exported,
so a web app that wants to hand the WebAssembly to `init()` as an asset had
to reach around the package into `node_modules`. The documented call, `await
init()` with no argument, was never affected.
### Added
- `tests/parity.sh`: every binding asked the same twelve days and compared
field by field against the command line. The days are the ones where the
bindings could plausibly differ, and the surfaces are the command line, the
Python wheel, Node by import and by require, TypeScript under `--strict`, a
real browser, Deno, Bun, the C ABI and LuaJIT over it. A surface whose
toolchain is absent is named as skipped rather than silently counted.
`--published` runs the same checks against PyPI and npm instead of the
checkout.
### Changed
- The README no longer explains how the project tests or releases itself. That
belongs to whoever works on it, and it is in `docs/` where they will look;
a reader who came to find out what a day of the Great Fast permits does not
need it.
- A release runs what a push runs. The release workflow had been gated on
`cargo test` alone, so the C ABI, the Lua binding, the Python parity check
and the README examples were checked on the branch that led to a release but
not on the release itself. A version cannot be reused on either registry, so
the gate belongs before the upload.
## 1.1.0
New ways in, and no change to any day: nothing here moves a feast, a fast
Generated
+1 -1
View File
@@ -404,7 +404,7 @@ checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca"
[[package]]
name = "typikon"
version = "1.1.0"
version = "1.2.0"
dependencies = [
"clap",
"js-sys",
+2 -2
View File
@@ -1,9 +1,9 @@
[package]
name = "typikon"
version = "1.1.0"
version = "1.2.0"
edition = "2021"
rust-version = "1.85"
description = "The Orthodox liturgical day: feasts, seasons and the fast, computed rather than fetched"
description = "The Orthodox liturgical day: feasts, seasons and the fast, computed rather than fetched. Twenty Orthodox jurisdictions and four Byzantine Catholic churches, across the Julian, Revised Julian and Gregorian reckonings."
license = "GPL-2.0-only"
repository = "https://git.pumpin.online/funkpower/typikon"
readme = "README.md"
+18 -8
View File
@@ -1,8 +1,8 @@
# typikon
The Orthodox liturgical day: feasts, seasons and the fast, computed rather
than fetched. The Byzantine Catholic churches are here too, on their own
calendars and, where the law has been sourced, under their own particular law.
than fetched. Twenty Orthodox jurisdictions and four Byzantine Catholic
churches, across the Julian, Revised Julian and Gregorian reckonings.
Everything derives from the paschalion and the fixed calendar, so it needs no
network, cannot go stale, and answers for any year you ask about. No API key,
@@ -277,6 +277,16 @@ $ typikon --format json --days 7 # for a bar, a widget, a script
$ typikon --format ics --days 365 > orthodox.ics
```
The calendar is thinned to the days worth marking: a subscription that fills
all 365 squares is one nobody keeps. `--every-day` is for the other kind of
reader, who wants the saint of each morning and does not mind a full year.
Either way the description carries the day's commemorations, the fast and its
reason, and where the day sits in the year.
```console
$ typikon -j ruthenian --days 467 --ics --every-day > byzantine.ics
```
Delimited output, for a spreadsheet or a pipeline. RFC 4180 quoting, one header
row, one row per day:
@@ -309,6 +319,11 @@ $ typikon --year 2027 -j goarch
…
```
Outside the Triodion and the Pentecostarion, whose Sundays carry names, `week`
says where the day falls in the count from Pentecost: `the 32nd Sunday after
Pentecost`, or `the 32nd week after Pentecost` on the days between. It is a
column in the delimited formats and a line in the single-day view.
Every day of vigil rank or above carries the mark its books print beside it:
⊕ for a great feast, ✚ for a vigil, ☩ for a polyeleos. It is the `sign`
field in the JSON and a column in the delimited formats.
@@ -332,6 +347,7 @@ $ typikon -j rocor --date 2026-03-18 --json --indent 2
"churchDate": "5 March",
"season": "Great Fast",
"cycle": null,
"week": null,
"feast": null,
"rank": null,
"sign": null,
@@ -555,12 +571,6 @@ widgets for Hyprland (Quickshell), waybar and eww, all reading the JSON above.
![The menologion widget](https://git.pumpin.online/funkpower/menologion/raw/branch/main/docs/nativity-fast.png)
## Releasing
`main` is always releasable; a `vX.Y.Z` tag on it builds the wheels and publishes
to PyPI. [docs/releasing.md](https://git.pumpin.online/funkpower/typikon/src/branch/main/docs/releasing.md) has the workflow, and what has to
be set up before the first one.
## Licence
GPL-2.0-only. The source for any published release is the source distribution
+19
View File
@@ -166,6 +166,25 @@ $ /tmp/v/bin/python -c 'import typikon, datetime; print(typikon.today())'
Installing from the sdist with `--no-binary` is the one that catches a missing
file, because it builds the crate from exactly what PyPI would hand someone.
### Every binding agrees
`tests/parity.sh` asks every binding for the same twelve days and compares all
twenty-two fields against what the command line says. It runs in CI on every
push and again in the release job before anything is uploaded.
```console
$ tests/parity.sh # against this checkout
$ tests/parity.sh --published # against what is on PyPI and npm
```
Run the second one after a release. It is the only check that exercises the
artefacts people will actually install rather than the ones the build produced.
A surface whose toolchain is missing is skipped by name, and the script refuses
to report a pass if fewer than three ran, so a container with nothing installed
cannot look like a green run. Everything it wants: `python3` with `venv`, `node`
and `npm`, `cc`, `luajit`, `chromium`, and optionally `deno` and `bun`.
For the npm package:
```console
+4 -1
View File
@@ -21,13 +21,16 @@ tradition title commemorations fast fastLabel emoji reason obligation binds
pascha daysToPascha julianOffset
```
`week` was added in 1.2.0.
`fastLabel`, `emoji` and `reason` are **presentation**: the fields are always
there, and their wording is not stable. Key on `fast`, `season`, `rank`,
`obligation` and `binds`.
Adding a field is a **minor** change, so read the object by key and ignore what
you do not recognise. `season`, `cycle`, `feast`, `rank`, `sign` and
`obligation` are null on ordinary days.
`obligation` are null on ordinary days, and `week` is null through the Triodion
and the Pentecostarion.
Two semantics worth stating because the names do not carry them:
+2 -1
View File
@@ -40,6 +40,7 @@ const char *typikon_day_emoji(const typikon_day *day);
const char *typikon_day_reason(const typikon_day *day);
const char *typikon_day_season(const typikon_day *day);
const char *typikon_day_cycle(const typikon_day *day);
const char *typikon_day_week(const typikon_day *day);
const char *typikon_day_feast(const typikon_day *day);
const char *typikon_day_rank(const typikon_day *day);
const char *typikon_day_sign(const typikon_day *day);
@@ -79,7 +80,7 @@ end
local FIELDS = {
"iso", "weekday", "jurisdiction", "calendar", "tradition", "church_date",
"title", "fast", "fast_label", "emoji", "reason",
"season", "cycle", "feast", "rank", "sign", "obligation", "binds",
"season", "cycle", "week", "feast", "rank", "sign", "obligation", "binds",
}
-- Copy the day into a plain Lua table and free it. The C day owns its strings
+1
View File
@@ -108,6 +108,7 @@ const char *typikon_day_reason(const typikon_day *day); /* why the day fas
/* NULL where the day has no such thing, which is not an error. */
const char *typikon_day_season(const typikon_day *day); /* NULL in ordinary time */
const char *typikon_day_cycle(const typikon_day *day); /* NULL outside the movable cycle */
const char *typikon_day_week(const typikon_day *day); /* NULL outside the count from Pentecost */
const char *typikon_day_feast(const typikon_day *day); /* NULL if the day has none */
const char *typikon_day_rank(const typikon_day *day); /* NULL if the day has no feast */
const char *typikon_day_sign(const typikon_day *day); /* the mark the books print, else NULL */
+4 -1
View File
@@ -1,7 +1,10 @@
# typikon
The Orthodox liturgical day: feasts, seasons and the fast, computed rather
than fetched. No network, no data files, no service to be up.
than fetched. Twenty Orthodox jurisdictions and four Byzantine Catholic
churches, across the Julian, Revised Julian and Gregorian reckonings.
No network, no data files, no service to be up.
```sh
npm install typikon
+3 -1
View File
@@ -1,7 +1,7 @@
{
"name": "typikon",
"version": "@VERSION@",
"description": "The Orthodox liturgical day: feasts, seasons and the fast, computed rather than fetched",
"description": "The Orthodox liturgical day: feasts, seasons and the fast, computed rather than fetched. Twenty Orthodox jurisdictions and four Byzantine Catholic churches, across the Julian, Revised Julian and Gregorian reckonings.",
"license": "GPL-2.0-only",
"homepage": "https://git.pumpin.online/funkpower/typikon",
"repository": {
@@ -38,6 +38,8 @@
"types": "./web/typikon.d.ts",
"default": "./web/typikon.js"
},
"./node/*": "./node/*",
"./web/*": "./web/*",
"./package.json": "./package.json"
},
"files": [
+1 -1
View File
@@ -4,7 +4,7 @@ build-backend = "maturin"
[project]
name = "typikon"
description = "The Orthodox liturgical day: feasts, seasons and the fast, computed rather than fetched"
description = "The Orthodox liturgical day: feasts, seasons and the fast, computed rather than fetched. Twenty Orthodox jurisdictions and four Byzantine Catholic churches, across the Julian, Revised Julian and Gregorian reckonings."
readme = "README.md"
license = "GPL-2.0-only"
license-files = ["LICENSE"]
+2
View File
@@ -24,6 +24,8 @@ class Day:
@property
def cycle(self) -> str | None: ...
@property
def week(self) -> str | None: ...
@property
def feast(self) -> str | None: ...
@property
def rank(self) -> str | None: ...
+3
View File
@@ -171,6 +171,7 @@ pub struct typikon_day {
reason: CString,
season: Option<CString>,
cycle: Option<CString>,
week: Option<CString>,
feast: Option<CString>,
rank: Option<CString>,
sign: Option<CString>,
@@ -223,6 +224,7 @@ fn build(
reason: cs(&inner.reason),
season: inner.season.map(|s| cs(s.name())),
cycle: inner.cycle.as_deref().map(&cs),
week: inner.week.as_deref().map(&cs),
feast: inner.feast.as_deref().map(&cs),
rank: inner.rank.map(|r| cs(r.key())),
sign: inner.rank.map(|r| cs(r.sign())),
@@ -326,6 +328,7 @@ accessor!(typikon_day_emoji, "The glyph for the fasting level.", |d| Some(&d.emo
accessor!(typikon_day_reason, "Why the day fasts as it does.", |d| Some(&d.reason));
accessor!(typikon_day_season, "The season, or NULL in ordinary time.", |d| d.season.as_ref());
accessor!(typikon_day_cycle, "The place in the movable cycle, or NULL outside it.", |d| d.cycle.as_ref());
accessor!(typikon_day_week, "The count of weeks from Pentecost, or NULL outside it.", |d| d.week.as_ref());
accessor!(typikon_day_feast, "The feast, or NULL if the day has none.", |d| d.feast.as_ref());
accessor!(typikon_day_rank, "The rank of the feast, or NULL if the day has none.", |d| d.rank.as_ref());
accessor!(typikon_day_sign, "The mark the books print beside a day of this rank, or NULL.", |d| d.sign.as_ref());
+18 -1
View File
@@ -11,7 +11,7 @@ use crate::calendars::{Date, Weekday, MONTHS};
use crate::fasting::{Fast, Level, Obligation};
use crate::jurisdictions::Jurisdiction;
use crate::menologion::{self, Menologion, Rank};
use crate::paschalion::{movable_cycle, Movables};
use crate::paschalion::{movable_cycle, week_after_pentecost_label, Movables};
use crate::rules::{self, Context};
use crate::seasons::season_for;
@@ -25,6 +25,10 @@ pub struct Day {
pub church_date: String,
pub season: Option<crate::seasons::Season>,
pub cycle: Option<String>,
/// Where the day falls in the count of weeks from Pentecost, worded: "the
/// 32nd Sunday after Pentecost". `None` through the Triodion and the
/// Pentecostarion, whose Sundays have names instead of numbers.
pub week: Option<String>,
pub feast: Option<String>,
pub rank: Option<Rank>,
pub tradition: &'static str,
@@ -81,6 +85,7 @@ pub struct DayJson<'a> {
pub church_date: &'a str,
pub season: Option<&'a str>,
pub cycle: Option<&'a str>,
pub week: Option<&'a str>,
pub feast: Option<&'a str>,
pub rank: Option<&'a str>,
/// The mark the books print beside a day of this rank.
@@ -109,6 +114,7 @@ impl Day {
church_date: &self.church_date,
season: self.season.map(|s| s.name()),
cycle: self.cycle.as_deref(),
week: self.week.as_deref(),
feast: self.feast.as_deref(),
rank: self.rank.map(|r| r.key()),
sign: self.rank.map(|r| r.sign()),
@@ -182,6 +188,16 @@ pub fn describe_with(date: Date, jur: &'static Jurisdiction, men: &Menologion) -
(None, fixed) => fixed.clone(),
};
// The Sundays counted from the Exaltation, the Nativity and the Theophany
// join the day rather than naming it: the books print the saint and the
// Sunday both, and the saint keeps the title.
if let Some(sunday) = menologion::fixed_cycle_sunday((fm, fd), date.weekday()) {
let sunday = sunday.to_string();
if !commemorations.contains(&sunday) && feast.as_deref() != Some(sunday.as_str()) {
commemorations.insert(1.min(commemorations.len()), sunday);
}
}
let ctx = Context {
civil: date,
fixed: (fm, fd),
@@ -228,6 +244,7 @@ pub fn describe_with(date: Date, jur: &'static Jurisdiction, men: &Menologion) -
church_date: format!("{} {}", fd, MONTHS[(fm - 1) as usize]),
season,
cycle: entry.cycle,
week: week_after_pentecost_label(date, date.weekday(), jur.paschalion),
feast,
rank,
tradition: jur.tradition.key(),
+2 -1
View File
@@ -8,7 +8,7 @@ use crate::day::Day;
pub const COLUMNS: &[&str] = &[
"date", "weekday", "jurisdiction", "calendar", "church_date", "season",
"cycle", "feast", "rank", "sign", "tradition", "title", "fast", "fast_label", "emoji",
"cycle", "week", "feast", "rank", "sign", "tradition", "title", "fast", "fast_label", "emoji",
"reason", "obligation", "binds", "pascha", "days_to_pascha",
"julian_offset", "commemorations",
];
@@ -33,6 +33,7 @@ fn cell(day: &Day, column: &str) -> String {
"church_date" => day.church_date.clone(),
"season" => day.season.map(|s| s.name()).unwrap_or("").to_string(),
"cycle" => day.cycle.clone().unwrap_or_default(),
"week" => day.week.clone().unwrap_or_default(),
"feast" => day.feast.clone().unwrap_or_default(),
"rank" => day.rank.map(|r| r.key()).unwrap_or("").to_string(),
"sign" => day.rank.map(|r| r.sign()).unwrap_or("").to_string(),
+76 -31
View File
@@ -1,14 +1,29 @@
//! iCalendar, so the calendar can live where the rest of your year does.
//!
//! Each day becomes one all-day event. The summary is the feast or the
//! principal commemoration; the description carries the fast, the season and
//! the rest of the day's commemorations. Days with nothing to say, no feast and
//! no fast, are left out, because a subscribed calendar that marks all 365 days
//! is one nobody keeps.
//! principal commemoration; the description lists every commemoration, then the
//! fast, then where the day sits in the year.
//!
//! By default the days with nothing to say, no feast and no fast, are left out,
//! because a subscribed calendar that marks all 365 days is one nobody keeps.
//! `Ics::every_day` is for the other kind of reader, who wants the saint of
//! each morning and does not mind a full calendar: it gives every day an event,
//! ferial ones included.
use crate::day::Day;
use crate::fasting::{Level, Obligation};
/// How to write the calendar.
pub struct Ics<'a> {
/// What a client shows the subscription as.
pub name: &'a str,
/// `DTSTAMP`, as `YYYYMMDDTHHMMSSZ`.
pub stamp: &'a str,
/// One event for every day, rather than only the days carrying a feast or
/// a fast.
pub every_day: bool,
}
/// A count of octets, which is what RFC 5545 measures content lines in.
///
/// A newtype because the Python this was ported from folded on *characters*
@@ -61,54 +76,75 @@ fn fold(line: &str) -> String {
out.join("\r\n")
}
/// The calendar as it has always been written: a subscription, thinned to the
/// days worth marking.
pub fn to_ics(days: &[Day], name: &str, stamp: &str) -> String {
to_ics_with(days, &Ics { name, stamp, every_day: false })
}
pub fn to_ics_with(days: &[Day], opts: &Ics<'_>) -> String {
let mut lines: Vec<String> = vec![
"BEGIN:VCALENDAR".into(),
"VERSION:2.0".into(),
"PRODID:-//typikon//EN".into(),
"CALSCALE:GREGORIAN".into(),
"METHOD:PUBLISH".into(),
format!("X-WR-CALNAME:{}", escape(name)),
format!("X-WR-CALNAME:{}", escape(opts.name)),
];
for d in days {
if d.feast.is_none() && d.fast == Level::None {
if !opts.every_day && d.feast.is_none() && d.fast == Level::None {
continue;
}
let start = d.date.iso().replace('-', "");
let end = (d.date + 1).iso().replace('-', "");
let summary = if d.emoji.is_empty() {
d.title().to_string()
} else {
format!("{} {}", d.emoji, d.title())
};
// The glyph for the fast and the mark for the rank, in the order the
// text view prints them, so one is scannable down a month view and the
// other says at a glance whether the day is kept.
let sign = d.rank.map(|r| r.sign()).unwrap_or("");
let summary = [d.emoji, sign, d.title()]
.iter()
.filter(|p| !p.is_empty())
.copied()
.collect::<Vec<_>>()
.join(" ");
// Paragraphs, joined by a blank line. A calendar client shows this in
// a popover a few lines tall, and the saints are what the reader came
// for, so they go first.
let mut body: Vec<String> = Vec::new();
if d.fast != Level::None {
body.push(if d.reason.is_empty() {
format!("Fast: {}", d.fast_label)
} else {
format!("Fast: {} ({})", d.fast_label, d.reason)
});
if !d.commemorations.is_empty() {
body.push(
d.commemorations
.iter()
.map(|c| format!("\u{2022} {c}"))
.collect::<Vec<_>>()
.join("\n"),
);
}
let mut fast = if d.reason.is_empty() {
format!("Fast: {}", d.fast_label)
} else {
format!("Fast: {} ({})", d.fast_label, d.reason)
};
if d.obligation == Some(Obligation::Obligatory) {
body.push("Obligatory.".into());
fast.push_str("\nObligatory.");
}
body.push(fast);
let mut where_ = Vec::new();
if let Some(w) = &d.week {
where_.push(capitalised(w));
}
if let Some(s) = d.season {
body.push(format!("Season: {}", s.name()));
where_.push(format!("Season: {}", s.name()));
}
if let Some(c) = &d.cycle {
let mut chars = c.chars();
let capped = match chars.next() {
Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
};
body.push(capped);
}
body.push(format!("Church date: {}", d.church_date));
for c in &d.commemorations {
body.push(c.clone());
where_.push(capitalised(c));
}
where_.push(format!("Church date: {}", d.church_date));
body.push(where_.join("\n"));
lines.extend([
"BEGIN:VEVENT".into(),
@@ -123,11 +159,11 @@ pub fn to_ics(days: &[Day], name: &str, stamp: &str) -> String {
d.tradition,
if d.shown_at_typikon { "typikon" } else { "particular" }
),
format!("DTSTAMP:{stamp}"),
format!("DTSTAMP:{}", opts.stamp),
format!("DTSTART;VALUE=DATE:{start}"),
format!("DTEND;VALUE=DATE:{end}"),
fold(&format!("SUMMARY:{}", escape(&summary))),
fold(&format!("DESCRIPTION:{}", escape(&body.join("\n")))),
fold(&format!("DESCRIPTION:{}", escape(&body.join("\n\n")))),
"TRANSP:TRANSPARENT".into(),
"END:VEVENT".into(),
]);
@@ -138,3 +174,12 @@ pub fn to_ics(days: &[Day], name: &str, stamp: &str) -> String {
s.push_str("\r\n");
s
}
/// A phrase written to sit inside a sentence, promoted to the start of a line.
fn capitalised(phrase: &str) -> String {
let mut chars = phrase.chars();
match chars.next() {
Some(f) => f.to_uppercase().collect::<String>() + chars.as_str(),
None => String::new(),
}
}
+1 -1
View File
@@ -3,5 +3,5 @@ pub mod ics;
pub mod json;
pub use csv::to_delimited;
pub use ics::to_ics;
pub use ics::{to_ics, to_ics_with, Ics};
pub use json::to_json;
+15 -2
View File
@@ -5,7 +5,7 @@ use clap::{Parser, ValueEnum};
use typikon::calendars::Date;
use typikon::config::{self, Source};
use typikon::day::{week, year_of, Day};
use typikon::export::{to_delimited, to_ics, to_json};
use typikon::export::{to_delimited, to_ics_with, to_json, Ics};
use typikon::jurisdictions::{self, Jurisdiction, CALENDARS, JURISDICTIONS};
use typikon::menaia;
use typikon::rules;
@@ -67,6 +67,11 @@ struct Args {
#[arg(long, conflicts_with = "format")]
ics: bool,
/// Give every day an event in ics, ferias included, rather than only the
/// days carrying a feast or a fast
#[arg(long)]
every_day: bool,
/// Leave the glyphs out, for a terminal or a bar without them
#[arg(long)]
no_emoji: bool,
@@ -222,6 +227,9 @@ fn print_days(days: &[Day], jur: &Jurisdiction, source: Source, verbose: bool) {
} else {
println!(" {} {sign}{}", d.emoji, d.title());
}
if let Some(w) = &d.week {
println!(" {w}");
}
if let Some(c) = &d.cycle {
println!(" {c}");
}
@@ -443,7 +451,12 @@ fn run() -> Result<i32, String> {
return Ok(0);
}
Format::Ics => {
print!("{}", to_ics(&days, &format!("{} \u{2014} Typikon", jur.name), &stamp()));
let opts = Ics {
name: &format!("{} \u{2014} Typikon", jur.name),
stamp: &stamp(),
every_day: args.every_day,
};
print!("{}", to_ics_with(&days, &opts));
return Ok(0);
}
Format::Csv | Format::Tsv => {
+48 -2
View File
@@ -14,7 +14,7 @@ use std::collections::BTreeMap;
use serde::Deserialize;
use crate::calendars::Date;
use crate::calendars::{Date, Weekday};
use crate::jurisdictions::Tradition;
use crate::paschalion::Movables;
@@ -212,7 +212,7 @@ pub fn for_jurisdiction(tradition: Tradition, menaia: &[&str]) -> Menologion {
/// The movable feasts, named by their offset from Pascha. These outrank
/// whatever the fixed calendar holds for the day.
pub fn movable_feast_for(civil: Date, mv: &Movables) -> Option<(&'static str, Option<Rank>)> {
let table: [(Date, &'static str, Option<Rank>); 24] = [
let table: [(Date, &'static str, Option<Rank>); 27] = [
(mv.pascha, "The Radiant and Life-giving Resurrection of our Lord \u{2014} Holy Pascha", Some(Rank::Great)),
(mv.palm_sunday, "The Entry of our Lord into Jerusalem", Some(Rank::Great)),
(mv.ascension, "The Ascension of our Lord, God and Saviour Jesus Christ", Some(Rank::Great)),
@@ -223,6 +223,9 @@ pub fn movable_feast_for(civil: Date, mv: &Movables) -> Option<(&'static str, Op
(mv.holy_saturday, "Great and Holy Saturday", Some(Rank::Vigil)),
(mv.thomas_sunday, "Thomas Sunday \u{2014} the Antipascha", Some(Rank::Polyeleos)),
(mv.myrrhbearers, "The Sunday of the Holy Myrrh-bearing Women", Some(Rank::Polyeleos)),
(mv.paralytic, "The Sunday of the Paralytic", Some(Rank::Polyeleos)),
(mv.samaritan_woman, "The Sunday of the Samaritan Woman", Some(Rank::Polyeleos)),
(mv.blind_man, "The Sunday of the Blind Man", Some(Rank::Polyeleos)),
(mv.midfeast, "The Midfeast of Pentecost", Some(Rank::Polyeleos)),
(mv.all_saints, "The Sunday of All Saints", Some(Rank::Polyeleos)),
(mv.publican_pharisee, "The Sunday of the Publican and the Pharisee", None),
@@ -245,3 +248,46 @@ pub fn movable_feast_for(civil: Date, mv: &Movables) -> Option<(&'static str, Op
.find(|(d, _, _)| *d == civil)
.map(|(_, title, rank)| (*title, *rank))
}
/// The Sundays reckoned from a fixed feast rather than from Pascha.
///
/// Six of them, hung off the Exaltation, the Nativity and the Theophany. They
/// are named by the **ecclesiastical** date, so one table serves the old
/// calendar and the new alike, and they are found by the civil weekday,
/// because a Sunday is a Sunday in both reckonings.
///
/// These are commemorations, not feasts: they carry no rank and never displace
/// the saint of the day. The books print both, and on 26 December the Synaxis
/// of the Theotokos still names the day.
///
/// Three of the windows are shorter than a week and so can miss their Sunday
/// altogether:
///
/// - The Nativity on a Sunday leaves 26–31 December without one. The Typikon
/// settles this: the Sunday after the Nativity is kept on 26 December, and
/// that is the one day here that is not a Sunday.
/// - 1 January on a Sunday leaves 2–5 January without one, and the Sunday
/// before the Theophany is kept on 1 January, with the Circumcision.
/// - The Theophany itself on a Sunday, and the Exaltation on a Sunday, leave
/// their windows empty with nowhere agreed to put what belongs in them.
/// Those two years go unmarked: an answer this calendar cannot defend is
/// worse than none.
pub fn fixed_cycle_sunday(fixed: (u32, u32), weekday: Weekday) -> Option<&'static str> {
let sunday = weekday == Weekday::Sunday;
let title = match fixed {
(9, 8..=13) if sunday => "The Sunday before the Exaltation",
(9, 15..=21) if sunday => "The Sunday after the Exaltation",
(12, 11..=17) if sunday => "The Sunday of the Holy Forefathers",
(12, 18..=24) if sunday => "The Sunday before the Nativity \u{2014} the Holy Fathers",
(12, 26..=31) if sunday => "The Sunday after the Nativity",
// 26 December falls on a Monday only in a year whose Nativity was a
// Sunday, which is exactly the year the window above is empty.
(12, 26) if weekday == Weekday::Monday => "The Sunday after the Nativity",
// 2 to 5 January is the window. 1 January is a Sunday only in a year
// where that window holds none, so the two fold into one range.
(1, 1..=5) if sunday => "The Sunday before the Theophany",
(1, 7..=13) if sunday => "The Sunday after the Theophany",
_ => return None,
};
Some(title)
}
+59 -1
View File
@@ -9,7 +9,7 @@
//! agree in some years, 2025 falls on 20 April by both, and can diverge by as
//! much as five weeks.
use crate::calendars::{Date, JulianDate};
use crate::calendars::{Date, JulianDate, Weekday, MAX_YEAR, MIN_YEAR};
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Paschalion {
@@ -95,7 +95,10 @@ pub struct Movables {
pub bright_week_end: Date,
pub thomas_sunday: Date,
pub myrrhbearers: Date,
pub paralytic: Date,
pub midfeast: Date,
pub samaritan_woman: Date,
pub blind_man: Date,
pub ascension: Date,
pub fathers_first_council: Date,
pub pentecost: Date,
@@ -131,7 +134,10 @@ pub fn movable_cycle(year: i32, p: Paschalion) -> Movables {
bright_week_end: d + 6,
thomas_sunday: d + 7,
myrrhbearers: d + 14,
paralytic: d + 21,
midfeast: d + 24,
samaritan_woman: d + 28,
blind_man: d + 35,
ascension: d + 39,
fathers_first_council: d + 42,
pentecost: d + 49,
@@ -140,3 +146,55 @@ pub fn movable_cycle(year: i32, p: Paschalion) -> Movables {
apostles_start: d + 57,
}
}
/// Where a day falls in the count of weeks from Pentecost, which is how the
/// books head the long ordinary stretch of the year: "the 32nd Sunday after
/// Pentecost".
///
/// The count runs from the Monday after Pentecost to the eve of the next
/// Sunday of the Publican and the Pharisee, and it is `None` outside that,
/// through the Triodion and the Pentecostarion, where the Sundays have names
/// of their own instead of a number.
///
/// The governing Pentecost is not always the one in this day's civil year: a
/// day in January is counted from the Pentecost of the year before. That is
/// the one place this differs from `days_to_pascha`, which is always reckoned
/// against its own year's Pascha.
pub fn week_after_pentecost(date: Date, p: Paschalion) -> Option<i32> {
let year = date.year();
// A day at either end of the range this calendar answers for would need a
// Pascha outside it. One week unlabelled beats a panic.
if !(MIN_YEAR + 1..=MAX_YEAR - 1).contains(&year) {
return None;
}
let this = movable_cycle(year, p);
let (pentecost, next_publican) = if date > this.pentecost {
(this.pentecost, movable_cycle(year + 1, p).publican_pharisee)
} else {
(movable_cycle(year - 1, p).pentecost, this.publican_pharisee)
};
if date <= pentecost || date >= next_publican {
return None;
}
Some((date - pentecost + 6) / 7)
}
/// The same count, worded. Lowercase and article-first, like `cycle`, because
/// both are phrases a front end drops into a sentence of its own.
pub fn week_after_pentecost_label(date: Date, weekday: Weekday, p: Paschalion) -> Option<String> {
let n = week_after_pentecost(date, p)?;
let unit = if weekday == Weekday::Sunday { "Sunday" } else { "week" };
Some(format!("the {} {unit} after Pentecost", ordinal(n)))
}
/// English ordinals, for the one place this calendar has to count out loud.
fn ordinal(n: i32) -> String {
let suffix = match (n % 100, n % 10) {
(11..=13, _) => "th",
(_, 1) => "st",
(_, 2) => "nd",
(_, 3) => "rd",
_ => "th",
};
format!("{n}{suffix}")
}
+6
View File
@@ -106,6 +106,11 @@ impl PyDay {
self.inner.cycle.as_deref()
}
#[getter]
fn week(&self) -> Option<&str> {
self.inner.week.as_deref()
}
#[getter]
fn feast(&self) -> Option<&str> {
self.inner.feast.as_deref()
@@ -203,6 +208,7 @@ impl PyDay {
d.set_item("church_date", j.church_date)?;
d.set_item("season", j.season)?;
d.set_item("cycle", j.cycle)?;
d.set_item("week", j.week)?;
d.set_item("feast", j.feast)?;
d.set_item("rank", j.rank)?;
d.set_item("sign", j.sign)?;
+2
View File
@@ -50,6 +50,8 @@ export interface Day {
season: string | null;
/** The place in the movable cycle, or null outside it. */
cycle: string | null;
/** "the 32nd Sunday after Pentecost", or null outside that count. */
week: string | null;
feast: string | null;
/** The rank of the feast, or null where there is none. */
rank: string | null;
+103
View File
@@ -0,0 +1,103 @@
//! The packaging metadata, which lives in three files and is published to two
//! registries.
//!
//! `Cargo.toml` describes the crate, `pyproject.toml` is what maturin puts on
//! PyPI, and `npm/package.json.in` is what npm shows. Nothing makes them agree
//! and nothing notices when they stop: a description edited in one of the three
//! reaches one registry and not the other, and the wrong one is then frozen
//! into a release, because neither registry lets published metadata be edited.
//! That has happened once already.
//!
//! The two READMEs open with the same sentence, because that paragraph is the
//! first thing shown on both registry pages and is what most people will read
//! instead of the description field.
use std::fs;
/// The value of a `key = "…"` line, from the first section that has one.
fn toml_string(path: &str, key: &str) -> String {
let text = fs::read_to_string(path).unwrap_or_else(|e| panic!("{path}: {e}"));
for line in text.lines() {
let line = line.trim();
let Some(rest) = line.strip_prefix(key) else { continue };
let Some(rest) = rest.trim_start().strip_prefix('=') else { continue };
let rest = rest.trim();
if let Some(v) = rest.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
return v.to_string();
}
}
panic!("{path}: no `{key} = \"…\"` line");
}
/// The value of a `"key": "…"` line. Enough for a hand-written file with no
/// escapes in it, and the test below fails loudly rather than quietly if that
/// ever stops being true.
fn json_string(path: &str, key: &str) -> String {
let text = fs::read_to_string(path).unwrap_or_else(|e| panic!("{path}: {e}"));
let needle = format!("\"{key}\":");
for line in text.lines() {
let Some(rest) = line.trim().strip_prefix(&needle) else { continue };
let rest = rest.trim().trim_end_matches(',').trim();
if let Some(v) = rest.strip_prefix('"').and_then(|v| v.strip_suffix('"')) {
assert!(!v.contains('\\'), "{path}: {key} has escapes this reader cannot handle");
return v.to_string();
}
}
panic!("{path}: no `\"{key}\": \"…\"` line");
}
#[test]
fn the_three_descriptions_are_the_same_sentence() {
let cargo = toml_string("Cargo.toml", "description");
let pyproject = toml_string("pyproject.toml", "description");
let npm = json_string("npm/package.json.in", "description");
assert_eq!(
cargo, pyproject,
"Cargo.toml and pyproject.toml disagree; pyproject.toml is the one PyPI shows"
);
assert_eq!(
cargo, npm,
"Cargo.toml and npm/package.json.in disagree; the latter is the one npm shows"
);
}
#[test]
fn the_description_says_what_the_crate_is_called() {
// Cheap guard against a description edited into something that no longer
// describes this package at all.
let d = toml_string("Cargo.toml", "description");
assert!(d.len() > 40, "description is too short to be one: {d:?}");
assert!(!d.ends_with(' '), "description has a trailing space");
assert!(d.contains("Orthodox"), "description no longer mentions Orthodox: {d:?}");
}
/// The opening paragraph of a README, unwrapped to one line.
fn lede(path: &str) -> String {
let text = fs::read_to_string(path).unwrap_or_else(|e| panic!("{path}: {e}"));
let body = text
.split("\n\n")
.find(|p| !p.trim().is_empty() && !p.trim_start().starts_with('#'))
.unwrap_or_else(|| panic!("{path}: no opening paragraph"));
body.split_whitespace().collect::<Vec<_>>().join(" ")
}
#[test]
fn both_readmes_open_with_the_description() {
// A registry page leads with the README, not with the description field,
// so the sentence a reader actually meets is this one. npm's README is a
// separate file from the crate's and had gone its own way: it described
// the package without mentioning that it covers Byzantine Catholic
// churches at all.
let description = toml_string("Cargo.toml", "description");
assert_eq!(
lede("README.md"),
description,
"README.md does not open with the published description"
);
assert_eq!(
lede("npm/README.md"),
description,
"npm/README.md does not open with the published description"
);
}
+244
View File
@@ -0,0 +1,244 @@
#!/usr/bin/env bash
# Every binding, asked the same twelve days, compared field by field against
# what the command line says.
#
# tests/parity.sh # against what is in this checkout
# tests/parity.sh --published # against what is on PyPI and npm
#
# A surface whose toolchain is missing is skipped by name. A surface that runs
# and disagrees fails the script. tests/parity/README.md says why these twelve.
set -uo pipefail
root="$(cd "$(dirname "$0")/.." && pwd)"
cd "$root"
P=tests/parity
published=0
[ "${1:-}" = "--published" ] && published=1
work="$(mktemp -d)"
server=""
# By pid. A job spec does not survive a subshell, and a web server left holding
# the script's stdout is a suite that hangs rather than fails.
cleanup() {
[ -n "$server" ] && kill "$server" 2>/dev/null && wait "$server" 2>/dev/null
rm -rf "$work"
}
trap cleanup EXIT
pass=0 fail=0 skipped=()
note() { printf '\n\033[1m%s\033[0m\n' "$1"; }
skip() { skipped+=("$1: $2"); printf ' skip %s (%s)\n' "$1" "$2"; }
verify() { # name, path to that surface's json
if python3 "$P/compare.py" "$1" "$work/oracle.json" "$2"; then
pass=$((pass + 1))
else
fail=$((fail + 1))
fi
}
# Neither a config file nor a fetched menaion may reach any surface, or this
# measures the machine rather than the code.
#
# Empty directories, not missing ones. Pointing these at a path that does not
# exist isolates typikon and breaks everything else that keeps state under
# them: a browser cannot build a profile and its crash handler will not start
# without somewhere to write.
export XDG_CONFIG_HOME="$work/xdg/config" XDG_DATA_HOME="$work/xdg/data"
mkdir -p "$XDG_CONFIG_HOME" "$XDG_DATA_HOME"
# ── the oracle ────────────────────────────────────────────────────────────
note "oracle"
cargo build --quiet --release || exit 1
python3 "$P/oracle.py" ./target/release/typikon "$P/probes.json" "$work/oracle.json" || exit 1
# The C probe carries its own copy of the list, because a binding whose point
# is to spare its callers a JSON parser should not need one to be tested.
python3 - "$P/probes.json" "$P/probe.c" <<'PY' || exit 1
import json, re, sys
probes = json.load(open(sys.argv[1]))
src = open(sys.argv[2]).read()
found = re.findall(r"\{(\d+),(\d+),(\d+),\"([a-z-]+)\",(-?\d+)\}", src.replace(" ", ""))
mine = [(f"{int(y):04d}-{int(m):02d}-{int(d):02d}", j, t == "1") for y, m, d, j, t in found]
want = [(d, j, bool(t)) for d, j, t in probes]
if mine != want:
sys.exit(f"tests/parity/probe.c has drifted from probes.json:\n c {mine}\n json {want}")
PY
# ── python ────────────────────────────────────────────────────────────────
note "python"
py="$work/venv/bin/python"
if ! python3 -m venv "$work/venv" >"$work/py.log" 2>&1; then
skip python "no usable python3 -m venv"
elif [ "$published" = 1 ] && ! "$work/venv/bin/pip" install --quiet typikon >>"$work/py.log" 2>&1; then
skip python "typikon would not install from PyPI"
elif [ "$published" = 0 ] && ! {
"$work/venv/bin/pip" install --quiet maturin >>"$work/py.log" 2>&1 &&
"$work/venv/bin/maturin" build --release --out "$work/wheels" >>"$work/py.log" 2>&1 &&
"$work/venv/bin/pip" install --quiet --no-index --find-links "$work/wheels" typikon \
>>"$work/py.log" 2>&1
}; then
echo " FAIL python: the wheel would not build or install"
tail -12 "$work/py.log" | sed 's/^/ /'
fail=$((fail + 1))
else
"$py" "$P/probe.py" "$P/probes.json" "$work/python.json" \
&& verify "python" "$work/python.json"
# The stubs are part of what is published, so they are part of what is
# checked. --strict, because a stub that only passes loosely is not one.
if "$work/venv/bin/pip" install --quiet mypy >>"$work/py.log" 2>&1; then
if "$py" -m mypy --strict "$P/probe.py" >"$work/mypy.log" 2>&1; then
echo " ok python: mypy --strict"
else
echo " FAIL python: mypy --strict"
tail -8 "$work/mypy.log" | sed 's/^/ /'
fail=$((fail + 1))
fi
else
skip "python, mypy" "mypy would not install"
fi
fi
# ── javascript ────────────────────────────────────────────────────────────
note "javascript"
if ! command -v node >/dev/null; then
skip javascript "no node"
else
js="$work/js"
mkdir -p "$js"
printf '{"name":"parity","private":true,"type":"module"}\n' > "$js/package.json"
cp "$P/probes.json" "$P/shape.mjs" "$P"/probe.{mjs,cjs,ts} "$js/"
mkdir -p "$js/web" && cp "$P"/web/{entry.mjs,index.html,extract.py} "$js/web/"
if [ "$published" = 1 ]; then
(cd "$js" && npm install --silent typikon >/dev/null 2>&1)
else
npm/build.sh >/dev/null 2>&1 && (cd "$js" && npm install --silent "$root/npm/dist" >/dev/null 2>&1)
fi
if [ ! -d "$js/node_modules/typikon" ]; then
skip javascript "the package would not build or install"
else
node "$js/probe.mjs" "$js/probes.json" "$work/node-esm.json" \
&& verify "node, import" "$work/node-esm.json"
node "$js/probe.cjs" "$js/probes.json" "$work/node-cjs.json" \
&& verify "node, require" "$work/node-cjs.json"
# TypeScript: compiled under --strict, then run.
if (cd "$js" && npm install --silent --no-save typescript@5 @types/node >/dev/null 2>&1); then
if (cd "$js" && ./node_modules/.bin/tsc --strict --target es2022 --module nodenext \
--moduleResolution nodenext --types node --outDir out probe.ts >/dev/null); then
node "$js/out/probe.js" "$js/probes.json" "$work/typescript.json" \
&& verify "typescript, tsc --strict then run" "$work/typescript.json"
else
echo " FAIL typescript: tsc --strict rejected the published types"; fail=$((fail + 1))
fi
else
skip typescript "typescript would not install"
fi
# The browser, which is the only place the web build is really exercised:
# a real fetch of the wasm, and no Node to fall back on.
chrome=""
for c in chromium chromium-browser google-chrome google-chrome-stable; do
command -v "$c" >/dev/null && { chrome="$c"; break; }
done
if [ -z "$chrome" ]; then
skip browser "no chromium"
elif ! (cd "$js" && npm install --silent --no-save esbuild >/dev/null 2>&1); then
skip browser "esbuild would not install"
else
if ! (cd "$js" && ./node_modules/.bin/esbuild web/entry.mjs --bundle \
--format=esm --platform=browser --loader:.wasm=file \
--outdir=served --log-level=error); then
echo " FAIL browser: the bundle would not build"; fail=$((fail + 1))
else
cp "$js/web/index.html" "$js/probes.json" "$js/served/"
# A port the kernel picks, so a leftover server from a previous run
# cannot quietly serve a stale bundle to this one.
port=$(python3 -c 'import socket; s=socket.socket(); s.bind(("127.0.0.1",0)); print(s.getsockname()[1]); s.close()')
python3 -m http.server "$port" --bind 127.0.0.1 \
--directory "$js/served" >/dev/null 2>&1 &
server=$!
for _ in $(seq 40); do
curl -sf -o /dev/null "http://127.0.0.1:$port/index.html" && break
sleep 0.25
done
# --user-data-dir because this script points XDG_CONFIG_HOME at
# nothing, to keep a real config file away from the surfaces under
# test, and a browser given nowhere to put a profile does not start.
# --disable-dev-shm-usage because a container's /dev/shm is too small.
# Bounded: a browser that never paints must fail the suite, not hang it.
timeout 90 "$chrome" --headless --disable-gpu --no-sandbox \
--no-first-run --disable-dev-shm-usage \
--user-data-dir="$work/chrome" \
--virtual-time-budget=20000 --dump-dom "http://127.0.0.1:$port/index.html" \
>"$work/dom.html" 2>"$work/chrome.log"
kill "$server" 2>/dev/null; wait "$server" 2>/dev/null; server=""
if python3 "$P/web/extract.py" "$work/dom.html" "$work/browser.json"; then
verify "browser, bare import of the web build" "$work/browser.json"
else
echo " FAIL browser"
tail -5 "$work/chrome.log" 2>/dev/null | sed 's/^/ /'
fail=$((fail + 1))
fi
fi
fi
for rt in deno bun; do
command -v "$rt" >/dev/null || { skip "$rt" "not installed"; continue; }
case "$rt" in
deno) (cd "$js" && deno run --quiet --allow-read --allow-write --allow-env \
probe.mjs probes.json "$work/deno.json") ;;
bun) (cd "$js" && bun run probe.mjs probes.json "$work/bun.json") ;;
esac && verify "$rt" "$work/$rt.json"
done
fi
fi
# ── the C ABI, and Lua over it ────────────────────────────────────────────
note "C and Lua"
if ! command -v cc >/dev/null; then
skip "C ABI" "no C compiler"
elif ! cargo build --quiet --release --features capi; then
echo " FAIL C ABI: the library would not build"; fail=$((fail + 1))
else
if cc -Wall -Wextra -Werror -Iinclude "$P/probe.c" \
-Ltarget/release -ltypikon -o "$work/c-probe" 2>"$work/cc.log"; then
LD_LIBRARY_PATH=target/release "$work/c-probe" "$work/c.json" \
&& verify "C ABI" "$work/c.json"
else
echo " FAIL C ABI: the probe would not compile"; sed 's/^/ /' "$work/cc.log"
fail=$((fail + 1))
fi
# The worked example has to keep working too.
if cc -Wall -Wextra -Werror -Iinclude examples/c/demo.c \
-Ltarget/release -ltypikon -o "$work/demo" 2>/dev/null \
&& LD_LIBRARY_PATH=target/release "$work/demo" rocor >/dev/null; then
echo " ok C ABI: examples/c/demo.c"
else
echo " FAIL C ABI: examples/c/demo.c"; fail=$((fail + 1))
fi
if ! command -v luajit >/dev/null; then
skip luajit "not installed"
else
TYPIKON_LIB=target/release/libtypikon.so TYPIKON_LUA=examples/lua \
luajit "$P/probe.lua" "$work/lua.json" && verify "luajit" "$work/lua.json"
TYPIKON_LIB=target/release/libtypikon.so \
luajit examples/lua/statusline.lua rocor >/dev/null \
&& echo " ok luajit: examples/lua/statusline.lua" \
|| { echo " FAIL luajit: examples/lua/statusline.lua"; fail=$((fail + 1)); }
fi
fi
# ── verdict ───────────────────────────────────────────────────────────────
note "verdict"
printf ' %d surfaces agree with the command line, %d disagree\n' "$pass" "$fail"
for s in "${skipped[@]:-}"; do [ -n "$s" ] && printf ' not run: %s\n' "$s"; done
# A run that skipped everything must not read as a pass.
if [ "$pass" -lt 3 ]; then
echo " too few surfaces ran to call this a check"
exit 1
fi
exit $(( fail > 0 ))
+14
View File
@@ -0,0 +1,14 @@
# Parity
Every binding answers the same question, so every binding has to give the same
answer. These probes ask each one for the same twelve days and compare all
twenty-two fields against what the command line says.
The probes are chosen for the places the bindings could plausibly disagree:
Pascha itself, the Nativity on both calendars, a Wednesday of the Great Fast
under Byzantine Catholic law and again at the Typikon, a weekday of the
Nativity Fast where Greek and Slavic usage part, the one Orthodox church on the
Gregorian Paschalion, and a day with no feast at all.
Run them with `tests/parity.sh`. Surfaces whose toolchain is absent are skipped
by name rather than silently passed.
+29
View File
@@ -0,0 +1,29 @@
"""One surface's answers against the oracle's.
A surface need not expose every field; it must not disagree about one it does.
"""
import json
import sys
name, oracle_path, got_path = sys.argv[1:4]
oracle = json.load(open(oracle_path))
got = json.load(open(got_path))
bad = []
for key in sorted(set(oracle) - set(got)):
bad.append(f"missing probe {key}")
for key in sorted(set(got) - set(oracle)):
bad.append(f"unexpected probe {key}")
for key in sorted(set(oracle) & set(got)):
for field, expected in sorted(oracle[key].items()):
if field in got[key] and got[key][field] != expected:
bad.append(f"{key} {field}: {got[key][field]!r} != {expected!r}")
fields = sorted({f for v in got.values() for f in v})
for line in bad[:20]:
print(f" {line}")
if len(bad) > 20:
print(f" ... and {len(bad) - 20} more")
print(f" {'ok ' if not bad else 'FAIL'} {name}: "
f"{len(got)} probes, {len(fields)} fields, {len(bad)} differences")
sys.exit(1 if bad else 0)
+35
View File
@@ -0,0 +1,35 @@
"""The command line's answer, which every other surface is measured against."""
import json
import os
import subprocess
import sys
FIELDS = [
"date", "weekday", "jurisdiction", "calendar", "churchDate", "season",
"cycle", "week", "feast", "rank", "sign", "tradition", "title", "commemorations",
"fast", "fastLabel", "emoji", "reason", "obligation", "binds", "pascha",
"daysToPascha", "julianOffset",
]
cli, probes_path, out_path = sys.argv[1:4]
# Neither a config file nor a fetched menaion may reach any surface, or the
# comparison measures the machine rather than the code. The caller has already
# pointed these at empty directories; this only refuses to run without them,
# because an oracle that quietly read the developer's own jurisdiction would
# make every surface agree about the wrong thing.
env = dict(os.environ)
for var in ("XDG_CONFIG_HOME", "XDG_DATA_HOME"):
if not env.get(var):
sys.exit(f"{var} must be set to an empty directory before reckoning the oracle")
out = {}
for date, jurisdiction, typikon in json.load(open(probes_path)):
args = [cli, "--date", date, "--jurisdiction", jurisdiction, "--json",
"--typikon" if typikon else "--no-typikon"]
day = json.loads(subprocess.run(args, capture_output=True, text=True,
env=env, check=True).stdout)
out[f"{date}|{jurisdiction}|{int(typikon)}"] = {k: day[k] for k in FIELDS}
json.dump(out, open(out_path, "w"), ensure_ascii=False)
print(f"oracle: {len(out)} probes, {len(FIELDS)} fields")
+99
View File
@@ -0,0 +1,99 @@
/* The C ABI, over the same probes, emitting the same JSON.
*
* The probe list is written out here rather than read from probes.json,
* because a JSON parser is exactly what this binding exists to spare its
* callers and it would be odd to need one to test it. tests/parity.sh checks
* the two lists have not drifted apart.
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <typikon.h>
static void esc(FILE *f, const char *s) {
fputc('"', f);
for (; *s; s++) {
if (*s == '"' || *s == '\\') fprintf(f, "\\%c", *s);
else if ((unsigned char)*s < 0x20) fprintf(f, "\\u%04x", *s);
else fputc(*s, f);
}
fputc('"', f);
}
static void field(FILE *f, const char *k, const char *v, int *first) {
if (!*first) fputc(',', f);
*first = 0;
esc(f, k); fputc(':', f);
if (v) esc(f, v); else fputs("null", f);
}
int main(int argc, char **argv) {
(void)argc;
FILE *f = fopen(argv[1], "w");
fputc('{', f);
int firstkey = 1;
/* date, jurisdiction, discipline: the same twelve as probes.json. */
struct { int y, m, d; const char *j; int t; } probes[] = {
{2026,4,12,"moscow",-1}, {2026,4,12,"goarch",-1}, {2026,1,7,"moscow",-1},
{2025,12,25,"old",-1}, {2026,3,4,"ruthenian",0}, {2026,3,4,"ruthenian",1},
{2025,12,9,"old",-1}, {2026,2,16,"oca",-1}, {2026,8,15,"antiochian",-1},
{2026,9,18,"finnish",-1},{2027,5,2,"serbian",-1}, {2026,6,28,"constantinople",-1},
};
for (size_t i = 0; i < sizeof probes / sizeof *probes; i++) {
int32_t jdn = typikon_jdn_from_ymd(probes[i].y, probes[i].m, probes[i].d);
int disc = probes[i].t < 0 ? 0 : probes[i].t; /* the CLI oracle passed --no-typikon */
typikon_day *day = typikon_describe_full(jdn, probes[i].j, NULL, disc);
if (!day) { fprintf(stderr, "%s\n", typikon_last_error()); return 1; }
char key[64];
snprintf(key, sizeof key, "%04d-%02d-%02d|%s|%d",
probes[i].y, probes[i].m, probes[i].d, probes[i].j,
probes[i].t == 1 ? 1 : 0);
if (!firstkey) fputc(',', f);
firstkey = 0;
esc(f, key); fputs(":{", f);
int first = 1;
field(f, "date", typikon_day_iso(day), &first);
field(f, "weekday", typikon_day_weekday(day), &first);
field(f, "jurisdiction",typikon_day_jurisdiction(day), &first);
field(f, "calendar", typikon_day_calendar(day), &first);
field(f, "churchDate", typikon_day_church_date(day), &first);
field(f, "season", typikon_day_season(day), &first);
field(f, "cycle", typikon_day_cycle(day), &first);
field(f, "week", typikon_day_week(day), &first);
field(f, "feast", typikon_day_feast(day), &first);
field(f, "rank", typikon_day_rank(day), &first);
field(f, "sign", typikon_day_sign(day), &first);
field(f, "tradition", typikon_day_tradition(day), &first);
field(f, "title", typikon_day_title(day), &first);
field(f, "fast", typikon_day_fast(day), &first);
field(f, "fastLabel", typikon_day_fast_label(day), &first);
field(f, "emoji", typikon_day_emoji(day), &first);
field(f, "reason", typikon_day_reason(day), &first);
field(f, "obligation", typikon_day_obligation(day), &first);
field(f, "binds", typikon_day_binds(day), &first);
fputs(",\"commemorations\":[", f);
for (uint32_t c = 0; c < typikon_day_commemoration_count(day); c++) {
if (c) fputc(',', f);
esc(f, typikon_day_commemoration(day, c));
}
fputc(']', f);
int32_t p = typikon_day_pascha(day);
int32_t py; uint32_t pm, pd;
typikon_ymd_from_jdn(p, &py, &pm, &pd);
char iso[16];
snprintf(iso, sizeof iso, "%04d-%02u-%02u", py, pm, pd);
fputs(",\"pascha\":", f); esc(f, iso);
fprintf(f, ",\"daysToPascha\":%d", typikon_day_days_to_pascha(day));
fprintf(f, ",\"julianOffset\":%d", typikon_day_julian_offset(day));
fputc('}', f);
typikon_day_free(day);
}
fputs("}\n", f);
fclose(f);
return 0;
}
+20
View File
@@ -0,0 +1,20 @@
// Node, by require. The other half of Node's world, and the half an exports
// map gets wrong.
const { readFileSync, writeFileSync } = require("node:fs");
const { describeIso } = require("typikon");
const [probesPath, outPath] = process.argv.slice(2);
const out = {};
for (const [date, jurisdiction, typikon] of JSON.parse(readFileSync(probesPath, "utf8"))) {
const d = describeIso(date, { jurisdiction, typikon });
out[`${date}|${jurisdiction}|${typikon ? 1 : 0}`] = {
date: d.date, weekday: d.weekday, jurisdiction: d.jurisdiction,
calendar: d.calendar, churchDate: d.churchDate, season: d.season,
cycle: d.cycle, week: d.week, feast: d.feast, rank: d.rank, sign: d.sign,
tradition: d.tradition, title: d.title, commemorations: d.commemorations,
fast: d.fast, fastLabel: d.fastLabel, emoji: d.emoji, reason: d.reason,
obligation: d.obligation, binds: d.binds, pascha: d.pascha,
daysToPascha: d.daysToPascha, julianOffset: d.julianOffset,
};
}
writeFileSync(outPath, JSON.stringify(out));
+59
View File
@@ -0,0 +1,59 @@
-- The binding under test is the one in examples/lua.
package.path = (os.getenv("TYPIKON_LUA") or "examples/lua") .. "/?.lua;" .. package.path
local typikon = require("typikon")
-- Minimal JSON writer: the binding hands back Lua tables, and the point is to
-- compare them with everything else, not to pull in a dependency.
local function esc(s)
return '"' .. s:gsub('[%c"\\]', function(c)
if c == '"' then return '\\"' elseif c == '\\' then return '\\\\' end
return string.format('\\u%04x', c:byte())
end) .. '"'
end
local function val(v)
if v == nil then return "null"
elseif type(v) == "number" then return tostring(math.floor(v))
elseif type(v) == "table" then
local parts = {}
for i = 1, #v do parts[i] = esc(v[i]) end
return "[" .. table.concat(parts, ",") .. "]"
else return esc(v) end
end
local probes = {
{2026,4,12,"moscow",false}, {2026,4,12,"goarch",false}, {2026,1,7,"moscow",false},
{2025,12,25,"old",false}, {2026,3,4,"ruthenian",false},{2026,3,4,"ruthenian",true},
{2025,12,9,"old",false}, {2026,2,16,"oca",false}, {2026,8,15,"antiochian",false},
{2026,9,18,"finnish",false},{2027,5,2,"serbian",false}, {2026,6,28,"constantinople",false},
}
local fields = {
{"date","iso"}, {"weekday","weekday"}, {"jurisdiction","jurisdiction"},
{"calendar","calendar"}, {"churchDate","church_date"}, {"season","season"},
{"cycle","cycle"}, {"week","week"}, {"feast","feast"}, {"rank","rank"}, {"sign","sign"},
{"tradition","tradition"}, {"title","title"}, {"fast","fast"},
{"fastLabel","fast_label"}, {"emoji","emoji"}, {"reason","reason"},
{"obligation","obligation"}, {"binds","binds"},
{"commemorations","commemorations"},
}
local out, firstkey = {}, true
for _, p in ipairs(probes) do
local jdn = assert(typikon.jdn(p[1], p[2], p[3]))
local day = assert(typikon.describe(jdn, { jurisdiction = p[4], typikon = p[5] }))
local parts = {}
for _, f in ipairs(fields) do
parts[#parts + 1] = esc(f[1]) .. ":" .. val(day[f[2]])
end
local py, pm, pd = typikon.ymd(day.pascha_jdn)
parts[#parts + 1] = esc("pascha") .. ":" .. esc(string.format("%04d-%02d-%02d", py, pm, pd))
parts[#parts + 1] = esc("daysToPascha") .. ":" .. tostring(day.days_to_pascha)
parts[#parts + 1] = esc("julianOffset") .. ":" .. tostring(day.julian_offset)
local key = string.format("%04d-%02d-%02d|%s|%d", p[1], p[2], p[3], p[4], p[5] and 1 or 0)
out[#out + 1] = (firstkey and "" or ",") .. esc(key) .. ":{" .. table.concat(parts, ",") .. "}"
firstkey = false
end
local f = assert(io.open(arg[1], "w"))
f:write("{" .. table.concat(out) .. "}\n")
f:close()
+12
View File
@@ -0,0 +1,12 @@
// Node, by import.
import { readFileSync, writeFileSync } from "node:fs";
import { describeIso } from "typikon";
import { shape } from "./shape.mjs";
const [probesPath, outPath] = process.argv.slice(2);
const out = {};
for (const [date, jurisdiction, typikon] of JSON.parse(readFileSync(probesPath, "utf8"))) {
out[`${date}|${jurisdiction}|${typikon ? 1 : 0}`] =
shape(describeIso(date, { jurisdiction, typikon }));
}
writeFileSync(outPath, JSON.stringify(out));
+38
View File
@@ -0,0 +1,38 @@
"""The Python bindings."""
import datetime
import json
import sys
import typikon
probes_path, out_path = sys.argv[1:3]
out = {}
for date, jurisdiction, tk in json.load(open(probes_path)):
y, m, d = map(int, date.split("-"))
day = typikon.describe(datetime.date(y, m, d), jurisdiction=jurisdiction, typikon=tk)
out[f"{date}|{jurisdiction}|{int(tk)}"] = {
"date": day.iso,
"weekday": day.weekday,
"jurisdiction": day.jurisdiction,
"calendar": day.calendar,
"churchDate": day.church_date,
"season": day.season,
"cycle": day.cycle,
"week": day.week,
"feast": day.feast,
"rank": day.rank,
"sign": day.sign,
"tradition": day.tradition,
"title": day.title,
"commemorations": day.commemorations,
"fast": day.fast,
"fastLabel": day.fast_label,
"emoji": day.emoji,
"reason": day.reason,
"obligation": day.obligation,
"binds": day.binds,
"pascha": day.pascha.isoformat(),
"daysToPascha": day.days_to_pascha,
"julianOffset": day.julian_offset,
}
json.dump(out, open(out_path, "w"), ensure_ascii=False)
+36
View File
@@ -0,0 +1,36 @@
// TypeScript, compiled under --strict and then run. Every field is annotated
// on the way out, so a type that has drifted from what the package returns is
// a compile error rather than a surprise at run time.
import { readFileSync, writeFileSync } from "node:fs";
import { describeIso, week, pascha, jurisdictions, type Day, type Options } from "typikon";
const [probesPath, outPath] = process.argv.slice(2);
type Probe = [string, string, boolean];
const out: Record<string, Record<string, unknown>> = {};
for (const [date, jurisdiction, typikon] of JSON.parse(readFileSync(probesPath, "utf8")) as Probe[]) {
const options: Options = { jurisdiction, typikon };
const d: Day = describeIso(date, options);
const season: string | null = d.season;
const commemorations: string[] = d.commemorations;
const daysToPascha: number = d.daysToPascha;
out[`${date}|${jurisdiction}|${typikon ? 1 : 0}`] = {
date: d.date, weekday: d.weekday, jurisdiction: d.jurisdiction,
calendar: d.calendar, churchDate: d.churchDate, season,
cycle: d.cycle, week: d.week, feast: d.feast, rank: d.rank, sign: d.sign,
tradition: d.tradition, title: d.title, commemorations,
fast: d.fast, fastLabel: d.fastLabel, emoji: d.emoji, reason: d.reason,
obligation: d.obligation, binds: d.binds, pascha: d.pascha,
daysToPascha, julianOffset: d.julianOffset,
};
}
// The rest of the surface, so nothing is typed only where it is called.
const seven: Day[] = week(new Date(2026, 3, 12), 7, { jurisdiction: "moscow" });
const p: Date = pascha(2027, "old");
const keys: string[] = jurisdictions().map((j) => j.key);
if (seven.length !== 7 || p.getFullYear() !== 2027 || keys.length < 20) {
throw new Error("the rest of the surface did not answer");
}
writeFileSync(outPath, JSON.stringify(out));
+14
View File
@@ -0,0 +1,14 @@
[
["2026-04-12", "moscow", false],
["2026-04-12", "goarch", false],
["2026-01-07", "moscow", false],
["2025-12-25", "old", false],
["2026-03-04", "ruthenian", false],
["2026-03-04", "ruthenian", true],
["2025-12-09", "old", false],
["2026-02-16", "oca", false],
["2026-08-15", "antiochian", false],
["2026-09-18", "finnish", false],
["2027-05-02", "serbian", false],
["2026-06-28", "constantinople", false]
]
+14
View File
@@ -0,0 +1,14 @@
// The fields, named once for every JavaScript surface. Written out rather than
// spread, so that a field the package stops exporting is a missing key here and
// not a silently absent one.
export function shape(d) {
return {
date: d.date, weekday: d.weekday, jurisdiction: d.jurisdiction,
calendar: d.calendar, churchDate: d.churchDate, season: d.season,
cycle: d.cycle, week: d.week, feast: d.feast, rank: d.rank, sign: d.sign,
tradition: d.tradition, title: d.title, commemorations: d.commemorations,
fast: d.fast, fastLabel: d.fastLabel, emoji: d.emoji, reason: d.reason,
obligation: d.obligation, binds: d.binds, pascha: d.pascha,
daysToPascha: d.daysToPascha, julianOffset: d.julianOffset,
};
}
+16
View File
@@ -0,0 +1,16 @@
// A bare "typikon" import under a browser-targeted bundler, which is what a
// web app actually writes. It has to resolve to the web build and not the Node
// one: the exports map is the only thing making that true.
import init, { describeIso } from "typikon";
import wasmUrl from "typikon/web/typikon_bg.wasm";
import { shape } from "../shape.mjs";
window.typikonProbe = async (probes) => {
await init({ module_or_path: wasmUrl });
const out = {};
for (const [date, jurisdiction, typikon] of probes) {
out[`${date}|${jurisdiction}|${typikon ? 1 : 0}`] =
shape(describeIso(date, { jurisdiction, typikon }));
}
return out;
};
+16
View File
@@ -0,0 +1,16 @@
"""Pull the probe result back out of the DOM the browser printed."""
import html
import json
import re
import sys
dom = open(sys.argv[1], encoding="utf-8").read()
match = re.search(r'<pre id="out">(.*?)</pre>', dom, re.S)
if not match:
sys.exit("the page produced no result element")
text = html.unescape(match.group(1))
if text == "running":
sys.exit("the page never finished; the wasm probably failed to load")
if text.startswith("ERROR"):
sys.exit(text[:600])
json.dump(json.loads(text), open(sys.argv[2], "w"), ensure_ascii=False)
+14
View File
@@ -0,0 +1,14 @@
<!doctype html>
<meta charset="utf-8">
<title>typikon parity</title>
<pre id="out">running</pre>
<script type="module">
import "./entry.js";
const probes = await (await fetch("./probes.json")).json();
try {
document.getElementById("out").textContent =
JSON.stringify(await window.typikonProbe(probes));
} catch (e) {
document.getElementById("out").textContent = "ERROR " + (e && e.stack || e);
}
</script>
+220 -2
View File
@@ -3,11 +3,11 @@
use typikon::calendars::{Date, JulianDate, Weekday};
use typikon::day::{describe, week, year_of};
use typikon::export::to_ics;
use typikon::export::{to_ics, to_ics_with, Ics};
use typikon::fasting::{Level, Obligation};
use typikon::jurisdictions::{resolve, Calendar, MenologionKind, CALENDARS, JURISDICTIONS};
use typikon::menologion::Rank;
use typikon::paschalion::{gregorian_pascha, julian_pascha, Paschalion};
use typikon::paschalion::{gregorian_pascha, julian_pascha, week_after_pentecost, Paschalion};
use typikon::seasons::Season;
fn d(s: &str) -> Date {
@@ -366,6 +366,200 @@ fn ics_is_well_formed() {
assert_eq!(text.matches("BEGIN:VEVENT").count(), text.matches("END:VEVENT").count());
}
#[test]
fn every_day_gives_every_day_an_event() {
let days = week(d("2026-09-21"), 60, resolve(Some("ruthenian")).unwrap());
let thin = to_ics(&days, "Typikon", "20260101T000000Z");
let full = to_ics_with(
&days,
&Ics { name: "Typikon", stamp: "20260101T000000Z", every_day: true },
);
assert!(thin.matches("BEGIN:VEVENT").count() < 60, "the thinned calendar drops days");
assert_eq!(full.matches("BEGIN:VEVENT").count(), 60);
for line in full.split("\r\n") {
assert!(line.len() <= 75, "{} octets: {line}", line.len());
}
}
#[test]
fn an_event_carries_the_saints_and_the_fast() {
// A ferial Wednesday of the Great Fast: no feast, a fast that binds, and
// a saint the thinned calendar would keep but the old body did not name
// until after the church date.
let days = week(d("2027-03-17"), 1, resolve(Some("ruthenian")).unwrap());
let text = to_ics_with(
&days,
&Ics { name: "Typikon", stamp: "20260101T000000Z", every_day: true },
);
let unfolded = text.replace("\r\n ", "");
let description = unfolded
.lines()
.find(|l| l.starts_with("DESCRIPTION:"))
.expect("an event with a description");
assert!(description.contains("\u{2022} Our Venerable Father Alexis the Man of God"),
"{description}");
assert!(description.contains("Fast: no meat"), "{description}");
assert!(description.contains("Obligatory."), "{description}");
assert!(description.contains("Church date: 17 March"), "{description}");
}
// ────────────────────── the Sundays of the movable year ──────────────────────
#[test]
fn the_pentecostarion_names_all_of_its_sundays() {
// Pascha 2027 is 28 March by the Gregorian paschalion and 2 May by the
// Julian one, so the same Sundays are asked of both reckonings.
for (jur, pascha) in [("ruthenian", "2027-03-28"), ("rocor", "2027-05-02")] {
let pascha = d(pascha);
for (offset, name) in [
(7, "Thomas Sunday"),
(14, "The Sunday of the Holy Myrrh-bearing Women"),
(21, "The Sunday of the Paralytic"),
(28, "The Sunday of the Samaritan Woman"),
(35, "The Sunday of the Blind Man"),
(42, "The Sunday of the Fathers of the First Council"),
] {
let day = describe(pascha + offset, resolve(Some(jur)).unwrap());
assert_eq!(day.weekday, Weekday::Sunday, "{jur} +{offset}");
let named = day.title().starts_with(name)
|| day.commemorations.iter().any(|c| c.starts_with(name));
assert!(named, "{jur} {} ({}) does not name {name}: {:?}",
day.date, offset, day.commemorations);
}
}
}
#[test]
fn a_vigil_rank_saint_keeps_the_day_and_the_sunday_joins_it() {
// 25 April 2027 is both the Sunday of the Samaritan Woman and St Mark,
// whose feast is of vigil rank. The apostle names the day; the Sunday is
// commemorated on it.
let day = at("2027-04-25", "ruthenian");
assert_eq!(day.title(), "The Holy Apostle and Evangelist Mark");
assert_eq!(day.rank, Some(Rank::Vigil));
assert!(day.commemorations.iter().any(|c| c == "The Sunday of the Samaritan Woman"),
"{:?}", day.commemorations);
}
#[test]
fn the_sundays_reckoned_from_a_fixed_feast_are_kept() {
for (date, jur, name) in [
("2026-09-13", "ruthenian", "The Sunday before the Exaltation"),
("2026-09-20", "ruthenian", "The Sunday after the Exaltation"),
("2026-12-13", "ruthenian", "The Sunday of the Holy Forefathers"),
("2026-12-20", "ruthenian", "The Sunday before the Nativity \u{2014} the Holy Fathers"),
("2026-12-27", "ruthenian", "The Sunday after the Nativity"),
("2027-01-03", "ruthenian", "The Sunday before the Theophany"),
("2027-01-10", "ruthenian", "The Sunday after the Theophany"),
// The old calendar keeps the same windows thirteen days later, which
// is the whole point of reckoning them in ecclesiastical space.
("2027-01-03", "moscow", "The Sunday before the Nativity \u{2014} the Holy Fathers"),
("2027-01-10", "moscow", "The Sunday after the Nativity"),
("2027-01-17", "moscow", "The Sunday before the Theophany"),
] {
let day = at(date, jur);
assert!(day.commemorations.iter().any(|c| c == name),
"{jur} {date}: {name} missing from {:?}", day.commemorations);
}
}
#[test]
fn a_nativity_on_a_sunday_moves_the_sunday_after_it_to_the_26th() {
// 25 December 2033 is a Sunday, so 26–31 December holds none and the
// Typikon keeps the Sunday after the Nativity on the Monday.
assert_eq!(at("2033-12-25", "ruthenian").weekday, Weekday::Sunday);
let monday = at("2033-12-26", "ruthenian");
assert_eq!(monday.weekday, Weekday::Monday);
assert!(monday.commemorations.iter().any(|c| c == "The Sunday after the Nativity"),
"{:?}", monday.commemorations);
// And it is kept once, not twice.
for n in 1..=6 {
let day = describe(d("2033-12-26") + n, resolve(Some("ruthenian")).unwrap());
assert!(!day.commemorations.iter().any(|c| c == "The Sunday after the Nativity"),
"{}", day.date);
}
}
#[test]
fn a_new_year_on_a_sunday_keeps_the_sunday_before_the_theophany_with_it() {
let day = at("2034-01-01", "ruthenian");
assert_eq!(day.weekday, Weekday::Sunday);
assert!(day.commemorations.iter().any(|c| c == "The Sunday before the Theophany"),
"{:?}", day.commemorations);
}
#[test]
fn no_sunday_of_the_year_is_named_twice() {
for jur in JURISDICTIONS.iter().chain(CALENDARS.iter()) {
for day in week(d("2024-01-01"), 366 * 12, jur) {
let mut seen = day.commemorations.clone();
seen.sort();
let before = seen.len();
seen.dedup();
assert_eq!(seen.len(), before, "{} {}: {:?}", jur.key, day.date, day.commemorations);
}
}
}
// ───────────────────── the count of weeks from Pentecost ─────────────────────
#[test]
fn the_weeks_after_pentecost_are_counted_from_all_saints() {
let p = Paschalion::Gregorian;
// Pascha 2026 is 5 April, so Pentecost is 24 May and All Saints 31 May.
assert_eq!(week_after_pentecost(d("2026-05-24"), p), None, "Pentecost itself");
assert_eq!(week_after_pentecost(d("2026-05-25"), p), Some(1), "the Monday after");
assert_eq!(week_after_pentecost(d("2026-05-31"), p), Some(1), "All Saints");
assert_eq!(week_after_pentecost(d("2026-06-07"), p), Some(2));
assert_eq!(week_after_pentecost(d("2026-09-27"), p), Some(18));
// The count does not restart at the new year: it runs on from last
// year's Pentecost until the Triodion opens.
assert_eq!(week_after_pentecost(d("2027-01-10"), p), Some(33));
assert_eq!(week_after_pentecost(d("2027-01-16"), p), Some(34));
// 17 January 2027 is the Publican and the Pharisee, and the Triodion
// names its own Sundays.
assert_eq!(week_after_pentecost(d("2027-01-17"), p), None);
assert_eq!(week_after_pentecost(d("2027-03-28"), p), None, "Pascha");
}
#[test]
fn the_week_is_worded_for_the_day_it_falls_on() {
assert_eq!(at("2026-09-27", "ruthenian").week.as_deref(),
Some("the 18th Sunday after Pentecost"));
assert_eq!(at("2026-09-28", "ruthenian").week.as_deref(),
Some("the 19th week after Pentecost"));
// The Pentecostarion and the Triodion carry names instead of numbers.
assert_eq!(at("2027-04-18", "ruthenian").week, None);
assert_eq!(at("2027-02-14", "ruthenian").week, None);
}
#[test]
fn the_week_count_never_skips_or_repeats_a_number() {
for jur in JURISDICTIONS.iter().chain(CALENDARS.iter()) {
// The walk starts mid-count, so the first run it sees is not a run
// that opened. Every later one is.
let mut last: Option<i32> = None;
let mut first_run = true;
for day in week(d("2025-01-01"), 366 * 6, jur) {
let Some(n) = week_after_pentecost(day.date, jur.paschalion) else {
if last.is_some() {
first_run = false;
}
last = None;
continue;
};
match last {
Some(prev) => assert!(n == prev || n == prev + 1,
"{} {}: {prev} then {n}", jur.key, day.date),
None if !first_run => assert_eq!(n, 1,
"{} {}: the count opens at one", jur.key, day.date),
None => {}
}
last = Some(n);
}
}
}
// ─────────────────────────── every jurisdiction ───────────────────────────
#[test]
@@ -706,3 +900,27 @@ fn date_arithmetic_saturates_instead_of_overflowing() {
assert_eq!(d.iso().len(), 10);
}
}
/// The published description counts the churches, on PyPI and on npm, where
/// nobody editing this table will see it. Adding a jurisdiction without saying
/// so makes that description quietly wrong, so the count is pinned here and
/// the failure names the two places to correct.
#[test]
fn the_published_description_still_counts_the_churches_correctly() {
let catholic = ["ruthenian", "ugcc", "melkite", "romanian-catholic"];
let orthodox = JURISDICTIONS
.iter()
.filter(|j| !catholic.contains(&j.key))
.count();
let byzantine_catholic = JURISDICTIONS
.iter()
.filter(|j| catholic.contains(&j.key))
.count();
assert_eq!(
(orthodox, byzantine_catholic, CALENDARS.len()),
(20, 4, 3),
"the counts moved; update `description` in Cargo.toml (PyPI) and in \
npm/package.json.in (npm), and the README's opening"
);
}