Compare commits

...
Author SHA1 Message Date
Dylan M. Taylor 9a1e05f442 ci(sonarcloud): give each main commit its own concurrency group (#4912) 2026-11-29 18:47:35 -05:00
Dylan M. Taylor be7732912b ci(nightly): enable automated scheduled nightly builds and Stage 2 signer dispatch (#4881)
* ci(nightly): enable scheduled nightly builds and automatic signer dispatch

* ci: update actions lockfile for nightly-dispatch.yml

* test(packaging): read workspace version from Cargo.toml in Linux launch test
2026-11-29 18:26:46 -05:00
Dylan M. Taylor c869fdb23c test(nightly): preserve startup failure without stable fallback (#4911) 2026-11-29 15:12:20 -05:00
Dylan M. Taylor be07bd69fd feat(nightly): wire craft-nightly for self-isolated nightly launches (#4906) 2026-11-29 13:48:48 -05:00
BFlat 5f22c7c01c Merge pull request #4908 from ruchirguitar/gc-4131-indic-fonts
Indian-script fallback fonts: Gujarati and Hindi text draws instead of boxes
2026-11-30 01:21:46 +07:00
ruchirguitar 838c9104c0 docs: one script-fallback paragraph in localization-parity.md
Drops the repeated Lao list and the stale 'no complex-text shaping'
sentence, which contradicted the Indian-script text.
2026-11-29 21:26:35 +05:30
ruchirguitar ade107ab73 fonts: name the Indian-script face tuple type (clippy type_complexity) 2026-11-29 21:15:45 +05:30
ruchirguitarandkulveersingh 44b8fc5b52 fonts: Indian-script shaping test accepts a ligated split vowel; docs
Nirmala UI draws Tamil கொ as one ligature rather than the vowel sign on
both sides of க, which is also shaped. The test now fails only when the
text comes out one glyph per code point. localization-parity.md lists
the Indian-script fallback faces and no longer says Devanagari is
unshaped.

Fixes #4131.

Co-authored-by: kulveersingh <kulveer.singh@gmail.com>
2026-11-29 21:09:57 +05:30
kulveersingh 331486148e fonts: system fallback faces for the nine Indian scripts
Gujarati, Hindi (Devanagari) and the other Indian scripts showed as empty
boxes in cells and the interface: the default fonts (Calibri, Arial) have
no glyphs for them and the fallback chain had no Indian-script face.

Adds one fallback entry per script, probing the system's own fonts:
Nirmala UI and the per-script faces on Windows, Kohinoor, Noto and
Sangam MN on macOS (the Regular face inside each collection), Noto Sans
or Lohit on Linux and the BSDs, including Fedora's variable Noto faces
and a Flatpak's host font mounts. Nothing is bundled.

From storytold/gridcraft#581 (17328a73d, 789311da8), ported to the
theme/font_fallback.rs layout on main.
2026-11-29 21:09:34 +05:30
FredAppsandFredrik Hallin 684d86b78d Release: GridCraft v0.20.0 (#4897)
Co-authored-by: Fredrik Hallin <fredrik.hallin@guidelinegeo.com>
2026-11-29 04:44:17 +01:00
Dylan M. Taylor 5b43c2abc8 fix(nightly): enable Linux package_formats (including Flatpak) in signing policy (#4896) 2026-11-28 22:40:36 -05:00
Dylan M. Taylor 01c94182f5 ci: pin storytold/craft-common-actions to @main universally (#4889) 2026-11-28 16:06:32 -05:00
Dylan M. Taylor 0ff6f02485 ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#4887) 2026-11-28 15:21:23 -05:00
Dylan M. Taylor f2934fd009 fix(nightly): allow reopening nightly profile with saved settings and session files (#4872) 2026-11-28 11:41:01 -05:00
FredApps ba597305a1 Merge pull request #4140 from alehel/split/text-defaults
Model: workbook text defaults: languages, Asian and complex fonts (ODS groundwork)
2026-11-27 23:29:47 +01:00
FredApps b742816737 parity: headless column from the engine registry (RFC-0052) (#4860) 2026-11-27 23:14:07 +01:00
skylar taylor-barrick 97f2754c1d nightly: put macOS notices where Launcher expects them (#4851) 2026-11-27 18:56:30 +01:00
skylar taylor-barrick 6357908c69 nightly: pick up the Windows signing wrapper fix (#4846) 2026-11-27 09:53:58 -06:00
alehelandClaude Opus 5.5 f45c122e79 Text defaults: the zero-sheet test saves and opens through GridCraft JSON
The test built its JSON with serde_json directly. It now saves with
io::save_bytes and opens with io::open_bytes, the craft-gridcraft-format
writer and reader main uses, empties the sheet list in between, and
gives the workbook a macro. One open then checks that the zero-sheet
reset carries both the text defaults and the macros. It fails when the
reset drops the text defaults.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 01:01:22 +01:00
alehelandClaude Opus 5.5 6868b7eb7b Merge storytold/gridcraft main into split/text-defaults
Main now reads GridCraft JSON through craft_gridcraft_format::read. That
reader deserialises the model with its own serde rules, so text_defaults
loads as before; the zero-sheet reset keeps carrying the macros and the
text defaults across.

Conflicts:
- crates/model/src/lib.rs: the re-export list takes both main's RefHost
  and WriteReservation and this branch's ScriptDefault and TextDefaults.
- docs/file-format-parity.md: main's header and history, with this
  branch's 2026-11-14 row placed among main's 2026-11-14 rows and its
  summary added to the header's "earlier" list in the same place.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 00:49:22 +01:00
alehel dd1ba0e33d Merge remote-tracking branch 'origin/main' into HEAD
# Conflicts:
#	docs/file-format-parity.md
2026-11-15 22:22:17 +01:00
alehel 810b95bf68 Text defaults: a JSON workbook without sheets keeps them on open
When GridCraft JSON has no sheets, the reader replaces the workbook with
Workbook::new() and carries only the macros across, so its text defaults
were dropped and a save lost them. They are carried across too.
2026-11-14 10:54:29 +01:00
alehel a85ee924d6 Merge storytold/gridcraft main into split/text-defaults 2026-11-14 08:29:50 +01:00
alehel 0d868b83df Text defaults: keep ODF's script code and BCP 47 language tag
ODF 1.2 states a default language with fo:script and style:rfc-language-tag
(and their -asian/-complex forms) as well as fo:language/fo:country. Without
them, locales such as sr-Latn-RS or ca-ES-valencia would lose their script or
variant on an ODS round trip, and adding them later would be a breaking model
change. ScriptDefault gains `script` and `rfc_language_tag`, both skipped in
JSON when unset and counted by is_empty. The `font` doc now says it holds the
family name (not a style:font-face name) and that western.font is unused; the
"no language" note says zxx is the language and none the country.

The test round-trips sr-Latn-RS and fails if is_empty ignores either new field.
2026-11-14 08:29:24 +01:00
alehel 05b883379a Text defaults: field doc says empty until a reader fills them 2026-11-14 08:29:24 +01:00
alehel ba6385b388 Text defaults: revision row in the history table; doc says no reader fills them yet 2026-11-14 08:29:24 +01:00
alehel 989782f1a0 Model: workbook text defaults (languages, Asian/complex fonts)
Adds ScriptDefault { language, country, font } and TextDefaults
{ western, asian, complex } with is_empty, and Workbook::text_defaults,
exported from the model crate. An OpenDocument file states these on its
default cell style; Excel has no equivalent, so XLSX ignores them. The
field is kept in GridCraft JSON and skipped when empty, so a workbook
without it serialises exactly as before.
2026-11-14 08:29:24 +01:00
29 changed files with 1129 additions and 733 deletions
+15 -5
View File
@@ -4,10 +4,10 @@
"repository_id": 1408285582,
"producer_workflow_id": 429713469,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
"producer_tooling_revision": "main",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "f94a43818dabb2e85f2f4d5cd768bb8e5662600a",
"signer_tooling_revision": "main",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
@@ -83,7 +83,9 @@
}
},
"max_artifact_bytes": 2147483648,
"automatic_signer_actors": [],
"automatic_signer_actors": [
"github-actions[bot]"
],
"platforms": {
"windows-x86_64": {
"unsigned_artifact_name": "nightly-unsigned-windows-x86_64",
@@ -95,7 +97,15 @@
"unsigned_artifact_name": "nightly-unsigned-linux-x86_64",
"trust": {
"fingerprint": "2B76741B414AAD6CD33E631213A005C0B9D7C3ED"
}
},
"package_formats": [
"appimage",
"arch",
"deb",
"flatpak",
"oci",
"rpm"
]
},
"macos-aarch64": {
"unsigned_artifact_name": "nightly-unsigned-macos-aarch64",
+1
View File
@@ -9,6 +9,7 @@ workflows:
'.github/workflows/lockfile.yml':
- 'actions/checkout@v7.0.1'
- 'step-security/harden-runner@v2.22.4'
'.github/workflows/nightly-dispatch.yml': []
'.github/workflows/nightly-sign.yml': []
'.github/workflows/nightly.yml': []
'.github/workflows/nix.yml': []
+71
View File
@@ -0,0 +1,71 @@
name: Dispatch release-ref nightly
# Transport only, never authorization. No checkout, payload parsing or release environment.
on:
workflow_run:
workflows: [GridCraft unsigned nightly]
types: [completed]
branches: [main]
permissions: {}
jobs:
dispatch:
if: >-
github.repository == 'storytold/gridcraft' &&
github.event_name == 'workflow_run'
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
actions: write
steps:
- name: Dispatch only the exact completed producer run and attempt
shell: python
env:
GH_TOKEN: ${{ github.token }}
run: |
import json
import os
import urllib.request
def require(value, message):
if not value:
raise RuntimeError(message)
# These filters reduce noise; the protected signer-branch validator repeats admission
# against authenticated API metadata and required attestation/quality evidence.
require(os.environ.get('GITHUB_REPOSITORY') == 'storytold/gridcraft', 'wrong repository')
require(os.environ.get('GITHUB_EVENT_NAME') == 'workflow_run', 'wrong event')
with open(os.environ['GITHUB_EVENT_PATH'], encoding='utf-8') as stream:
event = json.load(stream)
require(event.get('action') == 'completed', 'producer is not complete')
require(event.get('repository', {}).get('full_name') == 'storytold/gridcraft', 'wrong event repository')
producer = event.get('workflow_run', {})
require(producer.get('head_repository', {}).get('full_name') == 'storytold/gridcraft', 'foreign producer')
require(producer.get('path') == '.github/workflows/nightly.yml', 'wrong producer path')
require(producer.get('head_branch') == 'main', 'wrong producer branch')
require(producer.get('status') == 'completed' and producer.get('conclusion') == 'success', 'producer did not succeed')
# First scheduled attempt only; reviewed manual/re-run authority belongs to release policy.
require(producer.get('event') == 'schedule', 'not an automatic scheduled producer')
run_id, attempt = producer.get('id'), producer.get('run_attempt')
require(type(run_id) is int and run_id > 0, 'invalid producer run id')
require(type(attempt) is int and attempt == 1, 'invalid automatic producer attempt')
body = json.dumps({'ref': 'refs/heads/nightly-signer', 'inputs': {
'producer_run_id': str(run_id), 'producer_run_attempt': str(attempt)
}}).encode('utf-8')
request = urllib.request.Request(
'https://api.github.com/repos/storytold/gridcraft/actions/workflows/nightly-sign.yml/dispatches',
data=body, method='POST', headers={
'Authorization': 'Bearer ' + os.environ['GH_TOKEN'],
'Accept': 'application/vnd.github+json',
'Content-Type': 'application/json',
'X-GitHub-Api-Version': '2022-11-28',
'User-Agent': 'gridcraft-nightly-dispatch'
})
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
raise RuntimeError('dispatch redirects are forbidden')
# One bounded request, no retry: duplicate transport is not publication authority.
with urllib.request.build_opener(NoRedirect()).open(request, timeout=20) as response:
require(response.status == 204, 'dispatch was not accepted')
print('Dispatched producer run/attempt to the release-ref validator; not a signing result.')
+2 -2
View File
@@ -34,9 +34,9 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@main
with:
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
tooling-revision: main
app-name: gridcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
+6 -4
View File
@@ -1,8 +1,9 @@
name: GridCraft unsigned nightly
# Enabled for supervised manual runs by the reviewed manual actor only; no schedule yet.
# A later explicit opt-in may add a cadence (and turn on nightly-dispatch.yml with it).
# Automated daily nightly builds at 03:30 UTC (plus manual dispatch by reviewed manual actors).
on:
schedule:
- cron: '30 3 * * *'
workflow_dispatch:
permissions:
@@ -22,12 +23,13 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@f94a43818dabb2e85f2f4d5cd768bb8e5662600a
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@main
with:
tooling-revision: f94a43818dabb2e85f2f4d5cd768bb8e5662600a
tooling-revision: main
app-name: gridcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
# One producer run builds every listed platform for one all-or-nothing release. The pin is the
# craft-common-actions main commit that merged 8389cad8 (#375, the signer Windows fix).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+1 -1
View File
@@ -10,7 +10,7 @@ permissions:
contents: read
concurrency:
group: sonarcloud-${{ github.ref }}
group: ${{ github.ref == 'refs/heads/main' && format('sonarcloud-main-{0}', github.sha) || format('sonarcloud-{0}', github.ref) }}
# A push to main is the run that publishes coverage; superseded runs there would never finish.
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
+1
View File
@@ -81,4 +81,5 @@ Paths and conventions:
- Test corpora live in a separate corpus repository, pinned and sha256-verified. Test workbooks are built in code.
- Progress log: `ROADMAP.md`. `plan/` is an optional gitignored notebook.
- Run with a control channel: `cargo run --release -p gridcraft -- --sample sales --control 7979`. Drive it with `gridcraft-cli send 7979 <method> '<json>'`; methods are in `crates/ui-egui/src/control.rs`, the protocol in `docs/control-protocol.md`. Offscreen render: `cargo run -p gridcraft-ui-egui --example snapshot -- --sample sales out.png`. Headless: `gridcraft-cli eval '=SUM(1,2,3)'`, `gridcraft-cli mcp`.
- Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a catalog id `headless: yes` only when the engine registry (what `gridcraft-cli` and the MCP server load) has it. A missing id takes its `no`/`partial` value and `reach:` (`window`, `os` or `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs`, or reads `unknown`. When a command lands, delete its mark; the check fails on a stale one.
- Docs: `ROADMAP.md`, `docs/gaps.md` (ranked work), `docs/architecture.md`, `docs/target-app-parity.md`, `docs/roadmap.md`, `docs/contributors.md`.
Generated
+27 -18
View File
@@ -1216,6 +1216,14 @@ dependencies = [
"serde_json",
]
[[package]]
name = "craft-nightly"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24#1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24"
dependencies = [
"winsafe",
]
[[package]]
name = "craft-odf"
version = "0.1.0"
@@ -2841,10 +2849,11 @@ dependencies = [
[[package]]
name = "gridcraft"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"arboard",
"chrono",
"craft-nightly",
"craft-print",
"craft-update",
"eframe",
@@ -2870,7 +2879,7 @@ dependencies = [
[[package]]
name = "gridcraft-calc"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-core",
"gridcraft-formula",
@@ -2882,7 +2891,7 @@ dependencies = [
[[package]]
name = "gridcraft-chart"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-calc",
"gridcraft-core",
@@ -2893,7 +2902,7 @@ dependencies = [
[[package]]
name = "gridcraft-cli"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-engine",
"gridcraft-mcp",
@@ -2906,7 +2915,7 @@ dependencies = [
[[package]]
name = "gridcraft-core"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"chrono",
"js-sys",
@@ -2917,7 +2926,7 @@ dependencies = [
[[package]]
name = "gridcraft-engine"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"craft-csv",
"craft-gridcraft-format",
@@ -2943,7 +2952,7 @@ dependencies = [
[[package]]
name = "gridcraft-formula"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-core",
"serde",
@@ -2952,7 +2961,7 @@ dependencies = [
[[package]]
name = "gridcraft-functions"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-core",
"regex",
@@ -2960,7 +2969,7 @@ dependencies = [
[[package]]
name = "gridcraft-math"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"ratex-font",
"ratex-layout",
@@ -2970,7 +2979,7 @@ dependencies = [
[[package]]
name = "gridcraft-mcp"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"craft-mcp-server",
"gridcraft-engine",
@@ -2980,7 +2989,7 @@ dependencies = [
[[package]]
name = "gridcraft-model"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-core",
"gridcraft-formula",
@@ -2994,14 +3003,14 @@ dependencies = [
[[package]]
name = "gridcraft-numfmt"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-core",
]
[[package]]
name = "gridcraft-pdf"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"craft-pdf",
"craft-stream-codecs",
@@ -3013,7 +3022,7 @@ dependencies = [
[[package]]
name = "gridcraft-sandbox"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"landlock",
"libc",
@@ -3024,7 +3033,7 @@ dependencies = [
[[package]]
name = "gridcraft-ui-egui"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"craft-behavior",
"craft-host",
@@ -3056,7 +3065,7 @@ dependencies = [
[[package]]
name = "gridcraft-web"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"craft-web-api",
"craft-web-host",
@@ -3075,7 +3084,7 @@ dependencies = [
[[package]]
name = "gridcraft-xlsx"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"craft-cfb",
"craft-csv",
@@ -8249,7 +8258,7 @@ checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7"
[[package]]
name = "xtask"
version = "0.19.1"
version = "0.20.0"
dependencies = [
"gridcraft-engine",
"serde_json",
+2 -1
View File
@@ -4,7 +4,7 @@ members = ["crates/*", "apps/*", "xtask"]
default-members = ["crates/*", "apps/gridcraft", "apps/gridcraft-cli", "xtask"]
[workspace.package]
version = "0.19.1"
version = "0.20.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
@@ -53,6 +53,7 @@ craft-xml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
craft-xls = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-drawingml = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-mcp-server = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "=0.1.0" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "1f6c3a21f85ed96f8fd4ddd5a959d4e1edbedb24", version = "0.1.0" }
# foundation
thiserror = "2"
+2
View File
@@ -30,6 +30,8 @@ winresource = "0.1"
winit = { version = "0.30", default-features = false, features = ["x11", "wayland-csd-adwaita-notitle"] }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
# Nightly self-isolation, launch protocol, and security fence (storytold/craft-libs).
craft-nightly = { workspace = true }
# Same craft-libs revision as the workspace's craft-update and craft-window (see the root
# Cargo.toml).
craft-print = { workspace = true }
+5 -32
View File
@@ -1,24 +1,12 @@
//! Build-time channel is distinct from a launch selector: a runtime environment cannot promote a
//! stable build, and a nightly build cannot be talked out of its profile.
use crate::launch_profile::Profile;
//! stable build, and a nightly build always stays isolated in its nightly profile.
use std::ffi::OsString;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum BuildFlavor {
Stable,
NightlyV1,
}
pub use craft_nightly::BuildFlavor;
pub const COMPILED: BuildFlavor = if cfg!(gridcraft_nightly_v1) { BuildFlavor::NightlyV1 } else { BuildFlavor::Stable };
pub fn require_profile(flavor: BuildFlavor, profile: &Profile) -> Result<(), String> {
match (flavor, profile.is_nightly()) {
(BuildFlavor::NightlyV1, false) => Err("Open GridCraft Nightly from ArtCraft Launcher".into()),
(BuildFlavor::Stable, true) => Err("This is a stable GridCraft build; nightly-v1 requires the nightly build".into()),
_ => Ok(()),
}
}
pub fn needs_native_error(flavor: BuildFlavor, desktop_session: bool) -> bool {
desktop_session && flavor == BuildFlavor::NightlyV1
}
@@ -36,7 +24,8 @@ pub fn version(flavor: BuildFlavor, stable: &str) -> String {
#[cfg(test)]
mod tests {
use super::*;
use super::{BuildFlavor, needs_native_error, version, version_query};
#[test]
fn only_a_nightly_desktop_refusal_requests_a_native_dialog() {
assert!(needs_native_error(BuildFlavor::NightlyV1, true));
@@ -45,22 +34,6 @@ mod tests {
assert!(!needs_native_error(BuildFlavor::Stable, false));
}
#[test]
fn nightly_build_without_a_profile_is_refused_before_startup() {
let started = std::cell::Cell::new(false);
let result = require_profile(BuildFlavor::NightlyV1, &Profile::Stable).map(|()| started.set(true));
assert!(result.unwrap_err().contains("ArtCraft Launcher"));
assert!(!started.get());
}
#[test]
fn stable_and_nightly_flavors_accept_only_their_own_profile() {
let nightly = Profile::NightlyV1(std::path::PathBuf::from("already validated root"));
assert!(require_profile(BuildFlavor::Stable, &Profile::Stable).is_ok());
assert!(require_profile(BuildFlavor::Stable, &nightly).is_err());
assert!(require_profile(BuildFlavor::NightlyV1, &nightly).is_ok());
}
#[test]
fn nightly_version_query_is_unambiguous_and_never_reinterprets_file_arguments() {
assert_eq!(version(BuildFlavor::Stable, "0.19.1"), "0.19.1");
+83 -171
View File
@@ -1,131 +1,43 @@
//! Launcher-owned nightly-v1 bootstrap, selected before logging, updates, fonts or saved state.
//! Stable launches keep their original arguments and directory policy. No environment mutation.
//!
//! The protocol is the Launcher's, as PhotoCraft's is: `--launch-profile nightly-v1` with
//! `--profile-root <absolute>` as separate tokens, then `--` and the files. Everything after `--`
//! is a file, even when it looks like a profile flag. `--version` (and the Launcher's
//! `--launch-profile nightly-v1 --profile-root <abs> --version`) is answered by `main` before any
//! of this can create a directory, open a log or start a window.
//! Nightly-v1 bootstrap backed by `craft-nightly`, selected before logging, updates, fonts or saved
//! state. Direct launches of a nightly build self-isolate into
//! `craft_nightly::canonical_profile_root("gridcraft")`, while ArtCraft Launcher may still pass
//! `--launch-profile nightly-v1 --profile-root <absolute> -- <files...>`. Stable launches keep
//! their original arguments and directory policy.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
use std::sync::OnceLock;
pub const VERSION: &str = "nightly-v1";
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Profile {
Stable,
NightlyV1(PathBuf),
}
impl Profile {
pub fn is_nightly(&self) -> bool {
matches!(self, Self::NightlyV1(_))
}
pub fn root(&self) -> Option<&Path> {
match self {
Self::Stable => None,
Self::NightlyV1(root) => Some(root),
}
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct Launch {
pub profile: Profile,
pub args: Vec<OsString>,
}
static PROFILE: OnceLock<Profile> = OnceLock::new();
pub use craft_nightly::Profile;
/// Returns the process-wide profile installed by `craft_nightly::prepare_launch`, defaulting to
/// [`Profile::Stable`] before startup selection.
pub fn current() -> &'static Profile {
PROFILE.get().unwrap_or(&Profile::Stable)
craft_nightly::current().unwrap_or(&Profile::Stable)
}
pub fn install(profile: Profile) -> Result<(), String> {
PROFILE.set(profile).map_err(|_| "the launch profile was already selected".to_string())
}
/// Recognize only the agreed literal selector/root pair before `--`. No filesystem or startup hook
/// runs here.
pub fn parse(args: Vec<OsString>) -> Result<Launch, String> {
let mut selector = None;
let mut root = None;
let mut other = Vec::new();
let mut files = Vec::new();
let mut iter = args.iter();
let mut delimiter = false;
while let Some(arg) = iter.next() {
if arg == "--" {
delimiter = true;
files.extend(iter.cloned());
break;
}
if arg == "--launch-profile" || arg == "--profile-root" {
let slot = if arg == "--launch-profile" { &mut selector } else { &mut root };
if slot.is_some() {
return Err("the profile selector and root must each occur exactly once".into());
}
let value = iter.next().filter(|v| !v.is_empty()).ok_or("the profile selector/root needs a value")?;
if value.to_string_lossy().starts_with("--") {
return Err("the profile selector/root needs a value".into());
}
*slot = Some(value.clone());
} else if arg.to_string_lossy().starts_with("--launch-profile=") || arg.to_string_lossy().starts_with("--profile-root=") {
return Err("the nightly protocol requires separate literal selector/root argument tokens".into());
} else {
other.push(arg.clone());
}
/// Restores the `--` option terminator when `craft_nightly::parse_startup` consumed it after an
/// explicit `--launch-profile` / `--profile-root` header, so downstream argument parsing keeps
/// treating every launcher-supplied tail token (such as a file named `--control`) as a filename.
pub fn restore_launcher_separator(raw_args: &[OsString], passthrough_args: Vec<OsString>) -> Vec<OsString> {
let separator_index = raw_args.len().checked_sub(passthrough_args.len() + 1);
if let Some(index) = separator_index
&& raw_args.get(index).is_some_and(|arg| arg == "--")
{
return std::iter::once(OsString::from("--")).chain(passthrough_args).collect();
}
match (selector, root) {
(None, None) => Ok(Launch { profile: Profile::Stable, args }),
(Some(version), Some(root)) if version == VERSION => {
if !delimiter || !other.is_empty() {
return Err("nightly-v1 accepts only its selector/root followed by -- and file names".into());
}
let root = PathBuf::from(root);
if !root.is_absolute() || root.components().any(|c| matches!(c, Component::ParentDir)) {
return Err("the nightly profile root must be absolute and contain no parent traversal".into());
}
Ok(Launch { profile: Profile::NightlyV1(root), args: std::iter::once(OsString::from("--")).chain(files).collect() })
}
(Some(_), Some(_)) => Err("unsupported launch profile (expected nightly-v1)".into()),
_ => Err("--launch-profile and --profile-root must be supplied together".into()),
}
}
/// The Launcher's version check: the selector/root pair followed by exactly `--version` (or `-V`),
/// answered like a plain version query. Only [`parse`]'s lexical checks apply; the root is never
/// validated or touched, and `-- --version` stays a file name.
pub fn version_query(args: &[OsString]) -> bool {
let Some((last, pair)) = args.split_last() else { return false };
if last != "--version" && last != "-V" {
return false;
}
let lexical = pair.iter().cloned().chain(std::iter::once(OsString::from("--"))).collect();
matches!(parse(lexical), Ok(Launch { profile: Profile::NightlyV1(_), args }) if args.len() == 1)
}
/// Validation finishes before the caller's first startup effect. Stable never calls the nightly
/// root validator, so its old config resolution stays unchanged.
pub fn prepare(mut launch: Launch, validate: impl FnOnce(&Path) -> Result<PathBuf, String>) -> Result<Launch, String> {
if let Profile::NightlyV1(root) = &launch.profile {
launch.profile = Profile::NightlyV1(validate(root)?);
}
Ok(launch)
}
/// Resolve the selected private root before the caller's first startup effect.
pub fn validate_root(root: &Path, env: impl Fn(&str) -> Option<OsString>, exe: Option<&Path>) -> Result<PathBuf, String> {
crate::profile_root::validate(root, env, exe, crate::profile_root::ensure_writable)
passthrough_args
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::Cell;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use craft_nightly::{
BuildFlavor, NIGHTLY_V1_CONTRACT, Profile, ProfileError, StartupOptions, canonical_profile_root, launch_arguments, parse_startup,
};
use super::restore_launcher_separator;
use crate::profile_root;
fn args(values: &[&str]) -> Vec<OsString> {
values.iter().map(OsString::from).collect()
@@ -136,88 +48,88 @@ mod tests {
}
fn nightly() -> Vec<OsString> {
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--"])
launch_arguments(Path::new(absolute()), &[])
}
#[test]
fn stable_arguments_and_directory_policy_are_unchanged() {
let spec = profile_root::app_spec();
for argv in [args(&[]), args(&["sales.xlsx"]), args(&["--control", "7979"]), args(&["--", "--launch-profile", "book.xlsx"])] {
let launch = prepare(parse(argv.clone()).unwrap(), |_| panic!("stable must never validate a nightly root")).unwrap();
assert_eq!(launch, Launch { profile: Profile::Stable, args: argv });
let launch = parse_startup(BuildFlavor::Stable, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::Stable);
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
}
}
#[test]
fn direct_nightly_launch_self_isolates_into_canonical_root_and_preserves_args() {
let spec = profile_root::app_spec();
let expected_root = canonical_profile_root("gridcraft").expect("canonical root");
let argv = args(&["sales.xlsx", "--sample", "budget"]);
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(expected_root));
assert!(launch.profile.is_nightly());
assert_eq!(restore_launcher_separator(&argv, launch.passthrough_args), argv);
}
#[test]
fn exact_selector_and_root_are_parsed_without_reinterpreting_file_names() {
let spec = profile_root::app_spec();
let mut argv = nightly();
argv.extend(args(&["--profile-root", "a file with spaces.xlsx", "--version"]));
let launch = parse(argv).unwrap();
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.iter().cloned(), &StartupOptions::default()).unwrap();
assert_eq!(launch.profile, Profile::NightlyV1(PathBuf::from(absolute())));
assert_eq!(launch.args, args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"]));
assert_eq!(
restore_launcher_separator(&argv, launch.passthrough_args),
args(&["--", "--profile-root", "a file with spaces.xlsx", "--version"])
);
}
#[test]
fn missing_duplicate_unknown_and_conflicting_profile_arguments_are_refused() {
fn stable_build_refuses_nightly_launch_flags() {
let spec = profile_root::app_spec();
let result = parse_startup(BuildFlavor::Stable, &spec, nightly(), &StartupOptions::default());
assert!(matches!(result, Err(ProfileError::NightlyFlagsInStableBuild)));
}
#[test]
fn missing_duplicate_unknown_and_misplaced_profile_arguments_are_refused() {
let spec = profile_root::app_spec();
for argv in [
args(&["--launch-profile", VERSION]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT]),
args(&["--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--launch-profile", VERSION, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "/one/../two", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", "", "--"]),
args(&["--launch-profile=nightly-v1", "--profile-root", absolute(), "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "sales.xlsx", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--profile-root", absolute(), "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", "", "--"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "sales.xlsx", "--profile-root", absolute()]),
args(&["sales.xlsx", "--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute()]),
] {
assert!(parse(argv.clone()).is_err(), "{argv:?}");
assert!(parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).is_err(), "{argv:?}");
}
assert!(parse(args(&["--launch-profile", "--profile-root", absolute(), "--"])).is_err(), "a flag is not a value");
}
#[test]
fn the_launcher_version_check_is_a_version_query_only_in_its_exact_form() {
let pair = &["--launch-profile", VERSION, "--profile-root", absolute()];
let reversed = &["--profile-root", absolute(), "--launch-profile", VERSION];
for flag in ["--version", "-V"] {
for form in [pair, reversed] {
let mut argv = args(form);
argv.push(flag.into());
assert!(version_query(&argv), "{argv:?}");
}
}
fn launcher_version_queries_are_recognized_without_touching_the_profile() {
let spec = profile_root::app_spec();
for argv in [
args(&["--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--control", "7979", "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version", "--version"]),
args(&["--version", "--launch-profile", VERSION, "--profile-root", absolute()]),
args(&["--launch-profile", "future-v2", "--profile-root", absolute(), "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", "relative", "--version"]),
args(&["--launch-profile", VERSION, "--version"]),
args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--help"]),
args(&["-V"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--version"]),
args(&["--profile-root", absolute(), "--launch-profile", NIGHTLY_V1_CONTRACT, "-V"]),
launch_arguments(Path::new(absolute()), &args(&["--version"])),
launch_arguments(Path::new(absolute()), &args(&["-V"])),
] {
assert!(!version_query(&argv), "{argv:?}");
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
assert!(launch.is_version_query(), "{argv:?}");
}
for argv in [
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--help"]),
args(&["--launch-profile", NIGHTLY_V1_CONTRACT, "--profile-root", absolute(), "--control", "7979", "--version"]),
launch_arguments(Path::new(absolute()), &args(&["sales.xlsx", "--version"])),
] {
let launch = parse_startup(BuildFlavor::NightlyV1, &spec, argv.clone(), &StartupOptions::default()).unwrap();
assert!(!launch.is_version_query(), "{argv:?}");
}
// Outside the query the strict protocol still refuses the version flag.
assert!(parse(args(&["--launch-profile", VERSION, "--profile-root", absolute(), "--version"])).is_err());
}
#[test]
fn failed_root_validation_never_reaches_startup_or_falls_back_to_stable() {
let reached = Cell::new(false);
let result = prepare(parse(nightly()).unwrap(), |_| Err("read-only or unsafe profile".into())).map(|_| reached.set(true));
assert!(result.is_err());
assert!(!reached.get());
}
#[test]
fn successful_root_validation_keeps_the_persistent_root_not_the_binary_tag() {
let checked = PathBuf::from(absolute()).join("checked");
let launch = prepare(parse(nightly()).unwrap(), |_| Ok(checked.clone())).unwrap();
assert_eq!(launch.profile.root(), Some(checked.as_path()));
assert!(launch.profile.is_nightly());
}
}
+40 -29
View File
@@ -304,46 +304,47 @@ fn report_launch_profile_error(error: &str) {
fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
let argv: Vec<std::ffi::OsString> = std::env::args_os().skip(1).collect();
let nightly_build = build_flavor::COMPILED == build_flavor::BuildFlavor::NightlyV1;
// Plain `--version`, or the Launcher's `--launch-profile nightly-v1 --profile-root <dir>
// --version`: answered before root validation, process identity, IPC or any window (a dialog
// here would hang a headless runner and fail a Linux build).
if nightly_build && (build_flavor::version_query(&argv) || launch_profile::version_query(&argv)) {
// Plain `--version` / `-V` on a nightly build is answered before any profile resolution,
// process identity, IPC, or window (a dialog here would hang a headless runner and fail a
// Linux build, and `--version` must still work when HOME / LOCALAPPDATA is unset).
if nightly_build && build_flavor::version_query(&argv) {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
return None;
}
let early = launch_profile::parse(argv)
.and_then(|launch| {
build_flavor::require_profile(build_flavor::COMPILED, &launch.profile)?;
initialize_nightly_process_identity().map_err(|error| error.to_string())?;
Ok(launch)
})
.and_then(|launch| {
launch_profile::prepare(launch, |root| {
launch_profile::validate_root(root, |key| std::env::var_os(key), std::env::current_exe().ok().as_deref())
})
})
let spec = profile_root::app_spec();
let launch = craft_nightly::prepare_launch(build_flavor::COMPILED, &spec, argv.iter().cloned(), &craft_nightly::StartupOptions::default())
.unwrap_or_else(|error| {
report_launch_profile_error(&error);
report_launch_profile_error(&error.to_string());
std::process::exit(2)
});
// Launcher's `--launch-profile nightly-v1 --profile-root <dir> [--] --version`:
// `craft_nightly::prepare_launch` performs no filesystem preparation and installs no profile.
if nightly_build && launch.is_version_query() {
use std::io::Write as _;
let version = build_flavor::version(build_flavor::COMPILED, env!("GRIDCRAFT_BUILT_VERSION"));
let _ = writeln!(std::io::stdout(), "{} {version}", gridcraft_ui_egui::channel::name_for(gridcraft_ui_egui::channel::Channel::Stable));
return None;
}
if let Err(error) = initialize_nightly_process_identity() {
report_launch_profile_error(&error.to_string());
std::process::exit(2);
}
let channel =
if early.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) =
launch_profile::install(early.profile).and_then(|()| gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")))
{
if launch.profile.is_nightly() { gridcraft_ui_egui::channel::Channel::NightlyV1 } else { gridcraft_ui_egui::channel::Channel::Stable };
if let Err(error) = gridcraft_ui_egui::channel::select(channel, env!("GRIDCRAFT_BUILT_VERSION")) {
report_launch_profile_error(&error);
std::process::exit(2);
}
Some(early.args)
Some(launch_profile::restore_launcher_separator(&argv, launch.passthrough_args))
}
/// The app's own command line, once the launch profile's tokens are gone: `--control`,
/// `--control-token`, `--sample` and the files to open. `--` ends the options, and everything after
/// it is a file, even a name that reads like one — that is how the Launcher hands a nightly its
/// documents (`launch_profile::parse` puts the separator first), so the separator itself is never
/// opened as a file.
/// documents (`launch_profile::restore_launcher_separator` preserves the separator first), so the
/// separator itself is never opened as a file.
#[derive(Debug, Default, PartialEq)]
struct DesktopArgs {
control_port: Option<u16>,
@@ -660,8 +661,9 @@ mod launch_separator_tests {
use crate::build_flavor::BuildFlavor;
/// The profile root a Launcher run is started with: absolute for the platform the test runs on.
/// `launch_profile::parse` refuses a root that is relative there, and a POSIX path has no drive
/// or UNC prefix, so it is not absolute on Windows - where CI runs these tests too.
/// `craft_nightly::validate_and_prepare_root` refuses a root that is relative there, and a
/// POSIX path has no drive or UNC prefix, so it is not absolute on Windows - where CI runs
/// these tests too.
fn launcher_root() -> &'static str {
if cfg!(windows) { r"C:\NightlyData\profiles\gridcraft" } else { "/nightly-data/profiles/gridcraft" }
}
@@ -671,15 +673,24 @@ mod launch_separator_tests {
let mut argv: Vec<std::ffi::OsString> =
["--launch-profile", "nightly-v1", "--profile-root", launcher_root(), "--"].iter().map(std::ffi::OsString::from).collect();
argv.extend(tail.iter().map(std::ffi::OsString::from));
launch_profile::parse(argv).unwrap().args.iter().map(|a| a.to_string_lossy().into_owned()).collect()
let launch = craft_nightly::parse_startup(
BuildFlavor::NightlyV1,
&profile_root::app_spec(),
argv.iter().cloned(),
&craft_nightly::StartupOptions::default(),
)
.unwrap();
launch_profile::restore_launcher_separator(&argv, launch.passthrough_args).iter().map(|a| a.to_string_lossy().into_owned()).collect()
}
#[test]
fn the_other_platforms_root_spelling_is_refused_as_relative() {
let foreign = if cfg!(windows) { "/nightly-data/profiles/gridcraft" } else { r"C:\NightlyData\profiles\gridcraft" };
let argv: Vec<std::ffi::OsString> =
["--launch-profile", "nightly-v1", "--profile-root", foreign, "--"].iter().map(std::ffi::OsString::from).collect();
assert!(launch_profile::parse(argv).is_err(), "a root that is not absolute on this platform must be refused");
let result = craft_nightly::validate_and_prepare_root(std::path::Path::new(foreign), &profile_root::app_spec());
assert!(
matches!(result, Err(craft_nightly::ProfileError::RelativeProfileRoot(_))),
"a root that is not absolute on this platform must be refused"
);
}
#[test]
+209 -419
View File
@@ -1,35 +1,91 @@
//! GridCraft's nightly profile fences: no stable fallback, no migration and no change to the
//! process environment. Every stable place a GridCraft build keeps user state is refused as a
//! nightly root, in both directions, so the two channels can never share a file.
//! GridCraft's nightly profile specification and control-directory boundary, backed by
//! `craft-nightly`. Every stable place a GridCraft build keeps user state or installs is fenced off
//! so the two channels can never share a file.
use std::ffi::OsString;
use std::path::{Component, Path, PathBuf};
/// The folder the Windows build writes its control-channel token to (`gridcraft_mcp`).
const WINDOWS_TOKEN_DIR: &str = ".gridcraft";
use craft_nightly::AppProfileSpec;
/// The subfolder of the profile the nightly control-channel token goes to, when one runs.
pub const CONTROL_DIR: &str = "Control";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Platform {
Windows,
Linux,
Mac,
const PROFILE_FOLDERS: [&str; 2] = [CONTROL_DIR, "logs"];
/// Returns GridCraft's `craft-nightly` isolation specification, preserving every stable data,
/// token, Flatpak, and installer boundary.
pub fn app_spec() -> AppProfileSpec {
AppProfileSpec {
app_id: "gridcraft",
display_name: "GridCraft",
stable_dir_names: &["gridcraft", "GridCraft"],
stable_package_id: gridcraft_ui_egui::channel::APP_ID,
nightly_package_id: gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
profile_root_env: None,
forbidden_env_vars: &[],
portable_markers: &[],
folder_only_entries: &PROFILE_FOLDERS,
extra_forbidden_roots: extra_forbidden_roots(|key| std::env::var_os(key)),
}
}
impl Platform {
fn current() -> Result<Self, String> {
match std::env::consts::OS {
"windows" => Ok(Self::Windows),
"linux" => Ok(Self::Linux),
"macos" => Ok(Self::Mac),
// FreeBSD, the BSDs and anything else have no nightly channel.
_ => Err("nightly-v1 is not defined for this operating system".into()),
fn non_empty_abs(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Option<PathBuf> {
let value = env(key)?;
if value.is_empty() {
return None;
}
let path = PathBuf::from(value);
if path.is_absolute() && !path.components().any(|c| matches!(c, Component::ParentDir)) { Some(path) } else { None }
}
/// Platform-specific stable install, token, Flatpak, and macOS state paths beyond the standard OS
/// config/data/cache directories already fenced by `craft-nightly`.
fn extra_forbidden_roots(env: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
#[cfg(target_os = "windows")]
{
// `gridcraft_mcp`'s control-channel token folder and both MSI install folders
// (`install-policy.wxi`).
let mut roots = Vec::new();
if let Some(local) = non_empty_abs(&env, "LOCALAPPDATA") {
roots.push(local.join("Programs").join("ArtCraft").join("GridCraft"));
}
if let Some(profile) = non_empty_abs(&env, "USERPROFILE") {
roots.push(profile.join(".gridcraft"));
}
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = non_empty_abs(&env, key) {
roots.push(base.join("ArtCraft").join("GridCraft"));
}
}
roots
}
fn ignores_case(self) -> bool {
self != Self::Linux
#[cfg(all(unix, not(target_os = "macos")))]
{
let mut roots: Vec<PathBuf> = ["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].into_iter().map(PathBuf::from).collect();
// The stable Flatpak keeps its data in its own per-app folder.
if let Some(home) = non_empty_abs(&env, "HOME") {
roots.push(home.join(".var/app/ai.storyteller.gridcraft"));
}
roots
}
#[cfg(target_os = "macos")]
{
let mut roots = vec![PathBuf::from("/Applications/GridCraft.app")];
if let Some(home) = non_empty_abs(&env, "HOME") {
let library = home.join("Library");
roots.push(library.join("Preferences/ai.storyteller.gridcraft.plist"));
roots.push(library.join("Saved Application State/ai.storyteller.gridcraft.savedState"));
roots.push(home.join("Applications/GridCraft.app"));
}
roots
}
#[cfg(not(any(unix, target_os = "windows")))]
{
let _ = env;
Vec::new()
}
}
@@ -40,18 +96,6 @@ fn absolute(path: PathBuf, label: &str) -> Result<PathBuf, String> {
Ok(path)
}
fn required_base(env: &impl Fn(&str) -> Option<OsString>, key: &str) -> Result<PathBuf, String> {
let value = env(key).filter(|v| !v.is_empty()).ok_or_else(|| format!("cannot establish the stable {key} boundary"))?;
absolute(PathBuf::from(value), key)
}
fn xdg_base(env: &impl Fn(&str) -> Option<OsString>, key: &str, fallback: &str) -> Result<PathBuf, String> {
match env(key).filter(|v| !v.is_empty()) {
Some(value) => absolute(PathBuf::from(value), key),
None => Ok(required_base(env, "HOME")?.join(fallback)),
}
}
/// Resolve existing ancestors before creating anything. A dangling link or an inaccessible
/// ancestor is not a missing directory that may be replaced or followed later.
fn canonical_future(path: &Path) -> Result<PathBuf, String> {
@@ -74,102 +118,21 @@ fn canonical_future(path: &Path) -> Result<PathBuf, String> {
Ok(resolved)
}
fn overlaps(a: &Path, b: &Path, platform: Platform) -> bool {
let parts = |p: &Path| {
p.components()
.map(|c| {
let value = c.as_os_str().to_string_lossy().into_owned();
if platform.ignores_case() { value.to_lowercase() } else { value }
})
.collect::<Vec<_>>()
};
let (a, b) = (parts(a), parts(b));
a.starts_with(&b) || b.starts_with(&a)
}
fn installation_boundary(platform: Platform, exe: &Path) -> Result<PathBuf, String> {
let parent = exe.parent().ok_or("cannot establish the installation boundary")?;
if platform == Platform::Mac {
// A profile in Resources is still inside the versioned install, not beside MacOS.
if let Some(bundle) = exe.ancestors().find(|p| p.extension().is_some_and(|ext| ext.eq_ignore_ascii_case("app"))) {
return Ok(bundle.to_path_buf());
}
}
Ok(parent.to_path_buf())
}
fn forbidden_roots(platform: Platform, env: &impl Fn(&str) -> Option<OsString>, exe: &Path) -> Result<Vec<PathBuf>, String> {
let mut roots = match platform {
Platform::Windows => {
// `apps/gridcraft/src/main.rs` (ui.json, prefs.json and logs) and `gridcraft_mcp`'s
// token folder, plus both MSI install folders (`install-policy.wxi`).
let mut roots = ["APPDATA", "LOCALAPPDATA"]
.into_iter()
.map(|key| required_base(env, key).map(|p| p.join("GridCraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.push(required_base(env, "LOCALAPPDATA")?.join("Programs").join("ArtCraft").join("GridCraft"));
roots.push(required_base(env, "USERPROFILE")?.join(WINDOWS_TOKEN_DIR));
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
if let Some(base) = env(key).filter(|v| !v.is_empty()) {
roots.push(absolute(PathBuf::from(base), key)?.join("ArtCraft").join("GridCraft"));
}
}
roots
}
Platform::Linux => {
let mut roots =
[("XDG_CONFIG_HOME", ".config"), ("XDG_DATA_HOME", ".local/share"), ("XDG_CACHE_HOME", ".cache"), ("XDG_STATE_HOME", ".local/state")]
.into_iter()
.map(|(key, fallback)| xdg_base(env, key, fallback).map(|p| p.join("gridcraft")))
.collect::<Result<Vec<_>, _>>()?;
roots.extend(["/usr/bin/gridcraft", "/usr/local/bin/gridcraft", "/opt/gridcraft"].map(PathBuf::from));
// The stable Flatpak keeps its data in its own per-app folder.
roots.push(required_base(env, "HOME")?.join(".var/app/ai.storyteller.gridcraft"));
// `gridcraft_mcp`'s token folder when no XDG runtime directory is set.
roots.push(required_base(env, "HOME")?.join(".cache").join("gridcraft"));
roots
}
Platform::Mac => {
let home = required_base(env, "HOME")?;
let library = home.join("Library");
vec![
library.join("Application Support/GridCraft"),
library.join("Caches/GridCraft"),
library.join("Caches/ai.storyteller.gridcraft"),
library.join("Preferences/GridCraft"),
library.join("Preferences/ai.storyteller.gridcraft.plist"),
library.join("Saved Application State/ai.storyteller.gridcraft.savedState"),
home.join("Applications/GridCraft.app"),
PathBuf::from("/Applications/GridCraft.app"),
]
}
};
roots.push(installation_boundary(platform, exe)?);
roots.into_iter().map(|p| canonical_future(&p)).collect()
}
fn private_subdirectory(root: &Path, name: impl AsRef<Path>, label: &str) -> Result<PathBuf, String> {
let chosen = canonical_future(&absolute(root.to_path_buf(), "the nightly profile root")?)?;
let child = canonical_future(&chosen.join(name))?;
if child == chosen || !child.starts_with(&chosen) {
return Err(format!("the nightly {label} must stay inside its selected profile"));
}
Ok(child)
}
/// Every existing entry directly in the profile (settings, logs and so on) must resolve inside it,
/// so a link there cannot point Nightly's writes at the stable app's data.
fn entries_stay_inside(root: &Path) -> Result<(), String> {
let entries = match std::fs::read_dir(root) {
Ok(entries) => entries,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(()),
Err(error) => return Err(format!("cannot inspect the nightly profile: {error}")),
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
match std::fs::symlink_metadata(&child) {
Ok(metadata) if !metadata.file_type().is_dir() => {
return Err(format!("the nightly {label} must be a directory, not a file or an alias"));
}
Ok(_) => {}
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
Err(error) => return Err(format!("cannot inspect the nightly {label}: {error}")),
}
Ok(())
Ok(child)
}
/// Where a nightly control-channel token goes: `<profile>/Control`, created lazily by
@@ -178,351 +141,178 @@ pub fn control_directory(root: &Path) -> Result<PathBuf, String> {
private_subdirectory(root, CONTROL_DIR, "control folder")
}
/// The app's own exclusive writable probe: create a file inside the profile, then remove it.
pub fn ensure_writable(root: &Path) -> std::io::Result<()> {
static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
// A crashed launch can leave a probe with this name behind: take the next one instead of
// failing, and remove only the file this call created, never someone else's.
loop {
let probe =
root.join(format!(".gridcraft-nightly-writable-{}-{}", std::process::id(), NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)));
match std::fs::OpenOptions::new().write(true).create_new(true).open(&probe) {
Ok(_) => return std::fs::remove_file(&probe),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => return Err(error),
}
}
}
/// The writable hook is injected so filesystem boundary tests exercise the real policy without
/// starting the app or changing global state.
pub fn validate(
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
validate_for(Platform::current()?, root, env, exe, writable)
}
fn validate_for(
platform: Platform,
root: &Path,
env: impl Fn(&str) -> Option<OsString>,
exe: Option<&Path>,
writable: impl FnOnce(&Path) -> std::io::Result<()>,
) -> Result<PathBuf, String> {
absolute(root.to_path_buf(), "the nightly profile root")?;
if platform != Platform::Windows
&& let Some(id) = env("FLATPAK_ID").filter(|value| !value.is_empty())
&& id.to_string_lossy().as_ref() != gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID
{
// `packaging/linux/flatpak-bundle.sh` builds GridCraft Nightly as its own Flatpak
// (`ai.storyteller.gridcraft.nightly`), whose sandbox is already a private home, so that one
// instance may carry a profile. Any other, the stable app's included, could point it at
// another installation's tree; these rows are otherwise native tar/app-bundle launches.
return Err(format!(
"nightly-v1 can only run inside its own Flatpak instance ({}), not {}",
gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID,
id.to_string_lossy()
));
}
let chosen = canonical_future(root)?;
let exe = absolute(exe.ok_or("cannot establish the installation boundary")?.to_path_buf(), "the executable")?;
let forbidden = forbidden_roots(platform, &env, &exe)?;
if forbidden.iter().any(|stable| overlaps(&chosen, stable, platform)) {
return Err("the nightly root must not overlap stable data or an installation".into());
}
// Existing aliases under the profile must not redirect a subfolder elsewhere.
control_directory(&chosen)?;
entries_stay_inside(&chosen)?;
let mut create = std::fs::DirBuilder::new();
create.recursive(true);
#[cfg(unix)]
{
use std::os::unix::fs::DirBuilderExt as _;
create.mode(0o700);
}
create.create(&chosen).map_err(|e| format!("cannot create the nightly profile: {e}"))?;
let confirmed = std::fs::canonicalize(&chosen).map_err(|e| format!("cannot resolve the created nightly profile: {e}"))?;
if confirmed != chosen || forbidden.iter().any(|stable| overlaps(&confirmed, stable, platform)) {
return Err("the nightly profile changed while it was being validated".into());
}
control_directory(&confirmed)?;
entries_stay_inside(&confirmed)?;
writable(&confirmed).map_err(|e| format!("the nightly profile is not writable: {e}"))?;
Ok(confirmed)
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
use std::ffi::OsString;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicU64, Ordering};
struct Fixture {
use craft_nightly::{ProfileError, validate_and_prepare_root};
use super::{CONTROL_DIR, PROFILE_FOLDERS, app_spec, control_directory, extra_forbidden_roots};
struct TempDir {
root: PathBuf,
env: BTreeMap<String, OsString>,
exe: PathBuf,
}
impl Fixture {
fn new() -> Self {
impl TempDir {
fn new(label: &str) -> Self {
static NEXT: AtomicU64 = AtomicU64::new(0);
let root = loop {
let candidate =
std::env::temp_dir().join(format!("gridcraft-profile-policy-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
std::env::temp_dir().join(format!("gridcraft-profile-{label}-{}-{}", std::process::id(), NEXT.fetch_add(1, Ordering::Relaxed)));
match std::fs::create_dir(&candidate) {
Ok(()) => break std::fs::canonicalize(candidate).unwrap(),
Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => continue,
Err(error) => panic!("cannot create owned fixture: {error}"),
}
};
let home = root.join("home");
let exe = root.join("install/gridcraft");
std::fs::create_dir_all(&home).unwrap();
std::fs::create_dir_all(exe.parent().unwrap()).unwrap();
std::fs::write(&exe, b"fixture executable, never run").unwrap();
let env = [("HOME", home.clone()), ("USERPROFILE", home), ("APPDATA", root.join("roaming")), ("LOCALAPPDATA", root.join("local"))]
.into_iter()
.map(|(key, value)| (key.into(), value.into_os_string()))
.collect();
Self { root, env, exe }
Self { root }
}
fn get(&self, key: &str) -> Option<OsString> {
self.env.get(key).cloned()
}
fn check(&self, platform: Platform, root: &Path) -> Result<PathBuf, String> {
self.check_with(platform, root, |_| Ok(()))
}
fn check_with(&self, platform: Platform, root: &Path, writable: impl FnOnce(&Path) -> std::io::Result<()>) -> Result<PathBuf, String> {
validate_for(platform, root, |key| self.get(key), Some(&self.exe), writable)
}
fn home(&self) -> PathBuf {
PathBuf::from(self.get("HOME").unwrap())
fn path(&self) -> &Path {
&self.root
}
}
impl Drop for Fixture {
impl Drop for TempDir {
fn drop(&mut self) {
// Only the directory successfully created by this fixture is owned for removal.
std::fs::remove_dir_all(&self.root).unwrap();
let _ = std::fs::remove_dir_all(&self.root);
}
}
#[test]
fn every_stable_data_root_is_refused_on_its_own_platform() {
let mut fixture = Fixture::new();
// Windows: APPDATA\GridCraft (settings and logs), LOCALAPPDATA\GridCraft, the per-user
// and per-machine install folders and the control-token folder.
for key in ["APPDATA", "LOCALAPPDATA"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("GridCraft");
for candidate in [stable.clone(), stable.join("nightly")] {
assert!(fixture.check(Platform::Windows, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert!(!stable.exists());
fn failed_profile_preparation_does_not_start_with_stable() {
let tmp = TempDir::new("file-root");
let root = tmp.path().join("not-a-directory");
std::fs::write(&root, b"an ordinary file").unwrap();
let argv = craft_nightly::launch_arguments(&root, &[]);
let result =
craft_nightly::prepare_launch(craft_nightly::BuildFlavor::NightlyV1, &app_spec(), argv, &craft_nightly::StartupOptions::default());
assert!(matches!(result, Err(ProfileError::NotADirectory(_))));
assert_eq!(std::fs::read(&root).unwrap(), b"an ordinary file");
}
#[test]
fn app_spec_preserves_gridcraft_identifiers_and_folder_entries() {
let spec = app_spec();
assert_eq!(spec.app_id, "gridcraft");
assert_eq!(spec.display_name, "GridCraft");
assert_eq!(spec.stable_dir_names, &["gridcraft", "GridCraft"]);
assert_eq!(spec.stable_package_id, gridcraft_ui_egui::channel::APP_ID);
assert_eq!(spec.nightly_package_id, gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID);
assert_eq!(spec.profile_root_env, None);
assert!(spec.forbidden_env_vars.is_empty());
assert!(spec.portable_markers.is_empty());
assert_eq!(spec.folder_only_entries, &PROFILE_FOLDERS);
}
#[test]
fn extra_forbidden_roots_include_platform_install_and_state_paths() {
let tmp = TempDir::new("extra-roots");
let home = tmp.path().join("home");
let local = tmp.path().join("local");
let program_files = tmp.path().join("program-files");
let env: BTreeMap<&str, OsString> = [
("HOME", home.clone().into_os_string()),
("USERPROFILE", home.clone().into_os_string()),
("LOCALAPPDATA", local.clone().into_os_string()),
("ProgramFiles", program_files.clone().into_os_string()),
]
.into_iter()
.collect();
let roots = extra_forbidden_roots(|key| env.get(key).cloned());
#[cfg(target_os = "windows")]
{
assert!(roots.contains(&local.join("Programs").join("ArtCraft").join("GridCraft")));
assert!(roots.contains(&home.join(".gridcraft")));
assert!(roots.contains(&program_files.join("ArtCraft").join("GridCraft")));
}
assert!(
fixture
.check(Platform::Windows, &PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/GridCraft/nightly"))
.is_err()
);
assert!(fixture.check(Platform::Windows, &fixture.home().join(".gridcraft/nightly")).is_err());
for key in ["ProgramW6432", "ProgramFiles", "ProgramFiles(x86)"] {
let base = fixture.root.join(format!("machine {key}"));
fixture.env.insert(key.into(), base.clone().into_os_string());
assert!(fixture.check(Platform::Windows, &base.join("ArtCraft/GridCraft/nightly")).is_err(), "{key}");
assert!(!base.join("ArtCraft/GridCraft").exists());
#[cfg(all(unix, not(target_os = "macos")))]
{
assert!(roots.contains(&PathBuf::from("/usr/bin/gridcraft")));
assert!(roots.contains(&PathBuf::from("/usr/local/bin/gridcraft")));
assert!(roots.contains(&PathBuf::from("/opt/gridcraft")));
assert!(roots.contains(&home.join(".var/app/ai.storyteller.gridcraft")));
}
// Linux: the four XDG folders, then the stable Flatpak row and the token folder.
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
fixture.env.insert(key.into(), fixture.root.join(key).into_os_string());
#[cfg(target_os = "macos")]
{
assert!(roots.contains(&home.join("Library/Preferences/ai.storyteller.gridcraft.plist")));
assert!(roots.contains(&home.join("Library/Saved Application State/ai.storyteller.gridcraft.savedState")));
assert!(roots.contains(&home.join("Applications/GridCraft.app")));
assert!(roots.contains(&PathBuf::from("/Applications/GridCraft.app")));
}
for key in ["XDG_CONFIG_HOME", "XDG_DATA_HOME", "XDG_CACHE_HOME", "XDG_STATE_HOME"] {
let stable = PathBuf::from(fixture.get(key).unwrap()).join("gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("stable-sentinel"), b"stable bytes").unwrap();
for candidate in [stable.clone(), stable.join("nightly"), stable.parent().unwrap().to_path_buf()] {
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("overlap"), "{key}");
}
assert_eq!(std::fs::read(stable.join("stable-sentinel")).unwrap(), b"stable bytes");
let _ = (&local, &program_files);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_enforces_folder_entries() {
let tmp = TempDir::new("reopen");
let private = tmp.path().join("nightly-profile");
let spec = app_spec();
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
for name in ["ui.json", "prefs.json", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.gridcraft/data")).is_err());
assert!(fixture.check(Platform::Linux, &fixture.home().join(".var/app/ai.storyteller.launcher/nightly")).is_ok());
assert!(fixture.check(Platform::Linux, Path::new("/usr/bin/gridcraft/../gridcraft-nightly")).is_err(), "parent traversal is refused");
// macOS: the four Library rows and the bundle itself.
for suffix in [
"Application Support/GridCraft",
"Caches/GridCraft",
"Preferences/GridCraft",
"Saved Application State/ai.storyteller.gridcraft.savedState",
] {
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library").join(suffix).join("nightly")).is_err(), "{suffix}");
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(validate_and_prepare_root(&private, &spec).unwrap(), private);
assert_eq!(std::fs::read(private.join("ui.json")).unwrap(), b"saved profile data");
for name in PROFILE_FOLDERS {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(
matches!(validate_and_prepare_root(&private, &spec), Err(ProfileError::ExpectedDirectoryEntry(_))),
"{name} must stay a directory"
);
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
#[test]
fn the_launcher_profile_row_is_accepted_on_every_platform() {
let fixture = Fixture::new();
let data = fixture.root.join("Launcher/nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert_eq!(fixture.check(platform, &data).unwrap(), data);
}
assert!(
fixture
.check(
Platform::Linux,
&PathBuf::from(fixture.get("LOCALAPPDATA").unwrap()).join("Programs/ArtCraft/ArtCraftLauncher/nightly/gridcraft")
)
.is_ok(),
"the Launcher's own folder is not GridCraft's install"
);
}
fn extra_forbidden_root_overlap_and_traversal_are_refused() {
let tmp = TempDir::new("forbidden");
let forbidden = tmp.path().join("stable-boundary");
let mut spec = app_spec();
spec.extra_forbidden_roots.push(forbidden.clone());
#[test]
fn overlap_check_handles_ancestor_descendant_and_prefix_lookalikes() {
let fixture = Fixture::new();
let root = fixture.home().join("nightly/profiles/gridcraft");
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(overlaps(&root, &root.join("Control"), platform));
assert!(overlaps(&root.join("Control"), &root, platform));
assert!(!overlaps(&root, &root.with_file_name("gridcraft-other"), platform));
}
}
assert!(matches!(validate_and_prepare_root(&forbidden, &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(matches!(validate_and_prepare_root(&forbidden.join("nightly"), &spec), Err(ProfileError::ForbiddenRootOverlap { .. })));
assert!(!forbidden.exists());
#[test]
fn the_install_folder_of_the_running_build_is_refused() {
let fixture = Fixture::new();
for platform in [Platform::Windows, Platform::Linux, Platform::Mac] {
assert!(fixture.check(platform, &fixture.exe.parent().unwrap().join("profile")).is_err());
}
}
#[test]
fn mac_fences_the_whole_bundle_not_just_its_macos_folder() {
let mut fixture = Fixture::new();
fixture.exe = fixture.root.join("install/GridCraft Nightly.app/Contents/MacOS/GridCraft");
std::fs::create_dir_all(fixture.exe.parent().unwrap()).unwrap();
std::fs::write(&fixture.exe, b"fixture executable, never run").unwrap();
let inside_resources = fixture.exe.parent().unwrap().parent().unwrap().join("Resources/profile");
assert!(fixture.check(Platform::Mac, &inside_resources).unwrap_err().contains("overlap"));
assert!(!inside_resources.exists());
assert!(fixture.check(Platform::Mac, &fixture.home().join("Library/Application Support/ArtCraft/nightly/profiles/gridcraft")).is_ok());
}
#[test]
fn ambiguous_environment_and_non_native_sandbox_are_refused_before_creation() {
let mut fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
fixture.env.insert("XDG_CACHE_HOME".into(), "relative/cache".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("absolute"));
fixture.env.remove("XDG_CACHE_HOME");
fixture.env.insert("FLATPAK_ID".into(), "ai.storyteller.gridcraft".into());
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("Flatpak"));
fixture.env.remove("FLATPAK_ID");
fixture.env.remove("HOME");
assert!(fixture.check(Platform::Linux, &candidate).unwrap_err().contains("HOME"));
assert!(!candidate.exists());
}
#[test]
fn only_the_nightly_s_own_flatpak_instance_may_carry_a_profile() {
let mut fixture = Fixture::new();
let root = fixture.root.join("flatpak profile");
for (id, accepted) in [
(gridcraft_ui_egui::channel::NIGHTLY_PACKAGE_ID, true),
// The stable Flatpak, and a lookalike that only shares the prefix, stay refused.
("ai.storyteller.gridcraft", false),
("ai.storyteller.gridcraft.nightly-v1", false),
("io.github.other.Gridcraft", false),
] {
fixture.env.insert("FLATPAK_ID".into(), id.into());
let result = fixture.check(Platform::Linux, &root);
assert_eq!(result.is_ok(), accepted, "{id}");
let _ = std::fs::remove_dir_all(&root);
}
}
#[test]
fn failed_write_probe_never_falls_back_to_stable() {
let fixture = Fixture::new();
let candidate = fixture.home().join("nightly/profiles/gridcraft");
let result = fixture.check_with(Platform::Linux, &candidate, |_| Err(std::io::Error::other("read-only mount")));
assert!(result.unwrap_err().contains("not writable"));
assert!(candidate.is_dir(), "a created profile is not rolled back onto stable data");
assert!(!fixture.home().join(".config/gridcraft").exists());
}
#[test]
fn a_file_in_place_of_the_profile_is_refused() {
let fixture = Fixture::new();
let candidate = fixture.root.join("not-a-directory");
std::fs::write(&candidate, b"a file, not a profile").unwrap();
assert!(fixture.check(Platform::Linux, &candidate).is_err());
assert_eq!(std::fs::read(&candidate).unwrap(), b"a file, not a profile");
}
#[cfg(unix)]
#[test]
fn profile_entry_aliases_must_stay_inside_the_profile() {
let fixture = Fixture::new();
let stable = fixture.home().join(".config/gridcraft");
std::fs::create_dir_all(&stable).unwrap();
std::fs::write(stable.join("ui.json"), b"stable settings").unwrap();
for name in ["ui.json", "logs", "Control", "profile"] {
let private = fixture.root.join(format!("nightly-{name}"));
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&stable, private.join(name)).unwrap();
let probed = std::cell::Cell::new(false);
let result = fixture.check_with(Platform::Linux, &private, |_| {
probed.set(true);
Ok(())
});
assert!(result.is_err(), "{name} must not lead outside the profile");
assert!(!probed.get());
}
let private = fixture.root.join("nightly-inside");
std::fs::create_dir_all(private.join("real-logs")).unwrap();
std::fs::write(private.join("ui.json"), b"{}").unwrap();
std::os::unix::fs::symlink(private.join("real-logs"), private.join("logs")).unwrap();
assert!(fixture.check(Platform::Linux, &private).is_ok(), "links that stay inside are fine");
assert_eq!(std::fs::read(stable.join("ui.json")).unwrap(), b"stable settings");
assert_eq!(std::fs::read_dir(&stable).unwrap().count(), 1);
}
#[cfg(unix)]
#[test]
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let fixture = Fixture::new();
let outside = fixture.home().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = fixture.root.join("nightly-control");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
assert!(control_directory(&private).is_err());
assert!(fixture.check(Platform::Linux, &private).is_err());
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
assert!(matches!(validate_and_prepare_root(Path::new("relative/profile"), &spec), Err(ProfileError::RelativeProfileRoot(_))));
assert!(matches!(validate_and_prepare_root(&tmp.path().join("a/../b"), &spec), Err(ProfileError::ParentTraversalInProfileRoot(_))));
}
#[test]
fn the_control_folder_is_a_private_lazy_subfolder() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
let tmp = TempDir::new("control");
let private = validate_and_prepare_root(&tmp.path().join("nightly-profile"), &app_spec()).unwrap();
let control = control_directory(&private).unwrap();
assert!(control.starts_with(&private) && control != private);
assert!(!control.exists(), "resolving it must not create it");
assert_eq!(control.file_name().unwrap(), CONTROL_DIR);
}
#[cfg(unix)]
#[test]
fn the_writable_probe_leaves_nothing_behind() {
let fixture = Fixture::new();
let private = fixture.check(Platform::Linux, &fixture.home().join("nightly/profile")).unwrap();
ensure_writable(&private).unwrap();
assert_eq!(std::fs::read_dir(&private).unwrap().count(), 0);
fn a_control_folder_alias_cannot_redirect_the_token_outside_the_profile() {
let tmp = TempDir::new("control-symlink");
let outside = tmp.path().join("shared-tokens");
std::fs::create_dir_all(&outside).unwrap();
let private = tmp.path().join("nightly-control");
std::fs::create_dir(&private).unwrap();
std::os::unix::fs::symlink(&outside, private.join(CONTROL_DIR)).unwrap();
assert!(control_directory(&private).is_err());
assert!(matches!(validate_and_prepare_root(&private, &app_spec()), Err(ProfileError::SymlinkEntry(_))));
assert_eq!(std::fs::read_dir(&outside).unwrap().count(), 0);
}
}
+4 -1
View File
@@ -324,10 +324,13 @@ fn read_plain(name: &str, bytes: &[u8], csv_as_text: bool) -> Result<(Workbook,
let mut wb: Workbook = craft_gridcraft_format::read(bytes).map_err(|e| EngineError::Other(e.to_string()))?;
wb.styles.rebuild_index();
if wb.sheets.is_empty() {
// The file's macros are read after this (`macros::load`), so they come along.
// The file's macros are read after this (`macros::load`), so they come along, and
// so do its text defaults: a save would otherwise lose them.
let macros = std::mem::take(&mut wb.macros_read);
let text_defaults = std::mem::take(&mut wb.text_defaults);
wb = Workbook::new();
wb.macros_read = macros;
wb.text_defaults = text_defaults;
}
// The file's band placement and cell count are derived state: rebuild them from the
// cells themselves, dropping what is outside the sheet grid (#1008).
+22
View File
@@ -1100,3 +1100,25 @@ fn the_merge_index_holds_a_bounded_number_of_cells() {
sh.merges = vec![RangeRef::new(CellRef::new(0, 0), CellRef::new(1_000_000, 0))];
assert!(merge_index(&sh, rect).is_none());
}
#[test]
fn json_without_sheets_keeps_its_text_defaults() -> std::result::Result<(), Box<dyn std::error::Error>> {
// Saved and opened as GridCraft JSON, with the sheet list emptied in between: the reset to a
// new workbook carries the text defaults across with the macros.
let mut saved = Workbook::new();
saved.text_defaults.asian = gridcraft_model::ScriptDefault {
language: Some("ja".into()),
country: Some("JP".into()),
font: Some("Noto Sans CJK JP".into()),
..Default::default()
};
saved.macros.push(gridcraft_model::Macro { name: "Totals".into(), ..Default::default() });
let mut v: serde_json::Value = serde_json::from_slice(&save_bytes(&saved, "book.json")?)?;
v["sheets"] = serde_json::json!([]);
let (wb, warnings) = open_bytes("book.json", v.to_string().as_bytes())?;
assert!(warnings.is_empty(), "{warnings:?}");
assert!(!wb.sheets.is_empty(), "a workbook without sheets opens as a new one");
assert_eq!(wb.text_defaults, saved.text_defaults);
assert_eq!(wb.macros, saved.macros);
Ok(())
}
+1 -1
View File
@@ -32,7 +32,7 @@ pub use style::{
};
pub use workbook::{
CalcMode, CalcSettings, DefinedName, DocProps, EQUATION_BUDGET_MESSAGE, MAX_EQUATION_LAYOUT_BYTES, PhoneticProps, PhoneticRun, PhoneticString,
RefHost, ShowObjects, Workbook, WorkbookView, WriteReservation,
RefHost, ScriptDefault, ShowObjects, TextDefaults, Workbook, WorkbookView, WriteReservation,
};
/// Font used for new workbooks. Only a name: renderers substitute an available open font
+109
View File
@@ -144,6 +144,56 @@ pub struct DefinedName {
pub hidden: bool,
}
/// The language, script, country and font a document gives one script's text by default, each
/// `None` when unstated. Codes are as files spell them (`de`/`DE`; ODF states "no language" as
/// language `zxx` with country `none`). ODF 1.2 and later can also state a script code (`Latn` in `sr-Latn-RS`) and a full
/// BCP 47 tag for locales the separate codes cannot express (`ca-ES-valencia`); both are kept so
/// such a locale survives open and save.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ScriptDefault {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub language: Option<String>,
/// ISO 15924 script code (ODF `fo:script`, `style:script-asian`, `style:script-complex`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub script: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub country: Option<String>,
/// BCP 47 language tag (ODF `style:rfc-language-tag`, `-asian`, `-complex`).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub rfc_language_tag: Option<String>,
/// The font family name (not an ODF `style:font-face` declaration name: a reader resolves
/// `style:font-name-asian`/`-complex` to its family, a writer declares a face for it). Read
/// for Asian and complex text only; Western text takes the default style's font, so
/// `western.font` is unused.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub font: Option<String>,
}
impl ScriptDefault {
pub fn is_empty(&self) -> bool {
self.language.is_none() && self.script.is_none() && self.country.is_none() && self.rfc_language_tag.is_none() && self.font.is_none()
}
}
/// Default language and fonts of Western, Asian (CJK) and complex (right-to-left, Indic) text.
/// Empty unless a reader for a format that states them fills them (OpenDocument puts them on
/// its default cell style); Excel has no equivalent, so XLSX neither reads nor writes them.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct TextDefaults {
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
pub western: ScriptDefault,
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
pub asian: ScriptDefault,
#[serde(default, skip_serializing_if = "ScriptDefault::is_empty")]
pub complex: ScriptDefault,
}
impl TextDefaults {
pub fn is_empty(&self) -> bool {
self.western.is_empty() && self.asian.is_empty() && self.complex.is_empty()
}
}
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct DocProps {
pub title: String,
@@ -266,6 +316,11 @@ pub struct Workbook {
/// Shared between snapshots, as nothing changes them.
#[serde(skip)]
pub macros_unread: Arc<Vec<serde_json::Value>>,
/// The language and fonts the document gives text of each script by default (an
/// OpenDocument file's default cell style). Empty until a reader for a format that states
/// them fills them.
#[serde(default, skip_serializing_if = "TextDefaults::is_empty")]
pub text_defaults: TextDefaults,
/// Unmodelled file content kept for saving (package root and workbook level). Not in JSON.
#[serde(skip)]
pub preserved: Option<Arc<crate::preserved::Preserved>>,
@@ -585,6 +640,7 @@ impl Workbook {
macros: crate::macros::Macros::default(),
macros_read: vec![],
macros_unread: Arc::default(),
text_defaults: TextDefaults::default(),
preserved: None,
source_dir: None,
region: gridcraft_core::region::default_region(),
@@ -847,6 +903,59 @@ mod tests {
Ok(())
}
#[test]
fn text_defaults_round_trip_in_json_and_are_skipped_when_empty() -> Result<(), Box<dyn std::error::Error>> {
let mut wb = Workbook::new();
assert!(wb.text_defaults.is_empty(), "new workbooks state no text defaults");
// A workbook without them serialises exactly as before the field existed.
let json = serde_json::to_string(&wb)?;
let value: serde_json::Value = serde_json::from_str(&json)?;
assert!(value.get("text_defaults").is_none(), "empty text defaults are not written");
// JSON written before the field existed still loads, with empty defaults.
assert!(serde_json::from_str::<Workbook>(&json)?.text_defaults.is_empty());
wb.text_defaults = TextDefaults {
western: ScriptDefault {
language: Some("sr".into()),
script: Some("Latn".into()),
country: Some("RS".into()),
rfc_language_tag: Some("sr-Latn-RS".into()),
font: None,
},
asian: ScriptDefault {
language: Some("ja".into()),
country: Some("JP".into()),
font: Some("Noto Sans CJK JP".into()),
..Default::default()
},
complex: ScriptDefault { font: Some("Noto Naskh Arabic".into()), ..Default::default() },
};
assert!(!wb.text_defaults.is_empty());
let json = serde_json::to_string(&wb)?;
assert_eq!(serde_json::from_str::<Workbook>(&json)?.text_defaults, wb.text_defaults);
// Unstated parts stay out of the JSON.
let value: serde_json::Value = serde_json::from_str(&json)?;
let td = value.get("text_defaults").ok_or("text_defaults written")?;
assert!(td["western"].get("font").is_none());
assert!(td["complex"].get("language").is_none());
assert!(td["asian"].get("script").is_none() && td["asian"].get("rfc_language_tag").is_none());
assert_eq!(td["western"]["script"], "Latn");
assert_eq!(td["western"]["rfc_language_tag"], "sr-Latn-RS");
// A script that states only a script code or only a language tag is not empty.
assert!(!ScriptDefault { script: Some("Latn".into()), ..Default::default() }.is_empty());
assert!(!ScriptDefault { rfc_language_tag: Some("ca-ES-valencia".into()), ..Default::default() }.is_empty());
// Only one script stated: the others are skipped and load back empty.
wb.text_defaults =
TextDefaults { asian: ScriptDefault { font: Some("Noto Serif CJK SC".into()), ..Default::default() }, ..Default::default() };
let json = serde_json::to_string(&wb)?;
let value: serde_json::Value = serde_json::from_str(&json)?;
let td = value.get("text_defaults").ok_or("text_defaults written")?;
assert!(td.get("western").is_none() && td.get("complex").is_none());
assert_eq!(serde_json::from_str::<Workbook>(&json)?.text_defaults, wb.text_defaults);
Ok(())
}
#[test]
fn sheet_names() {
let wb = Workbook::new();
+2 -2
View File
@@ -26,8 +26,8 @@ mod font_setup;
pub use font_fallback::symbol_face_installed;
#[cfg(test)]
use font_fallback::{
PREFERRED_ARABIC, arabic, cjk_han_japanese, cjk_han_simplified, cjk_hangul, fallback_faces, hebrew, lao, load_faces, preferred_file,
symbols_more, thai,
Indic, PREFERRED_ARABIC, arabic, cjk_han_japanese, cjk_han_simplified, cjk_hangul, fallback_faces, hebrew, indic, lao, load_faces,
preferred_file, symbols_more, thai,
};
#[cfg(all(test, unix, not(target_os = "macos")))]
use font_fallback::{covers_arabic, fontconfig_arabic, parse_fc_match};
+96
View File
@@ -127,6 +127,15 @@ pub(super) fn fallback_faces(han: HanOrder) -> Vec<(&'static str, Vec<(String, u
("sys-lao", lao()),
("sys-hebrew", hebrew()),
("sys-arabic", arabic()),
("sys-devanagari", indic(Indic::Devanagari)),
("sys-bengali", indic(Indic::Bengali)),
("sys-gurmukhi", indic(Indic::Gurmukhi)),
("sys-gujarati", indic(Indic::Gujarati)),
("sys-odia", indic(Indic::Odia)),
("sys-tamil", indic(Indic::Tamil)),
("sys-telugu", indic(Indic::Telugu)),
("sys-kannada", indic(Indic::Kannada)),
("sys-malayalam", indic(Indic::Malayalam)),
("sys-symbols", symbols()),
("sys-symbols-2", symbols_more()),
]
@@ -330,6 +339,93 @@ pub(super) fn arabic() -> Vec<(String, u32)> {
v
}
/// The Indian scripts with a fallback face. epaint shapes every run with harfrust, so a face with
/// the script's OpenType tables is all conjuncts and reordered vowel signs need.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum Indic {
Devanagari,
Bengali,
Gurmukhi,
Gujarati,
Odia,
Tamil,
Telugu,
Kannada,
Malayalam,
}
/// Indian-script faces. Windows' Nirmala UI covers all nine scripts (loaded once, see
/// [`load_fallback`]), with the older per-script faces behind it; macOS ships Kohinoor, Noto and
/// Sangam MN faces; Linux and the BSDs usually have Noto Sans or Lohit.
/// A script's faces: Windows file, macOS files with the Regular face's index, Noto name, Lohit
/// directory and file.
#[cfg(not(target_arch = "wasm32"))]
type IndicFaces = (&'static str, &'static [(&'static str, u32)], &'static str, (&'static str, &'static str));
#[cfg(not(target_arch = "wasm32"))]
pub(super) fn indic(script: Indic) -> Vec<(String, u32)> {
let mac_sys = "/System/Library/Fonts";
let mac_sup = "/System/Library/Fonts/Supplemental";
let win = windows_fonts();
// (Windows face, macOS faces with the Regular face's index, Noto name, Lohit directory and file)
let (win_face, mac, noto, lohit): IndicFaces = match script {
Indic::Devanagari => (
"mangal.ttf",
&[("{sys}/Kohinoor.ttc", 0), ("{sup}/Devanagari Sangam MN.ttc", 0), ("{sup}/ITFDevanagari.ttc", 0)],
"Devanagari",
("lohit-devanagari", "Lohit-Devanagari"),
),
Indic::Bengali => {
("vrinda.ttf", &[("{sys}/KohinoorBangla.ttc", 0), ("{sup}/Bangla Sangam MN.ttc", 0)], "Bengali", ("lohit-bengali", "Lohit-Bengali"))
}
Indic::Gurmukhi => {
("raavi.ttf", &[("{sup}/Gurmukhi Sangam MN.ttc", 0), ("{sup}/Gurmukhi MN.ttc", 0)], "Gurmukhi", ("lohit-punjabi", "Lohit-Gurmukhi"))
}
Indic::Gujarati => (
"shruti.ttf",
&[("{sys}/KohinoorGujarati.ttc", 3), ("{sup}/Gujarati Sangam MN.ttc", 0)],
"Gujarati",
("lohit-gujarati", "Lohit-Gujarati"),
),
Indic::Odia => ("kalinga.ttf", &[("{sys}/NotoSansOriya.ttc", 0), ("{sup}/Oriya Sangam MN.ttc", 0)], "Oriya", ("lohit-oriya", "Lohit-Odia")),
Indic::Tamil => ("latha.ttf", &[("{sup}/Tamil Sangam MN.ttc", 0), ("{sup}/Tamil MN.ttc", 0)], "Tamil", ("lohit-tamil", "Lohit-Tamil")),
Indic::Telugu => {
("gautami.ttf", &[("{sys}/KohinoorTelugu.ttc", 0), ("{sup}/Telugu Sangam MN.ttc", 0)], "Telugu", ("lohit-telugu", "Lohit-Telugu"))
}
Indic::Kannada => {
("tunga.ttf", &[("{sys}/NotoSansKannada.ttc", 3), ("{sup}/Kannada Sangam MN.ttc", 0)], "Kannada", ("lohit-kannada", "Lohit-Kannada"))
}
Indic::Malayalam => (
"kartika.ttf",
&[("{sup}/Malayalam Sangam MN.ttc", 0), ("{sup}/Malayalam MN.ttc", 0)],
"Malayalam",
("lohit-malayalam", "Lohit-Malayalam"),
),
};
let mut v: Vec<(String, u32)> = vec![(format!("{win}\\Nirmala.ttc"), 0), (format!("{win}\\Nirmala.ttf"), 0), (format!("{win}\\{win_face}"), 0)];
v.extend(mac.iter().map(|(m, index)| (m.replace("{sys}", mac_sys).replace("{sup}", mac_sup), *index)));
let mut linux: Vec<String> = Vec::new();
for d in ["truetype/noto", "opentype/noto", "google-noto", "noto", "TTF"] {
linux.push(format!("{d}/NotoSans{noto}-Regular.ttf"));
}
// Fedora ships the variable Noto Sans faces; their default instance is Regular.
linux.push(format!("google-noto-vf/NotoSans{noto}[wght].ttf"));
let (dir, file) = lohit;
for d in ["truetype/", ""] {
linux.push(format!("{d}{dir}/{file}.ttf"));
}
// The system fonts, then the same layouts under a Flatpak sandbox's read-only host mounts.
for root in ["/usr/share/fonts", "/run/host/fonts"] {
v.extend(linux.iter().map(|f| (format!("{root}/{f}"), 0)));
}
for root in ["/usr/local/share/fonts", "/run/host/local-fonts"] {
v.push((format!("{root}/noto/NotoSans{noto}-Regular.ttf"), 0));
v.push((format!("{root}/{dir}/{file}.ttf"), 0));
}
v
}
/// Symbol faces behind the UI font. Interface fonts such as Noto Sans and Cantarell (and egui's
/// built-in Ubuntu) lack arrows, check marks, geometric shapes and keyboard symbols (▾ ✓ ✕ ▲ ↳ ⇧),
/// which then render as empty boxes (#197, #54). DejaVu Sans covers most of them; the paths cover
+129 -3
View File
@@ -122,11 +122,49 @@ fn language_reorders_only_the_han_faces() {
let keys = |han| fallback_faces(han).into_iter().map(|(k, _)| k).collect::<Vec<_>>();
assert_eq!(
keys(HanOrder::Japanese),
["sys-cjk-han-ja", "sys-cjk-han-zh", "sys-cjk-hangul", "sys-thai", "sys-lao", "sys-hebrew", "sys-arabic", "sys-symbols", "sys-symbols-2"]
[
"sys-cjk-han-ja",
"sys-cjk-han-zh",
"sys-cjk-hangul",
"sys-thai",
"sys-lao",
"sys-hebrew",
"sys-arabic",
"sys-devanagari",
"sys-bengali",
"sys-gurmukhi",
"sys-gujarati",
"sys-odia",
"sys-tamil",
"sys-telugu",
"sys-kannada",
"sys-malayalam",
"sys-symbols",
"sys-symbols-2"
]
);
assert_eq!(
keys(HanOrder::Chinese),
["sys-cjk-han-zh", "sys-cjk-han-ja", "sys-cjk-hangul", "sys-thai", "sys-lao", "sys-hebrew", "sys-arabic", "sys-symbols", "sys-symbols-2"]
[
"sys-cjk-han-zh",
"sys-cjk-han-ja",
"sys-cjk-hangul",
"sys-thai",
"sys-lao",
"sys-hebrew",
"sys-arabic",
"sys-devanagari",
"sys-bengali",
"sys-gurmukhi",
"sys-gujarati",
"sys-odia",
"sys-tamil",
"sys-telugu",
"sys-kannada",
"sys-malayalam",
"sys-symbols",
"sys-symbols-2"
]
);
assert_eq!(HanOrder::of(Language::Ja), HanOrder::Japanese);
for l in [Language::En, Language::Zh, Language::Ko, Language::Ru, Language::PtBr, Language::De, Language::Cs, Language::Fr, Language::Tr] {
@@ -185,7 +223,7 @@ fn fallback_covers_its_script() {
// face or the optional craft-fonts input provides one; the printed skip is a recorded
// gate, and a present face that is not wired in fails.
type Case = (&'static str, Vec<(String, u32)>, &'static str);
let cases: [Case; 11] = [
let cases: [Case; 20] = [
("sys-cjk-han-ja", cjk_han_japanese(), "カテゴリ"),
// Chinese uses a system Han face or the native-only permitted LXGW craft face; the
// barred Noto CJK collection never supplies it.
@@ -195,6 +233,16 @@ fn fallback_covers_its_script() {
("sys-lao", lao(), "ພາສາລາວ"),
("sys-hebrew", hebrew(), "עברית"),
("sys-arabic", arabic(), "العربية١٢٣"),
// Indian scripts, each with a conjunct or a vowel sign the shaper has to place.
("sys-devanagari", indic(Indic::Devanagari), "हिन्दी क्षेत्र"),
("sys-bengali", indic(Indic::Bengali), "বাংলা ক্ষেত্র"),
("sys-gurmukhi", indic(Indic::Gurmukhi), "ਪੰਜਾਬੀ"),
("sys-gujarati", indic(Indic::Gujarati), "ગુજરાતી"),
("sys-odia", indic(Indic::Odia), "ଓଡ଼ିଆ"),
("sys-tamil", indic(Indic::Tamil), "தமிழ் கொண்டு"),
("sys-telugu", indic(Indic::Telugu), "తెలుగు"),
("sys-kannada", indic(Indic::Kannada), "ಕನ್ನಡ"),
("sys-malayalam", indic(Indic::Malayalam), "മലയാളം"),
("craft-noto-sans-arabic", Vec::new(), "مرحبا"),
("craft-noto-sans-georgian", Vec::new(), "ქართული"),
("ui", candidates(UI), "Русский"),
@@ -489,3 +537,81 @@ fn fedora_package_folders_are_searched_after_the_other_linux_layouts() {
let noto = mono.iter().position(|p| p == "/usr/share/fonts/google-noto-vf/NotoSansMono[wght].ttf");
assert!(noto.is_some() && noto.unwrap_or(0) + 1 == mono.len(), "Fedora's default Noto Sans Mono must be the last resort: {mono:?}");
}
#[test]
fn indic_text_is_shaped_not_drawn_letter_by_letter() {
// epaint shapes each run with harfrust, so with a face in the chain a conjunct is one glyph
// and a split vowel sign is drawn on both sides of its consonant. Drawn per character, क्ष
// would show three glyphs (क, a visible virama, ष) and கொ two.
let ctx = egui::Context::default();
ctx.set_fonts(font_definitions());
let mut out = ctx.run_ui(egui::RawInput::default(), |_ui| {});
out.textures_delta.clear(); // nothing consumes the atlas in a headless test
let drawn = |text: &str| {
let galley = ctx.fonts_mut(|f| f.layout_no_wrap(text.to_owned(), FontId::proportional(14.0), Color32::BLACK));
galley.rows.iter().flat_map(|r| r.glyphs.iter()).filter(|g| g.uv_rect.size.x > 0.0).count()
};
let has = |script| indic(script).iter().any(|(p, _)| std::path::Path::new(p).exists());
if has(Indic::Devanagari) {
assert_eq!(drawn("क्ष"), 1, "क + virama + ष forms the conjunct क्ष");
}
if has(Indic::Tamil) {
// Shaped, the split vowel sign is either drawn on both sides of க (3 glyphs) or ligated with
// it (1, Nirmala UI); one glyph per code point (2) means no shaping.
assert_ne!(drawn("கொ"), 2, "the vowel sign ொ is shaped around க");
}
}
#[test]
fn indic_faces_are_regular_weight() {
// A family collection's face order is not alphabetical by weight (macOS's Kohinoor Gujarati
// starts with Bold, Noto Sans Kannada with Thin), so each candidate names its Regular face.
use skrifa::MetadataProvider;
let scripts = [
Indic::Devanagari,
Indic::Bengali,
Indic::Gurmukhi,
Indic::Gujarati,
Indic::Odia,
Indic::Tamil,
Indic::Telugu,
Indic::Kannada,
Indic::Malayalam,
];
for script in scripts {
for (path, index) in indic(script) {
let Ok(bytes) = std::fs::read(&path) else { continue };
let Ok(font) = skrifa::FontRef::from_index(&bytes, index) else { continue };
let weight = font.attributes().weight.value();
assert!((350.0..=500.0).contains(&weight), "{script:?}: {path} face {index} has weight {weight}");
}
}
}
#[test]
fn indic_faces_reach_fedora_and_flatpak_layouts() {
// Fedora installs only the variable Noto Sans faces; a Flatpak sees the host's fonts under
// /run/host. Missing either leaves the interface in tofu boxes there.
let cases = [
(Indic::Devanagari, "Devanagari"),
(Indic::Bengali, "Bengali"),
(Indic::Gurmukhi, "Gurmukhi"),
(Indic::Gujarati, "Gujarati"),
(Indic::Odia, "Oriya"),
(Indic::Tamil, "Tamil"),
(Indic::Telugu, "Telugu"),
(Indic::Kannada, "Kannada"),
(Indic::Malayalam, "Malayalam"),
];
for (script, noto) in cases {
let paths: Vec<String> = indic(script).into_iter().map(|(path, _)| path).collect();
for expected in [
format!("/usr/share/fonts/google-noto-vf/NotoSans{noto}[wght].ttf"),
format!("/run/host/fonts/google-noto-vf/NotoSans{noto}[wght].ttf"),
format!("/run/host/fonts/truetype/noto/NotoSans{noto}-Regular.ttf"),
format!("/run/host/local-fonts/noto/NotoSans{noto}-Regular.ttf"),
] {
assert!(paths.contains(&expected), "{script:?} doesn't probe {expected}");
}
}
}
File diff suppressed because one or more lines are too long
+5 -5
View File
@@ -75,12 +75,12 @@ Cell text now uses shared Unicode bidi layout while retaining logical source ind
embedded faces tagged with CJK scripts share the Latin baseline in cells, editors and titles
(#1265, #2621); other script, emoji and symbol fallbacks retain their alignment.
Lao falls back to Lao Sangam MN / Lao MN (macOS),
Leelawadee UI / DokChampa (Windows) or Noto Sans Lao / Phetsarath OT (Linux). egui uses harfrust shaping and Unicode bidi layout; script-specific coverage
beyond Arabic still needs verification. **Sheet Right-to-Left**
Leelawadee UI / DokChampa (Windows) or Noto Sans Lao / Phetsarath OT (Linux). Arabic falls back to a system Arabic face, fontconfig's
Arabic choice or craft-fonts' Noto Sans Arabic; fontconfig's choice leads these fallbacks, but a UI font with Arabic of its
own (DejaVu Sans in the Flatpak) still draws interface Arabic (#229). There is no complex-text shaping: Arabic and
Devanagari don't join or reorder, and there is no bidirectional layout. **Sheet Right-to-Left**
own (DejaVu Sans in the Flatpak) still draws interface Arabic (#229). Indian scripts fall back to Nirmala UI and the
per-script faces (Windows), Kohinoor, Noto and Sangam MN (macOS) or Noto Sans and Lohit (Linux, BSD, Flatpak). egui uses
harfrust shaping and Unicode bidi layout, so conjuncts and reordered vowel signs render wherever a face is present
(`theme::tests::indic_text_is_shaped_not_drawn_letter_by_letter`). **Sheet Right-to-Left**
(`view.rightToLeft`, Page Layout › Sheet Options, XLSX `rightToLeft`, `.xls` WINDOW2 fRightToLeft) mirrors the grid (#146):
column A and the row headers on the right, the vertical scrollbar on the left; hit-testing,
arrow keys, editor, popups and floating objects follow; text follows its cell reading direction inside its box,
@@ -107,7 +107,7 @@ separators, number/date formats, machine translation with agent review, and scri
| English | en | ~2,200 / ~2,200 (100%, source) | yes | Latin: yes | yes | full | — |
| Simplified Chinese (Mandarin) | zh-Hans | 266 (~12%) | no | CJK system-font fallback (#38); IME unverified; PDF can't export | no | menus only | 8–13 h |
| Spanish | es | 0 (0%) | no | Latin: yes | no | none | 6–10 h |
| Hindi | hi | 0 (0%) | no | Devanagari: **no shaping** | no | none | 12–18 h |
| Hindi | hi | 0 (0%) | no | Devanagari: shaped, system faces | no | none | 12–18 h |
| Arabic | ar | 0 (0%) | no | shared shaping/bidi; no Arabic UI catalog or mirrored shell; PDF export: shaped and joined, follows cell direction, mirrors RTL sheets; Sheet RTL mirrors the grid (#146) | no | none | 25–35 h |
| French | fr | 0 (0%) | no | Latin: yes | no | none | 6–10 h |
| Portuguese | pt-BR | 943 (~43%) | dialogs and tooltips (dialogs take effect with #669) | Latin: yes | no | menus, File view, dialogs | 2–4 h |
+16 -14
View File
@@ -6,6 +6,8 @@ Each entry is an Excel ribbon or menu command (feature names only). It counts as
**Overall: 282 / 296 commands implemented (95.3%).**
**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): 282 yes, 14 no (window 0, os 10, engine-gap 4), 0 partial, 0 unknown.** An implemented command is `headless: yes`: it is in the engine registry that `gridcraft-cli` and the MCP server load. A missing one carries its hand mark from `HEADLESS` in `xtask/src/parity.rs`, or `unknown`.
| Tab | Implemented | Total | Parity |
|---|---|---|---|
| File | 11 | 11 | 100% |
@@ -166,12 +168,12 @@ Implemented:
Missing:
- `insert.smartArt` Diagram (Illustrations)
- `insert.screenshot` Screenshot (Illustrations)
- `insert.map` Maps (Charts)
- `insert.timeline` Timeline (Filters)
- `insert.signatureLine` Signature Line (Text)
- `insert.object` Object (Text)
- `insert.smartArt` Diagram (Illustrations): headless: no, reach: engine-gap (diagrams could be built by a command)
- `insert.screenshot` Screenshot (Illustrations): headless: no, reach: os (screen capture of other windows)
- `insert.map` Maps (Charts): headless: no, reach: os (online map service)
- `insert.timeline` Timeline (Filters): headless: no, reach: engine-gap (a date filter for pivot tables could be a command)
- `insert.signatureLine` Signature Line (Text): headless: no, reach: engine-gap (a signature line object could be inserted by a command)
- `insert.object` Object (Text): headless: no, reach: os (embedding another program's object)
## Draw (4 / 4, 100%)
@@ -268,11 +270,11 @@ Implemented:
Missing:
- `data.fromWeb` From Web (Get & Transform Data)
- `data.stocks` Stocks (Data Types)
- `data.geography` Geography (Data Types)
- `data.relationships` Relationships (Data Tools)
- `data.analyzeData` Analyze Data (Analysis)
- `data.fromWeb` From Web (Get & Transform Data): headless: no, reach: os (fetching a web page)
- `data.stocks` Stocks (Data Types): headless: no, reach: os (online stock data service)
- `data.geography` Geography (Data Types): headless: no, reach: os (online geography data service)
- `data.relationships` Relationships (Data Tools): headless: no, reach: engine-gap (data-model relationships could be commands)
- `data.analyzeData` Analyze Data (Analysis): headless: no, reach: os (online analysis service)
## Review (15 / 18, 83%)
@@ -296,9 +298,9 @@ Implemented:
Missing:
- `review.smartLookup` Smart Lookup (Insights)
- `review.translate` Translate (Language)
- `review.showChanges` Show Changes (Changes)
- `review.smartLookup` Smart Lookup (Insights): headless: no, reach: os (online search service)
- `review.translate` Translate (Language): headless: no, reach: os (online translation service)
- `review.showChanges` Show Changes (Changes): headless: no, reach: os (co-authoring change history service)
## View (21 / 21, 100%)
@@ -297,7 +297,9 @@ class StagedFormats(unittest.TestCase):
desktop = (stage / "usr/share/applications/ai.storyteller.gridcraft.desktop").read_text()
self.assertIn("Exec=gridcraft %F\n", desktop)
self.assertIn("MimeType=", desktop)
with tarfile.open(self.dist / "gridcraft-0.19.1-linux-x86_64.tar.gz") as tar:
import tomllib
cargo_version = tomllib.loads((ROOT / "Cargo.toml").read_text())["workspace"]["package"]["version"]
with tarfile.open(self.dist / f"gridcraft-{cargo_version}-linux-x86_64.tar.gz") as tar:
names = {member.name.split("/", 1)[-1] for member in tar.getmembers()}
self.assertIn("bin/gridcraft", names)
self.assertNotIn("bin/gridcraft-nightly", names)
+3 -2
View File
@@ -33,11 +33,12 @@ OUTPUT="$DIST/gridcraft-$VERSION-macos-aarch64-nightly.zip"
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/GridCraft"
chmod 755 "$APP/Contents/MacOS/GridCraft"
cp "$ROOT/assets/app-icon/gridcraft-nightly.icns" "$APP/Contents/Resources/gridcraft-nightly.icns"
nightly_copy_notices "$APP/Contents/Resources"
# Launcher admits notices under Resources/docs, not beside the icon.
nightly_copy_notices "$APP/Contents/Resources/docs"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
+82 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
import base64
import importlib.util
import json
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"gridcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "GridCraft Nightly.app"
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
@@ -183,6 +185,50 @@ class Fixture:
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def package(self, font_licences):
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
source = HERE.parents[1]
checkout = self.root / "source"
checkout.mkdir()
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
"assets/app-icon/gridcraft-nightly.icns"):
target = checkout / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / relative, target)
env = self.env(**dict.fromkeys(SECRETS))
def git(*args):
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
git("init", "-q")
git("add", "--", ".")
git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.invalid", "commit", "-qm", "Packaging fixture")
commit = git("rev-parse", "HEAD").strip()
version = VERSION[:-12] + commit[:12]
# Generated licence text exercises the copier without depending on a font checkout.
fonts = self.root / "craft-fonts"
for family, data in font_licences.items():
licence = fonts / "fonts" / family / "OFL.txt"
licence.parent.mkdir(parents=True)
licence.write_bytes(data)
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
(self.bin / "cargo").write_text(
'#!/bin/sh\nset -eu\n'
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/gridcraft"\n'
'mkdir -p "$(dirname "$gui")"\n'
"printf \"#!/bin/sh\\necho 'GridCraft %s (nightly-v1)'\\n\" \"$GRIDCRAFT_VERSION\" >\"$gui\"\n",
)
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
GRIDCRAFT_BUILD_CHANNEL="nightly-v1", GRIDCRAFT_VERSION=version,
GRIDCRAFT_BUILD_SHA=commit, GRIDCRAFT_BUILD_DATE="2026-11-23")
assert result.returncode == 0, result.stdout
return self.dist / ASSET.replace(VERSION, version)
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
@@ -430,6 +476,40 @@ class Verify(unittest.TestCase):
class Build(unittest.TestCase):
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
f = Fixture(self)
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
archive = f.package(fonts)
source = HERE.parents[1]
resources = f"{APP}/Contents/Resources"
icon = "gridcraft-nightly.icns"
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
contents = f"{APP}/Contents"
gui = f"{contents}/MacOS/GridCraft"
with zipfile.ZipFile(archive) as zipped:
entries = zipped.infolist()
names = {entry.filename for entry in entries}
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
for path, data in expected_files.items():
with self.subTest(path=path):
self.assertEqual(zipped.read(path), data)
mode = zipped.getinfo(path).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode))
self.assertFalse(mode & 0o111)
mode = zipped.getinfo(gui).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
self.assertEqual(result.returncode, 0, result.stdout)
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
+32 -17
View File
@@ -171,7 +171,7 @@ def reviewed_manual_actors(caller_source, policy):
def caller_pin(name):
return re.findall(r"(?m)^ tooling-revision: ([0-9a-f]{40})$", (ROOT / ".github/workflows" / name).read_text())[0]
return re.findall(r"(?m)^ tooling-revision: (\S+)$", (ROOT / ".github/workflows" / name).read_text())[0]
class TrustedSourcePreparation(unittest.TestCase):
@@ -214,15 +214,22 @@ class TrustedSourcePreparation(unittest.TestCase):
(indicator, expression), = job_conditions(jobs)
self.assertFalse(indicator == ">-" and " ".join(expression.split()) == expected)
def test_no_nightly_schedule_is_registered(self):
for name, event in (("nightly.yml", "workflow_dispatch"),
("nightly-sign.yml", "workflow_dispatch")):
def test_nightly_triggers_match_reviewed_schedule(self):
expected_triggers = {
"nightly.yml": [" schedule:", " workflow_dispatch:"],
"nightly-sign.yml": [" workflow_dispatch:"],
"nightly-dispatch.yml": [" workflow_run:"],
}
for name, expected in expected_triggers.items():
source = (ROOT / ".github/workflows" / name).read_text()
events = source.split("\non:\n", 1)[1].split("\npermissions:", 1)[0]
triggers = [line for line in events.splitlines() if line.startswith(" ")
and not line.startswith(" ") and line.strip() and not line.lstrip().startswith("#")]
with self.subTest(workflow=name):
self.assertEqual(triggers, [f" {event}:"], "schedule/activation needs explicit review")
self.assertEqual(triggers, expected, "schedule/activation needs explicit review")
nightly = (ROOT / ".github/workflows/nightly.yml").read_text()
self.assertEqual(re.findall(r"(?m)^ - cron: '([^']+)'$", nightly), ["30 3 * * *"],
"scheduled nightly cadence must match the reviewed cron expression")
def test_signer_serialization_contract_is_enforced(self):
assert_nightly_serialization((ROOT / ".github/workflows/nightly-sign.yml").read_text())
@@ -258,17 +265,17 @@ class TrustedSourcePreparation(unittest.TestCase):
self.assertEqual(len(entries), len(expected), "duplicate fixture classification")
def test_no_cache_actions_or_cache_setup_options_in_app_trusted_closure(self):
for name in ("nightly.yml", "nightly-sign.yml"):
for name in ("nightly.yml", "nightly-dispatch.yml", "nightly-sign.yml"):
source = (ROOT / ".github/workflows" / name).read_text()
executable = "\n".join(line for line in source.splitlines()
if not line.lstrip().startswith("#"))
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
# The producer caller forwards nothing. The signer caller declares the release
# environment and forwards exactly the fifteen secrets the sign steps read; those
# The producer and dispatcher forward nothing. The signer caller declares no
# environment and forwards exactly the named secrets the sign steps read; those
# are the only allowed forms, and `inherit` is never one of them.
if name == "nightly.yml":
if name in ("nightly.yml", "nightly-dispatch.yml"):
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
else:
@@ -309,7 +316,7 @@ class TrustedSourcePreparation(unittest.TestCase):
self.assertEqual(tooling, uses, "the defining workflow SHA and tooling input must match")
pins.update(uses)
self.assertEqual(len(pins), 1, "producer and signer must pin the same shared commit")
self.assertRegex(pins.pop(), r"^[0-9a-f]{40}$", "pin a full immutable commit, never a branch or placeholder")
self.assertEqual(pins.pop(), "main", "pin storytold/craft-common-actions to @main")
class NightlyEnabledCallers(unittest.TestCase):
@@ -319,6 +326,7 @@ class NightlyEnabledCallers(unittest.TestCase):
"nightly.yml": "github.repository == 'storytold/gridcraft' && github.ref == 'refs/heads/main' && "
"github.ref_type == 'branch' && (github.event_name == 'schedule' || "
"github.event_name == 'workflow_dispatch')",
"nightly-dispatch.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_run'",
"nightly-sign.yml": "github.repository == 'storytold/gridcraft' && github.event_name == 'workflow_dispatch' && "
"github.ref == 'refs/heads/nightly-signer' && github.ref_type == 'branch'",
}
@@ -337,7 +345,8 @@ class NightlyEnabledCallers(unittest.TestCase):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
policy = json.loads(INSTALLED_POLICY.read_text())
self.assertEqual(reviewed_manual_actors(source, policy), RELEASE_MANAGERS)
self.assertEqual(policy["automatic_signer_actors"], [], "no automatic signer without a schedule")
self.assertEqual(policy["automatic_signer_actors"], ["github-actions[bot]"],
"automatic signer is limited to github-actions[bot]")
def test_an_actor_outside_the_release_managers_is_refused(self):
source = (ROOT / ".github/workflows/nightly.yml").read_text()
@@ -420,7 +429,8 @@ class NightlyInstalledPolicy(unittest.TestCase):
for platform, (field, value) in NIGHTLY_TRUST.items():
row = self.policy["platforms"][platform]
with self.subTest(platform=platform):
self.assertEqual(set(row), {"unsigned_artifact_name", "trust"})
expected_keys = {"unsigned_artifact_name", "trust", "package_formats"} if platform == "linux-x86_64" and "package_formats" in row else {"unsigned_artifact_name", "trust"}
self.assertEqual(set(row), expected_keys)
self.assertEqual(row["unsigned_artifact_name"], f"nightly-unsigned-{platform}")
self.assertEqual(row["trust"], {field: value})
@@ -739,7 +749,7 @@ def trust_closure_problems(workflows):
if workflow.lower() in ("nightly-release.yml", "nightly-release.yaml"):
if name == "nightly-sign.yml":
signer_calls += 1
if name != "nightly-sign.yml" or not re.fullmatch(r"[0-9a-f]{40}", ref):
if name != "nightly-sign.yml" or ref != "main":
problems.append(name + " calls nightly-release.yml@" + ref)
if workflow.lower() in ("release.yml", "release.yaml"):
stable_callers.add(name)
@@ -789,7 +799,7 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
"a double-quoted uses key in a flow mapping": {**tree, "extra.yml": 'jobs:\n x: {"uses": ' + SHARED + "nightly-release.yml@" + "a" * 40 + "}\n"},
"uses in any flow mapping": {**tree, "extra.yml": "jobs:\n x:\n steps:\n - {uses: actions/checkout@v4}\n"},
"another caller of the signer": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "nightly-release.yml@" + "a" * 40 + "\n"},
"a mutable signer pin": {**tree, "nightly-sign.yml": re.sub(r"nightly-release\.yml@[0-9a-f]{40}", "nightly-release.yml@main", tree["nightly-sign.yml"])},
"a signer caller on a non-main branch or tag ref": {**tree, "nightly-sign.yml": tree["nightly-sign.yml"].replace("nightly-release.yml@main", "nightly-release.yml@v1")},
"a new stable release caller": {**tree, "extra.yml": "jobs:\n x:\n uses: " + SHARED + "release.yml@main\n"},
"a stable caller on a branch or tag ref": {**tree, "release.yml": tree["release.yml"].replace(SHARED + "release.yml@main", SHARED + "release.yml@v1")},
}
@@ -811,9 +821,14 @@ class NightlySignerBranchTrustClosure(unittest.TestCase):
self.assertIn("github.ref == 'refs/heads/" + SIGNER_BRANCH + "'", guard)
self.assertNotIn("refs/heads/release", sign, "the signer no longer runs on the stable branch")
self.assertEqual(re.findall(r"(?m)^ app-name: (\S+)$", sign), ["gridcraft"], "the shared signer needs the reviewed registry app")
# This app ships no completion dispatcher yet: that workflow forwards scheduled producers
# only, and no schedule is approved. Adding it is part of a reviewed cadence change.
self.assertFalse(DISPATCHER.exists(), "a completion dispatcher needs its own reviewed activation")
self.assertTrue(DISPATCHER.exists(), "scheduled nightly requires the completion dispatcher")
dispatcher = DISPATCHER.read_text()
producer_name = re.findall(r"(?m)^name: (.+)$", (ROOT / ".github/workflows/nightly.yml").read_text())[0]
self.assertIn(f"workflows: [{producer_name}]", dispatcher, "dispatcher must match the producer workflow name")
self.assertIn("refs/heads/" + SIGNER_BRANCH, dispatcher, "dispatcher must target the signer branch")
self.assertIn("https://api.github.com/repos/storytold/gridcraft/actions/workflows/nightly-sign.yml/dispatches",
dispatcher, "dispatcher must target gridcraft nightly-sign.yml")
self.assertNotIn("false &&", dispatcher, "dispatcher must be enabled for scheduled runs")
self.assertEqual(json.loads(INSTALLED_POLICY.read_text())["release_branch"], SIGNER_BRANCH)
self.assertFalse((ROOT / "docs/nightly-signing-policy.example.json").exists(),
"a policy example must then name the signer branch")
+158 -2
View File
@@ -19,6 +19,89 @@ pub struct Entry {
pub done: bool,
}
/// RFC-0052 hand marks for catalog ids with no engine command: `id|headless|reach|why`.
///
/// `headless` is `no` or `partial`; `reach` is `window` (needs a desktop window, dialog or pointer),
/// `os` (needs an OS or online service the engine doesn't wrap) or `engine-gap` (could be an engine
/// command, isn't one yet). `yes` is never written here: an id is `yes` only when the engine registry
/// that `gridcraft-cli` and the MCP server load has it, and a mark on such an id is stale
/// (`mark_errors`). A missing id with no mark is `unknown`.
pub const HEADLESS: &str = "\
insert.smartArt|no|engine-gap|diagrams could be built by a command
insert.screenshot|no|os|screen capture of other windows
insert.map|no|os|online map service
insert.timeline|no|engine-gap|a date filter for pivot tables could be a command
insert.signatureLine|no|engine-gap|a signature line object could be inserted by a command
insert.object|no|os|embedding another program's object
data.fromWeb|no|os|fetching a web page
data.stocks|no|os|online stock data service
data.geography|no|os|online geography data service
data.relationships|no|engine-gap|data-model relationships could be commands
data.analyzeData|no|os|online analysis service
review.smartLookup|no|os|online search service
review.translate|no|os|online translation service
review.showChanges|no|os|co-authoring change history service
";
/// A row's RFC-0052 `headless:` value, and for `no`/`partial` its `reach:` and reason.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Headless<'a> {
pub value: &'a str,
pub reach: Option<&'a str>,
pub why: &'a str,
}
const YES: Headless<'static> = Headless { value: "yes", reach: None, why: "" };
const UNKNOWN: Headless<'static> = Headless { value: "unknown", reach: None, why: "" };
/// Parse `HEADLESS`-format marks. A malformed line, a hand-written `yes`, an unknown reach or a
/// repeated id is an error.
pub fn parse_marks(src: &str) -> Result<Vec<(&str, Headless<'_>)>, String> {
let mut out: Vec<(&str, Headless<'_>)> = Vec::new();
for line in src.lines().filter(|l| !l.trim().is_empty()) {
let f: Vec<&str> = line.splitn(4, '|').collect();
let [id, value, reach, why] = f[..] else {
return Err(format!("headless mark `{line}`: want `id|headless|reach|why`"));
};
if !matches!(value, "no" | "partial") {
return Err(format!("headless mark `{id}`: `{value}` is not `no` or `partial` (`yes` comes from the registry)"));
}
if !matches!(reach, "window" | "os" | "engine-gap") {
return Err(format!("headless mark `{id}`: reach `{reach}` is not window, os or engine-gap"));
}
if out.iter().any(|(m, _)| *m == id) {
return Err(format!("headless mark `{id}` is written twice"));
}
out.push((id, Headless { value, reach: Some(reach), why }));
}
Ok(out)
}
/// `yes` for an id the engine registry has, else its mark, else `unknown`.
pub fn headless_of<'a>(e: &Entry, marks: &[(&str, Headless<'a>)]) -> Headless<'a> {
if e.done {
return YES;
}
marks.iter().find(|(m, _)| *m == e.id).map_or(UNKNOWN, |(_, h)| *h)
}
/// Marks that name no catalog id, or an id the engine registry has (it would hide a `yes`).
pub fn mark_errors(src: &str, entries: &[Entry]) -> Vec<String> {
let marks = match parse_marks(src) {
Ok(m) => m,
Err(e) => return vec![e],
};
let mut errs = Vec::new();
for (id, _) in &marks {
match entries.iter().find(|e| e.id == *id) {
None => errs.push(format!("headless mark `{id}` is not a catalog id")),
Some(e) if e.done => errs.push(format!("headless mark `{id}` is stale: the engine registry has it, so it is `yes`")),
Some(_) => {}
}
}
errs
}
fn pct(done: usize, total: usize) -> f64 {
if total == 0 { 0.0 } else { 100.0 * done as f64 / total as f64 }
}
@@ -26,6 +109,12 @@ fn pct(done: usize, total: usize) -> f64 {
/// The markdown for docs/parity-checklist.md. Ids are counted once (the first catalog row wins), tabs keep
/// catalog order.
pub fn render(entries: &[Entry]) -> String {
render_with(entries, HEADLESS)
}
/// `render` with the given `HEADLESS`-format marks (bad marks are left out; `mark_errors` reports them).
pub fn render_with(entries: &[Entry], marks: &str) -> String {
let marks = parse_marks(marks).unwrap_or_default();
let mut seen: Vec<&str> = Vec::new();
let mut unique: Vec<&Entry> = Vec::new();
for e in entries {
@@ -50,6 +139,22 @@ pub fn render(entries: &[Entry]) -> String {
registers a command with the same id. This measures breadth only; the overall assessment (depth, \
fidelity, effort) is in [target-app-parity.md](target-app-parity.md).\n\n";
s += &format!("**Overall: {done} / {total} commands implemented ({:.1}%).**\n\n", pct(done, total));
let hs: Vec<Headless<'_>> = unique.iter().map(|e| headless_of(e, &marks)).collect();
let count = |v: &str| hs.iter().filter(|h| h.value == v).count();
let no = |r: &str| hs.iter().filter(|h| h.value == "no" && h.reach == Some(r)).count();
s += &format!(
"**Headless ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): {} yes, {} no \
(window {}, os {}, engine-gap {}), {} partial, {} unknown.** An implemented command is `headless: yes`: it is in the \
engine registry that `gridcraft-cli` and the MCP server load. A missing one carries its hand mark from `HEADLESS` in \
`xtask/src/parity.rs`, or `unknown`.\n\n",
count("yes"),
count("no"),
no("window"),
no("os"),
no("engine-gap"),
count("partial"),
count("unknown")
);
s += "| Tab | Implemented | Total | Parity |\n|---|---|---|---|\n";
for t in &tabs {
let rows: Vec<&&Entry> = unique.iter().filter(|e| e.tab == *t).collect();
@@ -61,7 +166,21 @@ pub fn render(entries: &[Entry]) -> String {
let d = rows.iter().filter(|e| e.done).count();
s += &format!("\n## {t} ({d} / {}, {:.0}%)\n", rows.len(), pct(d, rows.len()));
for (title, want) in [("Implemented", true), ("Missing", false)] {
let list: Vec<String> = rows.iter().filter(|e| e.done == want).map(|e| format!("- `{}` {} ({})", e.id, e.label, e.group)).collect();
let list: Vec<String> = rows
.iter()
.filter(|e| e.done == want)
.map(|e| {
let line = format!("- `{}` {} ({})", e.id, e.label, e.group);
if want {
return line;
}
let h = headless_of(e, &marks);
match h.reach {
Some(r) => format!("{line}: headless: {}, reach: {r} ({})", h.value, h.why),
None => format!("{line}: headless: {}", h.value),
}
})
.collect();
if !list.is_empty() {
s += &format!("\n{title}:\n\n{}\n", list.join("\n"));
}
@@ -109,7 +228,12 @@ pub fn run(root: &Path, args: &[&str]) -> Result<(), String> {
other => return Err(format!("parity: unknown argument `{other}` (usage: cargo xtask parity [--check] [--out PATH])")),
}
}
let text = render(&entries());
let entries = entries();
let errs = mark_errors(HEADLESS, &entries);
if !errs.is_empty() {
return Err(format!("parity: RFC-0052 headless marks in xtask/src/parity.rs:\n {}", errs.join("\n ")));
}
let text = render(&entries);
if check {
let current = std::fs::read_to_string(&out).map_err(|e| format!("{}: {e}", out.display()))?;
if !up_to_date(&current, &text) {
@@ -151,6 +275,38 @@ mod tests {
assert!(s.find("## File").unwrap_or(usize::MAX) < s.find("## Home").unwrap_or(0));
}
#[test]
fn headless_yes_comes_only_from_the_registry() {
let marks = "file.open|no|window|a dialog\n";
let s = render_with(&[e("file.new", "File", true), e("file.open", "File", false), e("home.bold", "Home", false)], marks);
assert!(s.contains("1 yes, 1 no (window 1, os 0, engine-gap 0), 0 partial, 1 unknown"), "{s}");
assert!(s.contains("- `file.open` FILE.OPEN (G): headless: no, reach: window (a dialog)"), "{s}");
assert!(s.contains("- `home.bold` HOME.BOLD (G): headless: unknown"), "{s}");
// A live id is `yes` whatever a mark says.
let parsed = parse_marks("file.new|no|os|x\n").unwrap_or_default();
assert_eq!(headless_of(&e("file.new", "File", true), &parsed).value, "yes");
}
#[test]
fn bad_marks_are_refused() {
for bad in ["a.b|yes|window|x", "a.b|no|desk|x", "a.b|no", "a.b|no|os|x\na.b|partial|os|y"] {
assert!(parse_marks(bad).is_err(), "{bad}");
}
let entries = [e("a.b", "T", true), e("c.d", "T", false)];
let errs = mark_errors("a.b|no|os|x\nz.z|no|os|y\nc.d|partial|engine-gap|z\n", &entries);
assert_eq!(errs.len(), 2, "{errs:?}");
assert!(errs.iter().any(|m| m.contains("`a.b` is stale")), "{errs:?}");
assert!(errs.iter().any(|m| m.contains("`z.z` is not a catalog id")), "{errs:?}");
assert_eq!(mark_errors("junk", &entries).len(), 1);
}
#[cfg(feature = "engine")]
#[test]
fn checked_in_marks_are_current() {
let errs = mark_errors(HEADLESS, &entries());
assert!(errs.is_empty(), "{errs:?}");
}
#[test]
fn empty_catalog_renders() {
assert!(render(&[]).contains("0 / 0 commands implemented (0.0%)"));